Access The Main Post ID Anywhere based on the Current WordPress Page

There’s a number of ways to retrieve the post id of a post, but what if your page has multiple loops and you want to retrieve the main post id of the page? In my case I wanted to insert social buttons only on the main content of the page. If you are using the_content filter to add the html for your social buttons, it will show every time any kind of post content is displayed. Some page designs often use several loops to display various pieces of content (especially front pages), so you could end up with an abundance of social buttons – not exactly ideal. My solution then involved checking to see if the currently outputted content was the main content of the page by comparing post ids.

So I looked to see if there was a simple way to access the main post id – even if we are inside a secondary loop. Surprisingly, there doesn’t really seem to be a function for this. The closest thing is a function called get_page_by_path, but that works just for pages. Another idea is to access the $wp_query global variable, but this can be altered when other queries are made. What we can do is store the ID in our global variable when we are certain that $wp_query contains the main post id.

[php]
function main_post_id() {
global $wp_query;
global $main_post_id;
if( is_singular () ) { // ignores index pages for posts, categories, tags, archives etc
$main_post_id = $wp_query->post->ID;
}
}
add_action( ‘wp_head’,’main_post_id’ );
[/php]

Now we can quickly access the post id anywhere on the page, even if you are in a custom loop.

[php]
ID ) {
// do stuff
}
?>
[/php]

One comment

  1. telemarker says:

    this is awesome.
    it allows to show the content of a page that is set to shows some posts as a portfolio.
    goodwork!

Leave a Reply

Your email address will not be published. Required fields are marked *