php – Get category name of current post (CPT UI)


I used CPT UI to create custom post types “Job Offers” which has a taxonomy with slug “job_offers_categories”.

enter image description here

In the CPT Categories I have 4 categories:

enter image description here

  1. Exchange Programme
  2. Job Offer
  3. Job Request (Beginner)
  4. Job Request (Expert)

What I want to achieve is to retrieve current post category name or slug so I can assign different picture according to the category. So in my WP_Query I’m able to retrieve current post, but tried several ways to achieve what I want, but is not working. Is either giving me Array, undefined or nothing at all like the example below.

Here is my code (example of current post: “Job Offer”):

$post_query = new WP_Query(array(
    'author'    =>  get_current_user_id(),
    'post_type' => 'job-offers'

while($post_query->have_posts()) {
    $post_query->the_post();//GET POST OBJECT
    $i = $post_query->current_post;//GET LOOP INDEX
    $post_id = get_the_id();//GET POST ID
    $view_post_URL = get_the_permalink();//URL FOR VIEW POST
    $terms = get_the_terms( $post_id, 'job_offer_categories' );
    if ($terms) {
        foreach($terms as $term) {
            echo $term->name; 
            //Expected Result: "Job Offer" or "job-offer", prefer to retrieve slug name of custom category

Also tried the following which:

$the_cat = get_the_category( $i->ID );
echo $the_cat; // is returning `Array`
foreach($the_cat as $cat) {
    echo $cat->name; //Array to string conversion error

Loizos Vasileiou 1 year 2023-01-08T03:40:07-05:00 0 Answers 0 views 0

Leave an answer