Search code examples
wordpresscustom-post-type

Display posts based on CPT category Name


I have post type named 'service'. It has two categories 'Left' & 'Right' I wish to display all posts of 'Left' category. Here's my code

<?php
    $args = array (
    'post_type'              => 'service',
    'post_status'            => 'publish',
    'order'                  => 'ASC',
    'category_name' => 'Left',
    'posts_per_page'=>-1
    );
    $posts = new WP_Query( $args );
    if ( $posts->have_posts() ) {

    while ( $posts->have_posts() ) {
    $posts->the_post();
    //$image11 = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );

?>

    <li><a href="<?php the_permalink(); ?>"><i class="fa fa-file-text"></i> <?php the_title(); ?></a></li>

 <?php  } } wp_reset_postdata(); ?>

The above code returns nothing.


Solution

  • Please try with below:

    On the $args Array please use the Left category ID insted of category_ID on "category" column.

    <?php
    $args = array (
        'post_type'  => 'service',
        'post_status' => 'publish',
        'order' => 'ASC',
        'category' => 'category_ID',
        'posts_per_page' =>-1
    );
    
    $posts = new WP_Query( $args );
    if ( $posts->have_posts() ) {
        while ( $posts->have_posts() ) {
            $posts->the_post();
            //$image11 = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
            ?>
            <li>
                <a href="<?php the_permalink(); ?>">
                    <i class="fa fa-file-text"></i> 
                    <?php the_title(); ?>
                </a>
            </li>
            <?php  
        } 
    } 
    wp_reset_postdata();
    ?>