How do I query a custom post type with a custom taxonomy?

For some reason I’m finding it a struggle to grab any posts using a custom taxonomy… can anyone unravel my stupidity?

$args = array(
    'post_type' => 'adverts',
    'advert_tag' => 'politics' // Doesn't seem to work.
);

query_posts($args); 

while ( have_posts() ) : the_post();
    //Show Posts
endwhile;

Taxonomy Declaration:

add_action( 'init', 'add_custom_taxonomy', 0 );
function add_custom_taxonomy() {
    register_taxonomy('advert_tag', 'Adverts', 
        array(
            'hierarchical' => true,
            'labels' => array(
            'name' => _x( 'Advert Tags', 'taxonomy general name' ),
            'singular_name' => _x( 'Advert Tag', 'taxonomy singular name' ),
            'search_items' =>  __( 'Search Advert Tags' ),
            'all_items' => __( 'All Advert Tags' ),
            'parent_item' => __( 'Parent Advert Tag' ),
            'parent_item_colon' => __( 'Parent Advert Tag:' ),
            'edit_item' => __( 'Edit Advert Tag' ),
            'update_item' => __( 'Update Advert Tag' ),
            'add_new_item' => __( 'Add New Advert Tag' ),
            'new_item_name' => __( 'New Advert Tag Name' ),
            'menu_name' => __( 'Advert Tags' ),
        ),
        'rewrite' => array(
            'slug' => 'advert-tags',
            'with_front' => false,
            'hierarchical' => true
        ),
    );
}

Custom Post Type Declaration:

add_action( 'init', 'create_post_type' );
function create_post_type() {
    register_post_type( 'Adverts',
        array(
            'labels' => array(
                'name' => __( 'Adverts' ),
                'singular_name' => __( 'Advert'),
                'add_new' => __( 'Add New' ),
                'add_new_item' => __( 'Add a New Advert' ),
                'edit' => __( 'Edit' ),
                'edit_item' => __( 'Edit Advert' ),
                'new_item' => __( 'New Advert' ),
                'view' => __( 'View' ),
                'view_item' => __( 'View Advert' ),
                'search_items' => __( 'Search Adverts' ),
                'not_found' => __( 'No Adverts found' ),
                'not_found_in_trash' => __( 'No Adverts found in Trash' ),
            ),
            'supports' => array(
                'title',
                'thumbnail',
            ),
            'has_archive' => true,
            'menu_position' => 10,
            'public' => true,
            'rewrite' => array( 
                'slug' => 'adverts' 
            ),
            'taxonomies' => array('advert_tag')
        )
    );
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Firs of all don’t use query_posts() ever, read more about it here: When should you use WP_Query vs query_posts() vs get_posts()?.

You have to use WP_Query to fetch posts what you need. Read documentation for it. In your case the query could be like this:

$the_query = new WP_Query( array(
    'post_type' => 'Adverts',
    'tax_query' => array(
        array (
            'taxonomy' => 'advert_tag',
            'field' => 'slug',
            'terms' => 'politics',
        )
    ),
) );

while ( $the_query->have_posts() ) :
    $the_query->the_post();
    // Show Posts ...
endwhile;

/* Restore original Post Data 
 * NB: Because we are using new WP_Query we aren't stomping on the 
 * original $wp_query and it does not need to be reset.
*/
wp_reset_postdata();

Method 2

i am using this query to fetch custom posts (FAQs Posts) with its custom taxonomy (faq_category). since {taxonomy} parameter in WP_Query args was deprecated since v.3.1 and introduced {tax_query}. below is the code that works perfectly.

$query = new WP_Query( array(
    'post_type' => 'faqs',          // name of post type.
    'tax_query' => array(
        array(
            'taxonomy' => 'faq_category',   // taxonomy name
            'field' => 'term_id',           // term_id, slug or name
            'terms' => 48,                  // term id, term slug or term name
        )
    )
) );

while ( $query->have_posts() ) : $query->the_post();
    // do stuff here....
endwhile;

/**
 * reset the orignal query
 * we should use this to reset wp_query
 */
wp_reset_query();

Method 3

Here the code that works like magic. I am fetching all posts for the custom post_type “university_unit” with custom taxonomy “unit_type” and multiple taxonomy terms as “directorate” and “office”.
I hope it helps out.

<?php
$args = array(
    'post_type' => 'university_unit',
    'posts_per_page' => -1,
    'orderby' => 'title',
    'order' => 'ASC',
    'tax_query' => array(

        array(
            'taxonomy' => 'unit_type',
            'field' => 'slug',
            'terms' => array('directorate', 'office')
        )

    )
);

$Query = new WP_Query($args);
if($Query -> have_posts()):

    while($Query -> have_posts()):
        $Query -> the_post();
        ?>
        <div class="cm-post-list-item">
            <article>
                <div class="cm-post-head">
                    <h3 class="cm-text-blue">
                        <a href="<?php the_permalink(); ?>" rel="nofollow noreferrer noopener"><?php the_title();?></a>
                    </h3>
                </div>
                <div class="cm-post-body"><?php the_excerpt();?></div>
            </article>
        </div>
        <?php
    endwhile;

else:
    "No Administrative Offices Found. Try again later";
endif;
wp_reset_postdata();
?>

Method 4

This helped me to get all posts listed under each term for custom taxanomy for CPT

    <?php
    // Get list of all taxonomy terms  -- In simple categories title
    $args = array(
                'taxonomy' => 'project_category',
                'orderby' => 'name',
                'order'   => 'ASC'
            );
    $cats = get_categories($args);

    // For every Terms of custom taxonomy get their posts by term_id
    foreach($cats as $cat) {
        ?>
        <a href="<?php echo get_category_link( $cat->term_id ) ?>" rel="nofollow noreferrer noopener">
            <?php echo $cat->name; ?> <br>
            <?php // echo $cat->term_id; ?> <br>
        </a>


            <?php
                // Query Arguments
                $args = array(
                    'post_type' => 'portfolio', // the post type
                    'tax_query' => array(
                        array(
                            'taxonomy' => 'project_category', // the custom vocabulary
                            'field'    => 'term_id',          // term_id, slug or name  (Define by what you want to search the below term)    
                            'terms'    => $cat->term_id,      // provide the term slugs
                        ),
                    ),
                );

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

                // The Loop
                if ( $the_query->have_posts() ) {
                    echo '<h2> List of posts tagged with this tag </h2>';

                    echo '<ul>';
                    $html_list_items = '';
                    while ( $the_query->have_posts() ) {
                        $the_query->the_post();
                        $html_list_items .= '<li>';
                        $html_list_items .= '<a href="' . get_permalink() . '" rel="nofollow noreferrer noopener">';
                        $html_list_items .= get_the_title();
                        $html_list_items .= '</a>';
                        $html_list_items .= '</li>';
                    }
                    echo $html_list_items;
                    echo '</ul>';

                } else {
                    // no posts found
                }

                wp_reset_postdata(); // reset global $post;

                ?>

    <?php } ?>

Method 5

This answer now is not valid anymore since wordpress changes their taxonomy parameter information. please use this way. It will work. It works for me. “tax_query” replaces with “tax”. hope it will work.

$the_query = new WP_Query( array(
    'post_type' => 'Adverts',
    'tax' => array(
        array (
            'taxonomy' => 'advert_tag',
            'field' => 'slug',
            'terms' => 'politics',
        )
    ),
) );

while ( $the_query->have_posts() ) :
    $the_query->the_post();
    // Show Posts ...
endwhile;

/* Restore original Post Data 
 * NB: Because we are using new WP_Query we aren't stomping on the 
 * original $wp_query and it does not need to be reset.
*/
wp_reset_postdata();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x