简体   繁体   中英

get_the_id() not returning ID's of posts

I'm trying to dynamically load blocks via AJAX:

  • Blocks with the ID's 1, 2, 3, 4 and 5 are loaded by default on the page.
  • On "Load more" click, five new blocks will show (with the ID's 6,7, 8, 9 and 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? I've tried globalising the var too.

Current approach ( 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; var_dump($args);

It returns the ID of this post is:NULL .

Unsure on what's happening?

Simple get_the_id() works within the WP loop and you've put it outside the loop. try:

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

Outside the loop:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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