0

I am trying to listing posts from a single category with custom taxonomy and several sub custom taxonomies.

sub custom taxonomy "Knowledgebase"

  • post KB 1
  • post KB 2

sub custom taxonomy "Optimization "

  • post OP 1

but result is repeat post list not by custom taxonomy:

sub custom taxonomy "Knowledgebase"

  • post KB 1
  • post KB 2
  • post OP 1

sub custom taxonomy "Optimization"

  • post KB 1
  • post KB 2
  • post OP 1

eg. code:

$taxonomies = get_terms(
                array(
                    'taxonomy'   => 'tutorial',
                    'hide_empty' => false,
                )
            );

    // Loop through categories
    foreach ( $taxonomies as $taxonomy ) {

        // Display Taxonomy name
        echo '<h2 class="post-title">' . $taxonomy->name . '</h2>';
        echo '<div class="post-list">';

        // WP_Query arguments
        $args = array(
            'cat'           => 2, // wordpress category
            'terms'         => name,
            'orderby'       => 'term_order',
        );

        // The Query
        $query = new WP_Query( $args );

        // The Loop
        if ( $query->have_posts() ) {
            while ( $query->have_posts() ) {
                $query->the_post();
        ?>
            <p><a href="<?php the_permalink();?>"><?php the_title(); ?></a></p>
        <?php

            } // End while
        } // End if
1
  • as per your shared code it seems like you do not closed foreach correctly
    – BlueSuiter
    Nov 7, 2019 at 4:52

1 Answer 1

0

Your post list is repeating because in your WP_Query args you are fetching posts just from the category with ID "2".

In order to get posts from custom taxonomies you need to use a tax_query inside your WP_Query. You can read more about tax_query here: https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters

I would do the following:

$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        'relation' => 'OR',
        array(
            'taxonomy' => 'category',
            'field'    => 'term_id',
            'terms'    =>  2,//Your Wordpress category here
        ),
        array(
            'taxonomy' => 'tutorial',
            'field'    => 'term_id',
            'terms'    =>  $taxonomy->term_id,
        ),
    ),
);
$query = new WP_Query( $args );
1
  • Hi giannisrig, Thx for time & help. I've tried it, but the results remain the same. Can you help me more?
    – Julham
    Nov 8, 2019 at 7:09

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.