Nice trick to get_the_ID() in wp_head()
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;
}
141
views
views


No Comments