Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 467
user2709743 Avatar asked Aug 23 '13 05:08

user2709743


People also ask

How do I find the current page id in WordPress?

get_the_ID(); or $post->ID; returns the current page or post id in Wordpress.

How can I get ID in JQuery?

JQuery uses attr() method to find out the id of an element.

Is Page ID in WordPress?

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.

How can I get URL in JQuery?

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.


3 Answers

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();
like image 125
Diyen Momjang Avatar answered Nov 14 '22 23:11

Diyen Momjang


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>
like image 29
Abhik Avatar answered Nov 15 '22 00:11

Abhik


If you want to get the current page id in jQuery alone you can do it in following steps:

  • First make hidden input or hidden HTML tag and add the current page id in it by id of the element: c_pageid and the value get_the_ID();
  • In your jQuery file you can get this value by id like var pageId=$("#c_pageid").val();

This may solve your problem.

like image 22
Rahul Avatar answered Nov 15 '22 01:11

Rahul