0

I'm trying to display 'related articles', I do this now like this:

                <?php
                    $exclude = get_the_ID();

                    $args = array(
                        'post_type' => 'article', 
                        'posts_per_page' => 3,
                    );
                    $your_query = new WP_Query( $args );

                    echo '<ul>';
                    while( $your_query->have_posts() ) : $your_query->the_post();
                        if( $exclude != get_the_ID() ) {
                            echo '<li><a href="' . get_permalink() . '">' .
                                get_the_title() . '</a></li>';
                        }
                    endwhile;
                    echo '</ul>';
                ?>

This works great.. But the custom post type 'articles' actually also has categories. So I'd like to only display links from within the same category.

This is where I'm stuck, I tried giving my args array a new line:

$category = get_the_category();

                    $args = array(
                        'post_type' => 'article', 
                        'posts_per_page' => 3,
                        'cat'=> $category 
                    );

But this doesn't do the trick.

Any suggestions?

1 Answer 1

0

You are using default category for custom post type. You can instead use a taxonomy query to get filtered result based upon your custom taxonomy terms.

Try this -

$cat_ids = array();

$postID = get_the_ID();

$categories = get_the_terms($postID, 'custom_taxonomy_name'); //this will give all the terms

foreach($categories as $cat) {
    $cat_ids[] = $cat->term_id; //you may put some condition and consider only some specific terms as per your requirement
}

$args = array(
                    'post_type' => 'article', 
                    'posts_per_page' => 3,
                    'tax_query' => array(array( 
                    'taxonomy' => 'custom_taxonomy_name',
                    'field' => 'id',
                    'terms' => $cat_ids //ids of specified terms
                    )
                  )
               );
2
  • Thanks for your reply! I tried to add your code and I'm getting no results though (yet there are 2 articles in the same category) do you see anything wrong here?: pastebin.com/sShZw2Nq
    – vlovsky
    Commented Aug 10, 2015 at 13:41
  • Nevermind found what was wrong, thank you so much!
    – vlovsky
    Commented Aug 10, 2015 at 13:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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