Get the post id from a plugin

One of the problems I have run into while trying to accomplish something like this is: WHEN are you trying to get this information.

A lot of stuff happens in a WordPress page request.
See: https://codex.wordpress.org/Plugin_API/Action_Reference

If you just have the raw function in your plugin file, it will try to run when the plugin loads (which is very early in the process), and you will not get the info you are looking for.

I’m not sure how early you can do it, but I generally stick it at wp.

add_action( 'wp', 'get_post_id' );


function get_post_id () {
    global $wp_query;
    $post_id = $wp_query->post->ID;
}

The way I do this is:

class Main_Plugin_Class(){

public $post_id;

public __constructor(){

 ...

 add_action( 'wp', array( 'this', 'at_wp') );

}

public function at_wp(){

 $post_id = $this->get_post_id();
 $this->object_that_will_actually_do_things = new Class_For_Doing_Things($post_id);

}

private function get_post_id(){
 global $wp_query;
 $id = $wp_query->post->ID;
 return $id;
}

}

tech