• I need help troubleshooting a query that isn’t working.

    I have Posts (standard WP blog post) and two Custom Post Types (‘Resorts’ and ‘Deals’) and am trying to show the related Deals and Posts on the page that is the single Resort. All three have the same custom taxonomy (term) applied (which is ‘Applicable Resorts’ – I’ve used the print_r function to verify), but the Deals and Posts are not showing up.

    I’ve made sure that when I registered the custom taxonomy, it applies to all post types (‘post’,’resort’,’deal’) and that when the CPTs are registered, they support the custom taxonomy (‘applicable_resort’).

    Here is the query that is supposed to display related Posts:

    // Creates loop of blog posts related to current page/post by Taxonomy
    function echo_related_posts() {
        global $post;
        // Get the current post's tags
    	$tags = wp_get_post_terms( $post->ID, 'applicable_resort', array("fields" => "all") );
        $tagIDs = array();
    
        if ( $tags ) {
            // Fill an array with the current post's tag ids
            $tagcount = count( $tags );
            for ( $i = 0; $i < $tagcount; $i++ ) {
                $tagIDs[$i] = $tags[$i]->term_id;
            }
            // Query options, the magic is with 'tag__in'
            $args = array(
                'post_type' => 'post',
                'tag__in' => $tagIDs,
                'post__not_in' => array( $post->ID ),
                'showposts'=> 4
            );
            $my_query = new WP_Query( $args );
            // If we have related posts, show them
            if ( $my_query->have_posts() ) {
            $related = '';
                while ( $my_query->have_posts() ) {
    		$my_query->the_post();
                    $current = $my_query->current_post + 1;
                    $related .= "<li><a href='" . get_permalink() . "' >";
                    $related .= get_the_title();
                    $related .= "</a></li>";
                    if ( ( $my_query->current_post + 1 ) != ( $my_query->post_count ) ) $related;
               }
                echo $related;
            }
            else echo "<li>No Posts</li>";
        wp_reset_query();
        }
    }

    When I use the snippet echo related_posts, I get the “No Posts” message, even though I am certain I have Posts that should be displayed.

    I am not a coder, so all of the above I have cobbled together from various other sources, examples, and the Codex….a lot of sources online are very old (many use the ‘caller_get_posts’ that has been deprecated for years), so I’ve tried to be sure this uses current functions….but I’ve been at this for days and cannot find the fault in it.

    Can anyone spot why this might not work?

  • The topic ‘Relating CPTs by taxonomy not working’ is closed to new replies.