Get current post_id on or before init hook in WordPress

Im looking for anyway to get the current page id by the time the init hook fires.

The closest I’ve come is grabbing the $_POST[‘post_id’] when init hits admin-ajax.php but its unreliable… It often doesn’t get set the first page load and requires a refresh for some reason.

Read More

Any ideas?

Related posts

1 comment

  1. You can use the ‘after_setup_theme’ hook, which executes just before ‘init’. Then, in a function triggered by that hook, you can get the current page ID like this:

    // Get access to the current WordPress object instance
    global $wp;
    
    // Get the base URL
    $current_url = home_url(add_query_arg(array(),$wp->request));
    
    // Add WP's redirect URL string
    $current_url = $current_url . $_SERVER['REDIRECT_URL'];
    
    // Retrieve the current post's ID based on its URL
    $id = url_to_postid($current_url);
    

Comments are closed.