0

I'm using a related posts PHP WordPress query, but having trouble excluding categories. I've tried excluding via cat and category__not_in as well as both as and not as an array. What am I setting up incorrectly?

<?php $orig_post = $post;
    global $post;
    $categories = get_the_category($post->ID);
    if ($categories) {
    $category_ids = array();
    foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
    $args=array(
    'cat' => array(-6,-173,-174),
    'category__in' => $category_ids,
    'category__not_in' => (6, 173, 174),
    'post__not_in' => array($post->ID),
    'posts_per_page'=> 3, // Number of related posts that will be displayed.
    'orderby'=>'rand' // Randomize the posts
    );
    $my_query = new wp_query( $args );
    if( $my_query->have_posts() ) {
    echo '<ul class="realted-article">';
    while( $my_query->have_posts() ) {
    $my_query->the_post(); ?>
    <li>
     <a href="<?php the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>">
     </a>
     <div class="perfect-related_by-category">
        <strong><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></strong>
     <a href="<?php echo get_permalink();?>">   
        <?php if(get_field('summary_text')=='')
            {echo substr(strip_tags(get_the_content()),0,90);}
            else{echo strip_tags(get_field('summary_text'));}?>
     </a>
     </div>
    </li>
    <? }
    echo '</ul>';
    } }
    $post = $orig_post;
    wp_reset_query();
    ?>
  • cat does not accept an array, your category__not_in argument is missing array before the parentheses. – Milo Sep 16 '15 at 4:29
1

You can simple run a foreach loop and exclude the terms from your returned array of terms. Just a few notes

  • cat accepts a string or integer value, not and array

  • category__not_in should be an array

Here is a modified version of a related posts function I recently did here. Please go and check it out and check out how the $args parameter should be used, just remember, it has moved to the third paremeter in the new function ;-)

Here is the code (I have commented the code so you can follow it, it is untested though and requires PHP 5.4+)

function get_related_posts( $taxonomy = '', $exclude = [], $args = [] )
{
    /*
     * Before we do anything and waste unnecessary time and resources, first check if we are on a single post page
     * If not, bail early and return false
     */
    if ( !is_single() )
        return false;

    /*
     * Check if we have a valid taxonomy and also if the taxonomy exists to avoid bugs further down.
     * Return false if taxonomy is invalid or does not exist
     */
    if ( !$taxonomy ) 
        return false;

    $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );
    if ( !taxonomy_exists( $taxonomy ) )
        return false;

    /*
     * We have made it to here, so we should start getting our stuff togther. 
     * Get the current post object to start of
     */
    $current_post = get_queried_object();

    /*
     * Get the post terms
     */
    $terms = get_the_terms( $current_post->ID, $taxonomy );

    /*
     * Lets only continue if we actually have post terms and if we don't have an WP_Error object. If not, return false
     */
    if ( !$terms || is_wp_error( $terms ) )
        return false;

    // Define our array to hold the term id'saveHTML
    $term_ids = [];
    foreach ( $terms as $term ) {
        // Check if we have terms to exclude and exclude them
        if ( $exclude ) {
            if ( in_array( $term->id, $exclude ) )
                continue;
        } else {
            $term_ids[] = (int) $term->term_id;
        }
    /*
     * Set the default query arguments
     */
    $defaults = [
        'post_type' => $current_post->post_type,
        'post__not_in' => [$current_post->ID],
        'tax_query' => [
            [
                'taxonomy' => $taxonomy,
                'terms' => $term_ids,
                'include_children' => false
            ],
        ],
    ];

    /*
     * Validate and merge the defaults with the user passed arguments
     */
    if ( is_array( $args ) ) {
        $args = wp_parse_args( $args, $defaults );
    } else {
        $args = $defaults;
    }

    return $q;
}

You would use it as follow then

if ( function_exists( 'get_related_posts' ) ) {
    $related_posts = get_related_posts( 
        'my_taxonomy_name', // Taxonomy name, if build in, in should be 'category'
        [1, 2, 3] // Array of terms to exclude
    );
    if ( $related_posts ) {
        foreach ( $related_posts as $post ) {
            setup_postdata( $post ); 
            // Use your template tags and html mark up as normal like
            the_title();
            the_content();
            // etc etc
        }
        wp_reset_postdata();
    }
}
  • Function makes sense. Thanks, but I'm not getting any output using the default if statements you used above. – Keefer Sep 16 '15 at 19:54
  • You need to be more specific – Pieter Goosen Sep 16 '15 at 19:56
  • Putting the following in the sidebar, I see nothing output: if ( function_exists( 'get_related_posts' ) ) { $related_posts = get_related_posts( 'my_taxonomy_name', // Taxonomy name, if build in, in should be 'category' [1, 2, 3] // Array of terms to exclude ); if ( $related_posts ) { foreach ( $related_posts as $post ) { setup_postdata( $post ); // Use your template tags and html mark up as normal like the_title(); the_content(); // etc etc } wp_reset_postdata(); } } – Keefer Sep 16 '15 at 19:57
  • my_taxonomy_name need to be the exact taxonomy name of your taxonomy, if it is the build in categories, it need to be category, also [1, 2, 3] needs to be an array of the exact category ID's you need to exclude. Please reread my answer and comments in code – Pieter Goosen Sep 16 '15 at 20:01
  • 1
    Please read this, it should shed some light. On the code issue, simply file an edit and add all your code in your question, then leave a small a small note in comments to the answer you are targeting about the changes, this will make it easier to read :-) – Pieter Goosen Sep 16 '15 at 20:08

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.