user147215
user147215

Reputation:

get_the_category returning the wrong category

I'm subscribing to the publish_post WordPress hook to send out push notifications when new posts are added using the following

add_action( 'publish_post' , 'onesignal_post_publish_new' , 10 , 2 );
function onesignal_post_publish_new( $ID , $post )
{
  if ( $post->post_date == $post->post_modified ) {
    echo "<pre>";
    $category = get_the_category($post->ID);
    echo $category[0]->cat_name;
    echo "</pre>";

    // push notification code removed for brevity
  }
}

I am trying to get the category name to include in the body of the notification, however $category[0]->cat_name is always "Uncategorized". I've verified the values of $post->ID and $ID are correct and category is set to something other than Uncategorized. Not sure why this would be happening.

Upvotes: 1

Views: 1136

Answers (1)

Xhynk
Xhynk

Reputation: 13840

Posts by default are categorized as Uncategorized. Try changing

echo $category[0]->cat_name;

to

echo $category[1]->cat_name;

or at least var_dump( $category ); to confirm what all is in there.

Even though it's probably better to account for multiple categories such as

if( $post->post_date == $post->post_modified ){
    echo "<pre>";
        // returns array of WP_Term objects, not just one category
        $cat_array = get_the_category( $post->ID );
        if( is_array( $cat_array ) ){
            foreach( $cat_array as $cat ){
                $post_cats .= $cat->cat_name.', ';
            }
        }
        echo substr( $post_cats, 0, -2 ); // Remove ', ' from last one.
    echo "</pre>";

    // push notification code removed for brevity
}

Upvotes: 1

Related Questions