skip to Main Content

I’m currently trying to get the categories when I create a post. For exemple here I want to create a post with the category ‘ actus ‘ and ‘ sport ‘ :

But then, when I want to get the category in PHP, I do :

$categories = get_the_category( $post->ID );

Then for testing I do :

echo $categories[0]->name

But this is giving me Uncategorized as value, but I haven’t selected this category in the post.

Am I using the wrong solution to get a specific post categories when he is created ?

The best result would be an array of string with the categories names

This is all my code :

function new_post($post_id, $post, $update) {
  if ($post->post_status == 'publish' && empty(get_post_meta( $post_id, 'check_if_run_once' ))) {

    $client = new FcmFcmClient(
       apiKey,
       id
    );

    $notification = new FcmPushNotification();

    $fcmData = [
      'dataTitle' => $post->post_title,
      "path" => "/la-baleine-de-retour-en-mariniere-sur-le-front-de-mer-darcachon",
    ];

    $terms = join( '', wp_list_pluck( wp_get_object_terms( $post_id, 'category' ), 'name' ) );


    $notification
      ->addTopic('actus')
      ->setTitle("Un nouvel article est disponible: ")
      ->setBody($terms)
      ->addDataArray($fcmData);

    $response = $client->send($notification);

    update_post_meta( $post_id, 'check_if_run_once', true );
  }
}

add_action( 'save_post', 'new_post', 10, 3);

2

Answers


  1. Chosen as BEST ANSWER

    I found the solution.

    For anyone wondering, "save_post" or "publish_post" actions are triggered before setting of the terms.

    You have to use " wp_after_insert_post " instead


  2. Categories are only applied to a post upon publishing/update. You would need to capture them after submitting using the save_post action hook.

    <?php
    
    add_action( 'save_post', function( $post_id, $post ) {
    
    $terms = join( '', wp_list_pluck( wp_get_object_terms( $post_id, 'category' ), 'name' ) );
    
    // ...
    
    }, 10, 2 );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search