Wordpress Get the Page ID outside the loop

2019-01-16 06:56发布

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.

标签: php wordpress
11条回答
劫难
2楼-- · 2019-01-16 07:28

This is the correct code.

echo $post->ID;
查看更多
姐就是有狂的资本
3楼-- · 2019-01-16 07:30

Use this global $post instead:

global $post;
echo $post->ID;
查看更多
smile是对你的礼貌
4楼-- · 2019-01-16 07:32

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();
查看更多
在下西门庆
5楼-- · 2019-01-16 07:35

Use below two lines of code to get current page or post ID

global $post;
echo $post->ID;
查看更多
我只想做你的唯一
6楼-- · 2019-01-16 07:35

If you are out of the Loop of WordPress you can not use any of the method of wordpress so you must use pure php.

You can use this code. And sure will help you :)

$page_id = @$_GET['page_id'];

if (!is_numeric($page_id)) {
    // Then the uri must be in friendly format aka /my_domain/category/onepage/
    // Try this
    //$path = '/www/public_html/index.php/';
    ///$path = '/my_domain/category/onepage/';
    $path = $_SERVER['REQUEST_URI'];
    // Clean the uri
    //$path = str_replace('/', '', $page);
    $path = str_replace('.php', '', $path);
    //$path = str_replace('?s=', '', $path);
    $path = $path ? $path : 'default';

    $path_len = strlen($path);
    $last_char = substr($path, $path_len -1);
    //echo $last_char;
    $has_slash = strpos($last_char, "/");
    //echo $has_slash;
    if ($has_slash === 0) :
        $path = substr($path, 0, $path_len -1);
    elseif ($has_slash === null) :
        $path = substr($path, 0, $path_len);
    endif;
    //echo "path: ".$path; // '/www/public_html/index'
    $page = substr(strrchr($path, "/"), 1);
    echo "page: ".$page; // 'index'
}

$my_page_id = 31;
$my_page = 'mypage';

//echo "page: ".$page;
//echo "page_id ".$page_id;
if($page_id == $my_page_id || $page == $my_page) 
{
    // your stuff....
}

Enjoy!

查看更多
不美不萌又怎样
7楼-- · 2019-01-16 07:36

You can use is_page($page_id) outside the loop to check.

查看更多
登录 后发表回答