WordPress single post request by slug

At the moment when I want to show one 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 identifier usually changes. Is there any way to request this message by a slug?

+64
php wordpress
Feb 20 '13 at 12:26
source share
4 answers

From 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

+92
Feb 20 '13 at 12:59
source share
— -

What about?

 <?php $queried_post = get_page_by_path('my_slug',OBJECT,'post'); ?> 
+59
Apr 21 '15 at 10:58
source share

less expensive and reusable method

 function get_post_id_by_name( $post_name, $post_type = 'post' ) { $post_ids = get_posts(array ( 'post_name' => $post_name, 'post_type' => $post_type, 'numberposts' => 1, 'fields' => 'ids' )); return array_shift( $post_ids ); } 
+5
Apr 03 '16 at 9:39
source share

Since the WordPress API has changed, you cannot use get_posts with the "post_name" parameter. I changed the Martens function a bit:

 function get_post_id_by_slug( $slug, $post_type = "post" ) { $query = new WP_Query( array( 'name' => $slug, 'post_type' => $post_type, 'numberposts' => 1, 'fields' => 'ids', ) ); $posts = $query->get_posts(); return array_shift( $posts ); } 
+2
Jan 30 '18 at 10:26
source share



All Articles