1

I have 3 categories (music , song, jpop) now and wanna remove song and jpop categories from related post.

How can I do it ?

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

from looking at https://developer.wordpress.org/reference/functions/wp_get_post_terms/

and https://developer.wordpress.org/reference/classes/wp_term_query/__construct/ for corresponding parameters, i.e. the 'exclude' parameter

and https://developer.wordpress.org/reference/functions/get_category_by_slug/ to get the category ids from their slugs.

it might work when you replace this line in your code:

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

with this example code:

// 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’ ) );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.