WordPress query single post by slug

PhpWordpress

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

How about?

<?php
   $queried_post = get_page_by_path('my_slug',OBJECT,'post');
?>

Solution 3 - Php

a 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 );
}

Solution 4 - Php

As wordpress api has changed, you can´t use get_posts with param 'post_name'. I´ve modified Maartens 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 );
}

Solution 5 - Php

<?php    
$page = get_page_by_path('slug', ARRAY_N);
echo $page->post_content

function get_id_by_slug($page_slug) {
      $page = get_page_by_path($page_slug, ARRAY_N);
      if ($page[0] > 0) {
        return $page[0];
      }else{
        return null;
      }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGeorge OikoView Question on Stackoverflow
Solution 1 - PhpztiromView Answer on Stackoverflow
Solution 2 - PhpMike GarciaView Answer on Stackoverflow
Solution 3 - PhpMaarten MentenView Answer on Stackoverflow
Solution 4 - PhpNurickanView Answer on Stackoverflow
Solution 5 - PhpKarra MaxView Answer on Stackoverflow