Search code examples
phpwordpresscustom-post-type

is_category not fetching data inside a loop with custom post type in wordpress


<div class="row sub_content">
    <div class="col-md-12 col-lg-12">
        <div class="dividerHeading">
            <h4><span>Services, that vitsol provide you</span></h4>
        </div>
    </div>
    <?php

         $args = array(

                       'post_type' => 'topvitsolservice',
                       'posts_per_page' => 3
         );

         $vitsol_posts = new WP_Query($args);
         if($vitsol_posts->have_posts() ): while($vitsol_posts-> have_posts() ): $vitsol_posts->the_post();

    ?>
    <div class="col-sm-4">
        <div class="serviceBox_4">
            <div class="service-icon">
              <?php
                        if(is_category('web-designing')){
                            // Some Icon
                            echo '<i class="fa fa-globe"></i>';

                        } else if(is_category('mobile-apps-development')) {
                            // Another Icon
                            echo '<i class="fa fa-icon"></i>';
                        } else {
                           echo '<i class="fa fa-somefallback"></i>';
                        }

              ?>
                <!--<i class="fa fa-signal"></i>-->
            </div>
            <div class="service-content">
                <h3><?php the_title();  ?></h3>
                <p><?php the_excerpt();  ?></p>
            </div>
            <div class="read">
                <a href="" class="btn btn-default">Read info<i class="fa fa-angle-right"></i></a>
            </div>
        </div>
    </div>
<?php

endwhile;
endif;

?>
</div>

Hi. I am using custom post type to fetch the data in the home page and I also want icon with is_category but it does not work custom post type work properly but the icon inside the loop with is_category is not showing any result.


Solution

  • If you are sure your custom post type is using the default WordPress categories then you will be able to use has_category

    if( has_category( 'web-designing' ) ) {
        // do something
    }
    

    Categories are one of the built-in taxonomies in WordPress, but they only appear in posts by default. Your Custom Post Type might have it's own taxonomy in which case the function you are looking for is has_term as per the reference you can use this to check if the current post has any of given terms within a custom taxonom. e.g. the product_cat taxonomy in the below example.

    if( has_term( 'web-designing', 'product_cat' ) ) {
        // do something
    }