简体   繁体   English

get_the_id()不返回帖子的ID

[英]get_the_id() not returning ID's of posts

I'm trying to dynamically load blocks via AJAX: 我正在尝试通过AJAX动态加载块:

  • Blocks with the ID's 1, 2, 3, 4 and 5 are loaded by default on the page. 默认情况下,页面上会加载ID为1、2、3、4和5的块。
  • On "Load more" click, five new blocks will show (with the ID's 6,7, 8, 9 and 10). 单击“加载更多”,将显示五个新块(ID为6,7、8、9和10)。

However, I currently can't even get the ID's of the new blocks to echo out on the page and I'm unsure why? 但是,我目前什至无法获取新块的ID在页面上回显,并且我不确定为什么? I've tried globalising the var too. 我也尝试过全球化。

Current approach ( ajax-loaders.php ): 当前方法( ajax-loaders.php ):

function ajax_handler(){

  check_ajax_referer('load_more', 'security');

  $args = json_decode(( $_POST['query'] ), true ); 

  global $postId;
  $postId = get_the_id($args);

  if( $args->have_posts() ) : 
    while( have_posts() ): the_post(); 
      echo "the ID of this post is:".$postId;
    endwhile;
  endif;
  die;
}

In console, I get an post error. 在控制台中,我收到一个发布错误。

And if I do: 如果我这样做:

echo "the ID of this post is:".$postId; echo“此帖子的ID为:”。$ postId; var_dump($args); 后续代码var_dump($参数);

It returns the ID of this post is:NULL . 它返回此帖子的ID为:NULL

Unsure on what's happening? 不确定发生了什么?

Simple get_the_id() works within the WP loop and you've put it outside the loop. 简单的get_the_id()在WP循环中有效,并且已将其放在循环之外。 try: 尝试:

echo "the ID of this post is:" . get_the_id();

Outside the loop: 循环外:

global $post;
postId = $post->ID;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM