显示 CPT 每个分类的最新 post

Display most recent post of each taxonomy for a CPT

我正在尝试显示每个自定义分类的最新帖子。 CPT 用于 'member-services',分类法为 'services'。

目前正在尝试合并我在网上找到的两个 ( and Getting Posts under Custom Taxonomy) 脚本。

我不确定我哪里出错了。

<!-- 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   
        }
        }
    } 
?>

现实世界的逻辑: 在主页上显示自定义分类法下提供的最新会员服务 (CPT) - 'product'、'price' 等。

目前: 显示自定义分类列表,因此 get_terms 似乎有效。

是的,您的 get_terms 正在工作,但您的 get_posts 不工作,因为您已经在 post_type 中传递了分类法名称。 我对您的代码做了一些更改。也许这对你有用

        <?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);
        ?>

您必须在 get_posts() 函数中编写 tax_query。

只需替换

'services' => $term->term_id,

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