Viewing 5 replies - 1 through 5 (of 5 total)
  • Plugin Author keesiemeijer

    (@keesiemeijer)

    Hi astpaul

    Including and excluding terms is a bit tricky. What the plugin does is it gets the current post terms and removes the (exclude) terms from the terms found. Then it searches for related posts with the remaining terms and orders them by relatedness. The found posts however can still have one or more of the excluded terms. It’s a mind bender ??

    If you really need to exclude all posts with any of the excluded terms parameter you’ll have to use the exclude_posts parameter.

    Try it with this in your theme’s functions.php

    add_filter( 'related_posts_by_taxonomy_shortcode_atts', 'related_posts_exclude_terms_strict' );
    
    function related_posts_exclude_terms_strict( $args ) {
    	global $wpdb;
    
    	if ( empty( $args['exclude_terms'] )  ) {
    		return $args;
    	}
    
    	// sanitize the excluded terms
    	$exclude_terms = explode( ',', (string) $args['exclude_terms'] );
    	$exclude_terms = array_filter( array_map( 'intval', $exclude_terms ) );
    	$exclude_terms = array_values( array_unique( $exclude_terms ) );
    
    	$term_ids_sql = "tt.term_id IN (" . implode( ', ', $exclude_terms ) . ")";
    
    	$query = "
    		SELECT p.ID FROM $wpdb->posts p
    		LEFT JOIN $wpdb->term_relationships t ON (p.ID = t.object_id)
    		WHERE exists (
            	SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy tt
            	WHERE tt.term_taxonomy_id = t.term_taxonomy_id
            	and {$term_ids_sql}
        	) GROUP BY p.ID
    	";
    
    	// get post ids with the excluded terms
    	$results = $wpdb->get_col( $query );
    
    	if ( !empty( $results ) ) {
    		$args['exclude_posts'] = $results;
    	}
    
    	// return arguments with the excluded posts
    	return $args;
    }

    btw:
    consider creating a child theme instead of editing your theme directly – if you upgrade the theme all your modifications will be lost. Or create a plugin with the code above.

    Thread Starter astpaul

    (@astpaul)

    Awesome!

    And do I use wp_terms.term_id as number or the corresponding wp_7t86sf0zdh_term_taxonomy.term_taxonomy_id with that exclude_posts parameter?

    Plugin Author keesiemeijer

    (@keesiemeijer)

    With the code in your theme’s functions.php
    you can just use the term ids you want to exclude in the shortcode (exclude_terms="58").

    [related_posts_by_tax posts_per_page="6" format="thumbnails" order="RAND" post_types="post,product" columns="2" title="My Related Quotes" before_title="<h4>" after_title="</h4>" exclude_terms="58" taxonomies="category,post_tag"]
    Thread Starter astpaul

    (@astpaul)

    Forgot to say thank you ??

    Plugin Author keesiemeijer

    (@keesiemeijer)

    No problem ??

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Excude category’ is closed to new replies.