如何按类别显示最近/随机发布的帖子

时间:2019-04-23 作者:K H

尝试显示我的自定义帖子所属的每个类别中的随机帖子(它与2个类别相关)。我正在尝试按id获取帖子类别。我尝试手动放置类别id,但它仍然显示他类型中所有帖子的随机帖子。有人能帮我吗?

<?php
    $term_list = wp_get_post_terms( $post->ID, \'listing-category\', array( \'fields\' => \'ids\' ) );
    $args = array(
        \'post_type\' => \'listing\',
        \'category\' => $term_list[0],
        \'post_status\' => \'publish\',
        \'orderby\'   => \'rand\',
        \'posts_per_page\' => 3,
        );

    $the_query = new WP_Query( $args );

    if ( $the_query->have_posts() ) {
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            $rand_posts .= \'<li> <a href="\'. get_the_permalink() .\'">\'. get_the_title() .\'</a> </li>\';
        }
        echo $rand_posts;
        wp_reset_postdata();
    } 
?>

1 个回复
SO网友:Krzysiek Dróżdż

好的,如果你想从当前帖子分配到的每个类别中随机显示3篇帖子,那么。。。

首先,你应该循环浏览所有术语,并获得每个术语的随机帖子:

$term_list = wp_get_post_terms( $post->ID, \'listing-category\', array( \'fields\' => \'ids\' ) );
if ( $term_list && ! is_wp_error($term_list) ) {
    foreach ( $term_list as $term_id ) {
        // get random posts for given term
    }
}
目前,您从每个类别中随机获得帖子,因为您的查询有一个小缺陷:

$args = array(
    \'post_type\' => \'listing\',
    \'category\' => $term_list[0], // <- this works with built-in post categories, not your custom taxonomy called listing-category
    \'post_status\' => \'publish\',
    \'orderby\'   => \'rand\',
    \'posts_per_page\' => 3,
);
因此,您应该使用Tax\\u查询:

$args = array(
    \'post_type\' => \'listing\',
    \'post_status\' => \'publish\',
    \'orderby\' => \'rand\',
    \'posts_per_page\' => 3,
    \'tax_query\' => array(
        array( \'taxonomy\' => \'listing-category\', \'field\' => \'term_id\', \'terms\' => <TERM_ID> ), // change <TERM_ID> for real term
        // so in your code it\'s $term_list[0] and in my loop just $term_id
    )
);

相关推荐

Dropdown menu for categories

当我使用下面的代码时<?php wp_nav_menu( array(\'menu\' => \'categories\' )); ?> 我可以创建一个新的菜单来列出我创建的wordpress中的所有类别。我用它在页面中间列出所有类别。我现在的问题是:有没有一种简单的方法可以为存在的每个子类别创建下拉菜单?那么,当我点击一个特定的类别时,它的子类别会显示出来吗?