【问题标题】:get_permalink and get_the_category return emptyget_permalink 和 get_the_category 返回空
【发布时间】:2018-07-11 09:42:56
【问题描述】:

保存/更新自定义 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!?
}

有什么想法吗?

【问题讨论】:

  • 我会首先尝试调试实际的get_permalink() 方法:developer.wordpress.org/reference/functions/get_permalink 看看发生了什么。也许帖子对象的ID 没有设置?
  • 您是否尝试过使用普通的wp_query 循环而不是get_posts()?这样你就不需要每次都传递帖子 ID。
  • 是的,wp_query 给出相同的空结果。
  • 过滤过程中发生了一些事情,但我迷路了......

标签: wordpress


【解决方案1】:

删除 $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!?
}

【讨论】:

  • 同样的结果,结果还是空
  • @raju_eww。你的代码和问题代码有什么区别?
猜你喜欢
  • 2017-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
相关资源
最近更新 更多