![](/img/trans.png)
[英]Looping to organize and display custom posts by category using PHP and WordPress
[英]PHP: How to display posts of specific category using a custom query in WordPress?
我没有使用WP语言,但是使用了简单的PHP,现在我的代码是
SELECT * FROM wp_posts w
WHERE w.post_status = 'publish'
AND w.post_type = 'post'
ORDER BY RAND()
LIMIT 3
因此,我可以在我的自定义首页(而非WP)上显示3条随机博客文章,它可以正常工作。
但现在我想选择一个特定的类别
我该怎么做?
query_posts('cat=123');
这可以解决特定类别的问题。 如果类别具有名称,则将值等于名称。 虽然,建议使用类别ID(如果以后进行更改)。
您实际上不应该使用SQL查询,而应该使用WP_Query对象或query_posts函数。
您的查询应如下所示:
$posts = new WP_Query(array(
'orderby' => rand,
'posts_per_page' => 3,
'post_status' => 'publish',
'cat' => 123
));
如果您在首页上使用此功能,则“ query_posts”功能更合适:
query_posts(array(
'orderby' => rand,
'posts_per_page' => 3,
'post_status' => 'publish',
'cat' => 123
));
在这种情况下,类别ID为“ 123”,但是您可以在此处使用任何类别参数 。
global $wpdb;
$posts = $wpdb->get_results('SELECT ID, post_title AS title, post_excerpt AS excerpt FROM '.$wpdb->posts.' WHERE post_type = "post" AND post_status = "publish" ORDER BY post_date DESC LIMIT 5');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.