简体   繁体   English

显示CPT每种分类法的最新帖子

[英]Display most recent post of each taxonomy for a CPT

I'm trying to display the most recent posts from each custom taxonomy. 我正在尝试显示每个自定义分类法的最新帖子。 The CPT is for 'member-services' and the taxonomy is 'services'. CPT用于“成员服务”,而分类法则用于“服务”。

Currently trying to combine two ( Getting Custom Taxonomies and Getting Posts under Custom Taxonomy ) scripts I've found online. 目前,我在网上尝试将两个脚本(“ 获取自定义分类法”和“ 在自定义分类法下获取帖子” )组合在一起。

I'm unsure where I'm going wrong. 我不确定我要去哪里。

<!-- Add in list of member services -->
<?php // Get the taxonomy's terms
    $terms = get_terms(
        array(
            'taxonomy'   => 'services',
            'hide_empty' => false,
        )
    );
    // Check if any term exists
    if ( ! empty( $terms ) && is_array( $terms ) ) {
        // Run a loop and print them all
        foreach ( $terms as $term ) { ?>
            <a href="<?php echo esc_url( get_term_link( $term ) ) ?>">
                <?php echo $term->name; ?>
            </a>
<?php
        $post_args = array(
            'numberposts' => 5,
            'post_type' => 'services',
            'services' => $term->term_id,
            );
        $posts = get_posts($post_args);
        foreach($posts as $post) {
            ?>
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php   
        }
        }
    } 
?>

Real world logic: Show most recent member-services (CPT) offered under custom taxonomies - 'product', 'price', etc on home page. 现实世界的逻辑:在首页上显示根据自定义分类法提供的最新会员服务(CPT)-“产品”,“价格”等。

Currently: Shows list of custom taxonomies, so get_terms seems to be working. 当前:显示自定义分类法列表,因此get_terms似乎有效。

Yes your get_terms is working but your get_posts is not working because you have passed taxonomy name in post_type. 是的,您的get_terms有效,但您的get_posts不起作用,因为您已在post_type中传递了分类名称。 I have done some changes in your code. 我已经对您的代码进行了一些更改。 May be this will work for you 也许这会为你工作

        <?php
        $post_args = array(
            'posts_per_page' => 5,
            'post_type' => 'member-services',
            'orderby' => 'date',
            'sort_order' => 'desc',
            'tax_query' => array(
                array(
                    'taxonomy' => 'services',
                    'field' => 'id',
                    'terms' => $term->term_id,
                    'include_children' => false
                )
            )
        );
        $posts = get_posts($post_args);
        ?>

You have to write tax_query in get_posts() functions. 您必须在get_posts()函数中编写tax_query。

Just Replace 只需更换

'services' => $term->term_id, '服务'=> $ term-> term_id,

with

'tax_query' => array( array( 'taxonomy' => 'services', 'field' => 'id', 'terms' => $term->term_id ) ) 'tax_query'=>数组(array('taxonomy'=>'services','field'=>'id','terms'=> $ term-> term_id))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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