get_permalink和get_the_category返回空

时间:2018-07-11 09:42:57

标签: wordpress

保存/更新自定义wordpress posttype后,我正在调用脚本:

function update_save_post( $post_id, $post, $update ){

    if ($post->post_type == 'my_custom_posttype')
    {
      include 'api/index.php';
    }

}
add_action( 'save_post', 'update_save_post', 10, 3); 

在index.php中,我检索my_custom_posttype的所有帖子,并循环遍历它们。在循环中,“ get_permalink”和“ get_the_category”返回空(空字符串和空数组)。 $ post和$ acf数组包含预期的字段。在存档页面内使用时,永久链接和get_the_category正常工作。

$posts = get_posts([
  'post_type' => 'my_custom_posttype',
  'post_status' => 'publish',
  'numberposts' => -1,
  'order'    => 'ASC'
]);

foreach ($posts as $post) {
  print_r($post);
  echo get_permalink($post->ID); //empty string!?
  $acf = get_fields($post->ID);
  print_r($acf);
  $cats = get_the_category($post->ID);
  print_r($cats); //empty array!?
}

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

删除$post->ID并仅添加$post,它将在您使用foreach时起作用

$posts = get_posts(array(
  'post_type' => 'my_custom_posttype',
  'post_status' => 'publish',
  'numberposts' => -1,
  'order'    => 'ASC'
));

foreach ($posts as $post) {
  print_r($post);
  echo get_permalink($post->ID); //empty string!?
  $acf = get_fields($post->ID);
  print_r($acf);
  $cats = get_the_category($post->ID);
  print_r($cats); //empty array!?
}