wordpress get post id from side widget

2019-08-07 10:34发布

问题:

I am trying to get the post id from a widget I am putting into the sidebar, but what ever I try I seem to get random post id's from other posts.

I have tried:

            $id = get_the_id();

            $post_id = $GLOBALS['post']->ID;

            global $wp_query;

            $thePostID = $wp_query->post->ID;

The template I am using is classipress and I am putting my widget into the sidebar they provide. They already have a form at the top of the sidebar which uses the post id. They use

            global $post;

I have tried this also and it too gives my a different post id, but not the correct one.

I am all out of ideas at this stage.

回答1:

Make sure your plugin is added with:

add_action("widgets_init", "your_init");

otherwise $post won't be initialized at the time.



回答2:

I'm not sure I understand - why would the widget in the sidebar have a dedicated post ID? As far as I'm aware, post ID's are saved for actual posts (or pages, even) and not elements like widgets? Could the reason you're not getting the "correct" ID be because there isn't one? How do you know what the "correct id" is in the first place?