获取同一分类中的帖子和输出帖子的自定义分类值

时间:2019-07-11 作者:user108167

我正在尝试在我的单个帖子模板上显示相关视频。我在帖子中设置了一个名为“子类别”的自定义分类法。我想获取当前帖子的子类别,并循环浏览具有相同子类别的任何帖子,将它们输出到页面。有没有关于实现这一目标的最佳方法的想法?

3 个回复
SO网友:Giang D.MAI

尝试使用此功能

function get_posts_in_taxonomy($post_type, $taxonomy, $term_id, $include_children=false, $limit)
{
$args = [
    \'post_type\'      => $post_type,
    \'posts_per_page\' => $limit,
    \'tax_query\' => [
        [
            \'taxonomy\'         => $taxonomy,
            \'terms\'            => $term_id,
            \'include_children\' => $include_children
        ],
    ],
    // Rest of your arguments
];

$posts = new WP_Query( $args );

if($posts->have_posts()) {
    while($posts->have_posts()) {
        $posts->the_post();

        //code todo here

    }
}
} //end func

SO网友:Oscprofessionals
function get_the_terms( $post, $taxonomy ) {
if ( ! $post = get_post( $post ) ) {
    return false;
}

$terms = get_object_term_cache( $post->ID, $taxonomy );
if ( false === $terms ) {
    $terms = wp_get_object_terms( $post->ID, $taxonomy );
    if ( ! is_wp_error( $terms ) ) {
        $term_ids = wp_list_pluck( $terms, \'term_id\' );
        wp_cache_add( $post->ID, $term_ids, $taxonomy . \'_relationships\' );
    }
}

/**
 * Filters the list of terms attached to the given post.
 *
 * @since 3.1.0
 *
 * @param WP_Term[]|WP_Error $terms    Array of attached terms, or WP_Error on failure.
 * @param int                $post_id  Post ID.
 * @param string             $taxonomy Name of the taxonomy.
 */
$terms = apply_filters( \'get_the_terms\', $terms, $post->ID, $taxonomy );

if ( empty( $terms ) ) {
    return false;
}

return $terms;}
SO网友:user108167

我想我把自己弄糊涂了事实上,我是这样做的:

$_terms = wp_get_post_terms($post->ID, \'sub-category\', array("fields" => "all"));
        foreach ($_terms as $term) :
            $term_slug = $term->slug;
            $_posts = new WP_Query( array(
                        \'post_type\'         => \'post\',
                        \'posts_per_page\'    => 4,
                        \'tax_query\' => array(
                            array(
                                \'taxonomy\' => \'sub-category\',
                                \'field\'    => \'slug\',
                                \'terms\'    => $term_slug,
                            ),
                        ),
                    ));
            if( $_posts->have_posts() ) :
                while ( $_posts->have_posts() ) : $_posts->the_post();
                    //Output
                endwhile;
            endif;
            wp_reset_postdata();
            endforeach;

相关推荐

Get category url in loop

我需要获取类别url,以便将其放入元代码段中。现在,span内的输出是带有url的标记。我只需要获取不带标记的url,并将其放入$cat\\u display中。我尝试使用2个选项,但会看到一个错误:注意:尝试获取非对象的属性// Get post category info $category = get_the_category(); if(!empty($category)) { // Get last category post is in