• Resolved montanan

    (@montanan)


    I am trying to get the id of the currently loaded post in my plugin. I have tried a global $post, $post->ID and it is empty. I assume it has to do with the fact that the plugin must have loaded before the page, therefore, there is no post ID. It is for an ajax request. When the user clicks on a link on that post it will load information. That information requires me knowing what post they are currently on.

    function MSC_SP_ajax_handler() { // this function gets the ajax data
        
        check_ajax_referer( 'my_nonce' ); // checks for the correct nonce which is set in the enqueue function
    
        // I need the post ID here.
                 
        wp_die(); // All ajax handlers die when finished
    }

    If I place this in my plug the page fails to fully load and shows the post id.

    add_action( 'the_post', 'set_post_id' );
    function set_post_id() {
        global $post;
        die("the id: ".$post->ID);
    }

    But I cannot pass that to the MSC_SP_ajax_handler function.

Viewing 3 replies - 1 through 3 (of 3 total)
  • I assume it has to do with the fact that the plugin must have loaded before the page, therefore, there is no post ID. It is for an ajax request.

    No, it’s because there is no post for the AJAX request.

    At the time that you create the nonce, you should know the post ID. So put it in the page (or in the link in a data attribute).

    Moderator bcworkz

    (@bcworkz)

    Indeed, as Joy said, it needs to be on the Ajax calling page somewhere and passed as part of the Ajax request. With most themes, it’s usually already in an HTML element as a class attribute, such as <article class="post-1234">. Or in the body tag. If you’ve enqueued your Ajax script, you could use wp_localize_script() to pass PHP values like the queried object ID to the page’s JS/jQuery. For example:

    wp_localize_script( 'ajax-script', 'my_ajax_object', array(
    	'ajax_url' => admin_url( 'admin-ajax.php' ),
    	'_wp_nonce' => wp_create_nonce( 'example-nonce' ),
    	'post_id' => get_queried_object_id(),
    ));

    Be advised though the queried object in not always a post. You could get other object IDs or sometimes null. It will be a post ID for single post requests.

    Thread Starter montanan

    (@montanan)

    Thanks to @bcworkz

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘Needing Post ID in Ajax plugin.’ is closed to new replies.