facebook twitter youtube
in How & Why - 16 Mar, 2012
by Amit Gupta - no comments

If you call the_ID() or get_the_ID() in wp_head(), you’ll get nothing. Sometimes you require post id to do a specific action like including post id in meta tag or to count number of visits etc.
Well this trick can help you. Let’s see how;

add_action('wp_head', 'doSomethingInHead');
function doSomethingInHead() {
		:
		echo "#amtypostid#;
		:
	}
}

Now use jQuery functions find() & replaceWith() to replace this constant value with post id. But how will you get post id and when will you replace it?

Note: find() search for tag. So echo your constant in some tag. Otherwise create a new dummy tag. replaceWith() will replace all value with post id along with tag.

To get post id of current post:

add_action('the_content', 'getId');
function getId($content) {
	//prepare your jquery script here.
	//use the_ID() or get_the_ID() to get current post id.
	//attach it with your content and return.
	return $content . $myscript;
}
Amit Gupta

Hey! this is Amit Gupta (amty). By profession, I am a Software Eng. And teaching is my passion. Sometimes I am a teacher, as you can see many technical tutorials on my site, sometimes I am a poet, And sometime just a friend of friends...

Leave a Reply

captcha