简体   繁体   中英

How to get a Wordpress post by Id using query_posts

I am trying to load a post by ID using query_posts, however it always returns an empty array. I get a post Id at random using SQL as follows;

$randomProdSql = "SELECT ID FROM `posts` WHERE post_status = 'publish' ORDER BY RAND() LIMIT 0,1";

I then load that into a variable using;

$randomPost = $wpdb->get_var($randomProdSql);

This works fine and if I print it out I get an Id. I then call query_posts like this;

$args = array(
    'p' => $randomPost
);

$posts = query_posts($args);

I would now expect the $posts variable to contain the post.. however, if I call;

print_r($args);
print_r($posts);

I get:

Array
(
    [p] => 778
)
Array
(
)

Can anyone see what I am doing wrong?

Update your code as below:

query_posts('p='.'"$randomPost"');

Also, rather using the query_posts() method to get a single post, you can use get_post() method.

$my_post = get_post($randomPost);
echo $my_post->post_title;

As per your code, you shared you want post id's in random manner. The following code will get the post id's for you in random manner.

By using post_per_page you can control the number of posts returned in result. Also, fields will force the query to return id's of posts. However, in case you want to retrieve any other field also please remove it from here. As, it only supports id field only.

For details please refer to this link :

<?php 
    $args = array(
        'post_status' => 'publish',
        'orderby' => 'rand',
        'fields' => 'ids',
        'posts_per_page' => '1'
    );

    $posts = query_posts($args);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM