how to get a page id in wordpress using jquery alone.I am planing to change some styles of a page using a custom script for which i need to know page id.
get_the_ID(); or $post->ID; returns the current page or post id in Wordpress.
JQuery uses attr() method to find out the id of an element.
To find a page ID, open your WordPress dashboard and click on Pages > All Pages. Once the page has opened, you need to look at the URL in your web browser's address bar. Here, you will find the page ID number displayed within the page URL.
The current URL in jQuery can be obtained by using the 'href' property of the Location object which contains information about the current URL. The 'href' property returns a string with the full URL of the current page.
function get_current_page_id() {
var page_body = $('body.page');
var id = 0;
if(page_body) {
var classList = page_body.attr('class').split(/\s+/);
$.each(classList, function(index, item) {
if (item.indexOf('page-id') >= 0) {
var item_arr = item.split('-');
id = item_arr[item_arr.length -1];
return false;
}
});
}
return id;
}
Add this function to your code. You can now get the page id by using:
var id = get_current_page_id();
Use wp_localize_script
.
function my_custom_vars() {
global $wp_query;
$vars = array(
'postID' => $wp_query->post->ID,
);
wp_localize_script( 'myvars', 'MyScriptVars', $vars );
}
add_action ('wp_enqueue_scripts', 'my_custom_vars');
You can use the vaiables in your scripts this way..
<script type="text/javascript">
var MyPostID = MyScriptVars.postID;
</script>
If you want to get the current page id in jQuery alone you can do it in following steps:
c_pageid
and the value get_the_ID();
var pageId=$("#c_pageid").val();
This may solve your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With