开发者

How to retrieve the ID of the page the user is currently viewing in Wordpress sites?

I am developing a Wordpress pl开发者_如何学Gougin in which I am displaying the Archive based on Categories. Categories are my pages in my site and each Page should display post in the Archive belongs to that Category only. So i need to dynamically get the Category ID of the page the user is currently viewing.How can I retrieve it?


You're using the word page a little confusingly there - are you talking about WordPress pages that you have created in the admin, or the webpage displayed for each category archive?

If the latter, you can use the global $wp_query to get the category ID like so;

$cat_ID = $wp_query->get_queried_object_id();


Remember that a post can belong to more than one category. This code might work for you:

if(is_category()){
    $cat_id = get_query_var('cat');
} else if (is_single()) {
    $cat_id = '';
    foreach (get_the_category() as $catt) {
        $cat_id .= $catt->cat_ID.' '; 
    }
    $cat_id = str_replace(" ", ",", trim($cat_id));
}
if (!intval($cat_id)) $cat_id='';

$query = "&category=$cat_id";
$posts = get_posts($query);
$postlist = ''; 
foreach ($posts as $post) {
   // something for each post
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜