DEV Community

Cover image for How to get custom post data in WordPress
Stackfindover
Stackfindover

Posted on

How to get custom post data in WordPress

*Hello, guys do you want to learn how to get custom post type data in WordPress, then you are in the right post today in this article I will share with you a simple and fastest way to get custom post type data with many examples.
*

A comprehensive guide to obtain custom post type data

How to get custom post type according cat id

<?php

$args = array(
    'posts_per_page' => -1,    
    'post_type' => 'our-work',
    'tax_query' => array(
        array(
            'taxonomy' => 'work_type',
            'field'    => 'id',
            'terms'    => 5, // id of category
        ),
    ),
 );
$the_query = new WP_Query( $args );

if($the_query->have_posts() ) : 
    while ( $the_query->have_posts() ) : 
       $the_query->the_post(); 
    //   for title
       the_title();
    // for content
    echo get_the_content();

    // for post link
    echo get_permalink();
    endwhile; 
    wp_reset_postdata(); 
else: 
endif;

?>
Enter fullscreen mode Exit fullscreen mode

How to get custom post type category name in WordPress

Simple Way to get the list of all categories of my custom post type Our work, I will use the get_terms() function by giving my custom post type’s taxonomy slug, which is ‘work_type‘ in my case.

You can also add multiple taxonomies as an array to the taxonomy parameter.

The most important thing is, ‘hide_empty‘ parameter, make sure it’s set to false. Otherwise, it will not show the categories that have 0 posts.

<?php
$terms = get_terms(
         array(
                'taxonomy'   => 'work_type', // Custom Post Type Taxonomy Slug
                'hide_empty' => false,
                'order'         => 'asc'
            )
         );?>
         <ul>
<?php 
foreach ($terms as $term) { ?>
        <li><a href="<?php echo get_term_link($term);?>"><?php echo $term->name;?></a></li>
 <?php   }?>

</ul>
Enter fullscreen mode Exit fullscreen mode

How to get custom post type featured image in WordPress

Top comments (0)