How to Pass Current Taxonomy Terms into new WP_Query?

On my single portfolio pages, I want to add a “See more from this category” section under the post.

Here is my code that checks for the single CPT and creates the new query:

add_action( 'genesis_loop', 'bds_more_projects_query' );
    function bds_more_projects_query() {
        if ( is_singular( 'portfolio' ) ) {
            $categories = get_the_terms( $post->ID, 'portfolio_category' );
            $args = array(
                'post_type' => 'portfolio',
                'posts_per_page' => 4,
                'tax_query' => array(
                    array(
                        'taxonomy' => 'portfolio_category',
                        'field' => 'name',
                        'terms' => array( $categories ),
                    ),
                ),
            );
            $loop = new WP_Query( $args );
            if ( $loop->have_posts() ) {
                while ( $loop->have_posts() ) : $loop->the_post();
                echo the_title();
                endwhile;
            }
            wp_reset_postdata();
        }
    }

When I manually type in a term string, the appropriate titles all echo out as desired, but I cannot get the “get_the_terms” function to work for dynamic display of the current post category.

What am I missing is my code?

Read more here: How to Pass Current Taxonomy Terms into new WP_Query?

Leave a Reply

Your email address will not be published. Required fields are marked *