Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress Get the Page ID outside the loop

Tags:

php

wordpress

I want to get the page ID before starting the loop in WordPress. I am using

$page = get_query_var('page_id'); 

Apparently, it returns nothing.

I just want to check a page for its ID and add a class to <body> tag based on it.

like image 655
Atif Avatar asked Jun 27 '10 12:06

Atif


People also ask

How do I find the 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 get current page id in WordPress functions php?

function getcity(){ global $wpdb; if($_POST['state']) { $id=$_POST['state']; $district = get_post_meta(get_the_ID() , 'district', true); var_dump($district); $result=$wpdb->get_results("SELECT * FROM districts WHERE state_id='$id'"); foreach($result as $row) { $district_name = $row- >district_name; $district_id = $row- ...

How do I find the current page ID in Woocommerce?

php if(is_shop()){ $page_id = woocommerce_get_page_id('shop'); }else{ $page_id = $post->ID; } ?> Hope this will help you.


1 Answers

If you're using pretty permalinks, get_query_var('page_id') won't work.

Instead, get the queried object ID from the global $wp_query:

// Since 3.1 - recommended! $page_object = get_queried_object(); $page_id     = get_queried_object_id();   // "Dirty" pre 3.1 global $wp_query;  $page_object = $wp_query->get_queried_object(); $page_id     = $wp_query->get_queried_object_id(); 
like image 116
TheDeadMedic Avatar answered Sep 19 '22 19:09

TheDeadMedic