how to get the current page id in wordpress using jquery

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.


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;

The best way to do this is by adding global javascript variables via PHP.

To do this first add the following script to your page.php template file:

var pageId = <?php echo isset($posts[0]) ? $posts[0]->ID : 'null'; ?>;

Now in in your javascript code you are able to use this global variable like this.

if(pageId !== undefined && pageId) {
 // do some code based on pageId

You can use this same technique to use other WordPress variables in javascript.

var pageId="<?php echo get_the_ID(); ?>"

Use the above line in your script

Need Your Help

How do I set the padding-top based on height of a div in JQuery or Javascript?

javascript jquery html

Hey guys so I have a product site and each product's div's height is different based on the info entered.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.