Php Wordpress=>;获取帖子类别

Php Wordpress=>;获取帖子类别,php,wordpress,wordpress-plugin-creation,Php,Wordpress,Wordpress Plugin Creation,我目前正在尝试在创建帖子时获取类别。例如,我想在这里创建一个“actus”和“sport”类别的帖子: 但是,当我想在PHP中获取类别时,我会: $categories = get_the_category( $post->ID ); 那么对于测试,我会: echo $categories[0]->name 但这给了我未分类的价值,但我还没有在帖子中选择这个类别 当他被创建时,我是否使用了错误的解决方案来获取特定的帖子类别 最好的结果是一个包含类别名称的字符串数组 这是我的全部代

我目前正在尝试在创建帖子时获取类别。例如,我想在这里创建一个“actus”和“sport”类别的帖子:

但是,当我想在PHP中获取类别时,我会:

$categories = get_the_category( $post->ID );
那么对于测试,我会:

echo $categories[0]->name
但这给了我未分类的价值,但我还没有在帖子中选择这个类别

当他被创建时,我是否使用了错误的解决方案来获取特定的帖子类别

最好的结果是一个包含类别名称的字符串数组

这是我的全部代码:

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

    $client = new \Fcm\FcmClient(
       apiKey,
       id
    );

    $notification = new \Fcm\Push\Notification();

    $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);

类别仅在发布/更新时应用于帖子。您需要在提交后使用
save\u post
操作钩子捕获它们

我找到了解决办法

对于任何想知道“保存帖子”或“发布帖子”操作是在设置术语之前触发的人


你必须改用“wp\u after\u insert\u post”来代替

如果你没有选择类别,你会得到默认的帖子类别(通常是“未分类的”),试着更改你的默认帖子类别,看看它是否会改变你返回的内容。正如你在屏幕截图中看到的,我选择了两个类别我看到了屏幕截图。不太清楚的是何时调用函数以及何时期望类别存在。人们试图在互联网上免费帮助你尝试一些礼貌。我已经用我所有的功能编辑了我的帖子。使用您的解决方案,我仍然将“未分类”作为$terms的值