从相关帖子中删除特定类别ID

时间:2018-06-04 作者:Taka

我现在有3个类别(音乐、歌曲、jpop),我想从相关帖子中删除歌曲和jpop类别。

我该怎么做?

if ( get_theme_mod(‘related-posts-on’, true) ) :

    // Get the taxonomy terms of the current page for the specified taxonomy.
    $terms = wp_get_post_terms( get_the_ID(), ‘category’, array( ‘fields’ => ‘ids’ ) );

    // Bail if the term empty.
    if ( empty( $terms ) ) {
        return;
    }

    // Posts query arguments.
    $query = array(
        ‘post__not_in’ => array( get_the_ID() ),
        ‘tax_query’ => array(
            array(
                ‘taxonomy’ => ‘category’,
                ‘field’ => ‘id’,
                ‘terms’ => $terms,
                ‘operator’ => ‘IN’
            )
        ),
        ‘posts_per_page’ => 6,
        ‘post_type’ => ‘post’,
    );

1 个回复
SO网友:Michael

从查看https://developer.wordpress.org/reference/functions/wp_get_post_terms/

https://developer.wordpress.org/reference/classes/wp_term_query/__construct/ 对应参数,即“排除”参数

https://developer.wordpress.org/reference/functions/get_category_by_slug/ 从Slug中获取类别ID。

当您在代码中替换此行时,它可能会起作用:

// Get the taxonomy terms of the current page for the specified taxonomy. 
$terms = wp_get_post_terms( get_the_ID(), ‘category’, array( ‘fields’ => ‘ids’ ) );
使用此示例代码:

// Get the catogory ids of the two categories to be excluded
$cat1 = get_category_by_slug( \'song\' ); 
$cat2 = get_category_by_slug( \'jpop\' ); 
// Get the taxonomy terms of the current page for the specified taxonomy and exclude two categories
$terms = wp_get_post_terms( get_the_ID(), ‘category’, array( \'exclude\' => array( $cat1->term_id, $cat2->term_id ), ‘fields’ => ‘ids’ ) );

结束

相关推荐

Media Library Categories

我使用以下内容将类别分配给我的WordPress媒体库(在functions.php):function wptp_add_categories_to_attachments() { register_taxonomy_for_object_type( \'category\', \'attachment\' ); } add_action( \'init\' , \'wptp_add_categories_to_attachments\' ); 每个媒体库项目都