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?
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();
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.
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.
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
How about?
<?php $queried_post = get_page_by_path('my_slug',OBJECT,'post'); ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With