WordPress Tip: PHP Codes for Getting the Slug of Current Page

While I was working on a WordPress template, I needed to show posts in the category which has the same name ( or slug) of a page. As the WordPress.org said, the codes:

<?php query_posts(‘category_name=page_slug & showposts=10’);?>

could be used. But how to identify the slug of current page? It took me a long time to find out the way.

Here is the codes I used finally:

<?php if(is_page()){

$current_page_link=get_permalink();

$current_page_slug_holder=explode(“/”,$current_page_link); /*get current page slug, stored in $current_page_slug_holder[4]*/

$counter=count($current_page_slug_holder)-2;

/*use variable $counter to get the position, because it may be a subpage, added by lonelicloud at 2009.10.06 14:24*/}

?>

<?php query_posts(‘category_name=’ . $current_page_slug_holder[4] . ‘&showposts=10’);?>

<?php query_posts(‘category_name=’ . $current_page_slug_holder[$counter] . ‘&showposts=10’);?>

Inspireted by:

1. Category Templates
2. Subpage get parent page slug

<?php if (is_page()) { ?>

<?php $cssdir = get_permalink(); ?>

<?php $holder = explode(“/”,$cssdir) ?>

<link rel=”stylesheet” href=”<?php bloginfo(‘template_directory’); ?>/page.css” type=”text/css” media=”screen” />

<link rel=”stylesheet” href=”<?php bloginfo(‘template_directory’); ?>/<?php echo $holder[3]; ?>/style.css” type=”text/css” media=”screen” />

<?php } ?>

3. Also, there is a post working on this, but I can’t understand:

WordPress Tip: Find the Current Page Slug

by Michael on August 9th, 2007 in Tips and Tricks, WordPress

While I was working on a WordPress template today, I needed to find the current page’s post_slug. After investigating the function is_single in wp-includes/query.php, I discovered the following method for determining the current page ID, post title, or post name:

$post_obj = $wp_query->get_queried_object();

$post_ID = $post_obj->ID;

$post_title = $post_obj->post_title;

$post_name = $post_obj->post_name;

via WordPress Tip: Find the Current Page Slug :: WenderHost.

©

本文发表于水景一页。永久链接:<https://cnzhx.net/blog/wordpress-tip-php-codes-for-getting-the-slug-of-current-page/>。转载请保留此信息及相应链接。

1 条关于 “WordPress Tip: PHP Codes for Getting the Slug of Current Page” 的评论

  1. In the original post, I hadn’t realized that the page could be a sub-page. This leaded to a function error when the current page was a sub-page.
    The code had been corrected in the post.

雁过留声,人过留名

您的电子邮箱地址不会被公开。 必填项已用 * 标注

特别提示:与当前文章主题无关的讨论相关但需要较多讨论求助信息请发布到水景一页讨论区的相应版块,谢谢您的理解与合作!请参考本站互助指南
您可以在评论中使用如下的 HTML 标记来辅助表达: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>