Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress query single post by slug

Tags:

php

wordpress

For the moment when I want to show a single post without using a loop I use this:

<?php $post_id = 54; $queried_post = get_post($post_id); echo $queried_post->post_title; ?> 

The problem is that when I move the site, the id's usually change. Is there a way to query this post by slug?

like image 390
George Oiko Avatar asked Feb 20 '13 12:02

George Oiko


People also ask

How do I query custom post type in WordPress?

You can query posts of a specific type by passing the post_type key in the arguments array of the WP_Query class constructor. $loop ->the_post();

What is WP_Query?

WP_Query is a class defined in WordPress. It allows developers to write custom queries and display posts using different parameters. It is possible for developers to directly query WordPress database. However, WP_Query is one of the recommended ways to query posts from WordPress database.

How do I find page slugs in WordPress?

Most simply, a post's or page's slug can be retrieved by accessing the global post object's post_name property. The first method shown below accesses that post_name property within the $post variable while the second option below uses the get_post_field method.


2 Answers

From the WordPress Codex:

<?php $the_slug = 'my_slug'; $args = array(   'name'        => $the_slug,   'post_type'   => 'post',   'post_status' => 'publish',   'numberposts' => 1 ); $my_posts = get_posts($args); if( $my_posts ) :   echo 'ID on the first post found ' . $my_posts[0]->ID; endif; ?> 

WordPress Codex Get Posts

like image 140
ztirom Avatar answered Oct 05 '22 13:10

ztirom


How about?

<?php    $queried_post = get_page_by_path('my_slug',OBJECT,'post'); ?> 
like image 29
Mike Garcia Avatar answered Oct 05 '22 12:10

Mike Garcia