类别和随机帖子中的WP_Query
I'm developing a "related posts" kind of plugin and want to show random related posts in specific category. That's the easy part and I'm doing it like this:
$args=array(
'category__in' => $categories,
'showposts' => $post_count,
'orderby' => 'rand',
);
$related_query = new WP_Query($args);
Now my problem is that the post count is not always met and I want the query to always return the number of posts specified.
For example, my $post_count is 4 but the category we're querying only returns 2 posts. I want the rest to fill in with random posts.
The easiest solution would be to check if the number of returned posts is equal to 4. If not, create another query for posts from all categories except the ones in $categories
. The count there should be (4 - the number of results from the first query)
. This way, you'll always get 4 posts, and posts from the specified categor(y/ies) would show up first.