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?

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
                    )
                  )
               );
  • 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 Aug 10 '15 at 13:41
  • Nevermind found what was wrong, thank you so much! – vlovsky Aug 10 '15 at 13:48

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.