I'm trying to send the post id to js file to create a localStorage for each post by using their id's as the key. The problem is when i try this code in php it returns 0, as a result all my pages have the same localStorage. What should i do?

public function button_js(){
    $url     = wp_get_referer();
    $post_id = url_to_postid( $url );

    wp_localize_script( 'likeButton', 'ajax_object',
        array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => $post_id) )
add_action('wp_enqueue_scripts',[ $this ,'button_js']);
  • does $url contain the URL you expected ? – mmm Apr 16 '17 at 21:24
  • I checked now : So no :(. Why cant i get the right address? – codemonkey Apr 16 '17 at 21:31
  • what do you call "the right address" ? – mmm Apr 16 '17 at 21:35
  • the post's url. – codemonkey Apr 16 '17 at 21:42

when you are at the post URL, you don't need to work with referer (which is not reliable moreover) but with $GLOBALS["post"] because you are in the PHP code which generate the page

then you can have the post ID with that :

$post_id = $GLOBALS["post"]->ID;
  • I solved the problem with get_the_ID(); however this may work too! – codemonkey Apr 16 '17 at 22:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.