假设我在wordpress中有六页
example.com/apples
example.com/art
example.com/bananas
example.com/broccoli
example.com/cars
example.com/cats
我想定位以特定字母开头的网页
if (page slug beginns with "a"){
echo 'content for pages with slug beginning with a';
}
else if (page slug beginns with "b"){
echo 'content for pages with slug beginning with b';
}
else if (page slug beginns with "c"){
echo 'content for pages with slug beginning with c';
}
如何正确编写
答案 0 :(得分:1)
你需要使用php substr函数获得第一个字符。在functions.php文件中放置以下代码
add_filter('the_content', 'change_content_by_firstCharacter');
function change_content_by_firstCharacter( $content ) {
global $post;
$post_slug = $post->post_name;
$firstCharacter = substr($post_slug, 0, 1);
if ( $firstCharacter == 'a' ) {
$content = 'content for a goes here';
} else {
return $content;
}
}
答案 1 :(得分:1)
参考这个答案here,我说这样可以安全地获取网址:
/** Get the queried object and sanitize it */
$current_page = sanitize_post( $GLOBALS['wp_the_query']->get_queried_object() );
/** Get the page slug */
$slug = $current_page->post_name;
然后:
/** Get the first character */
$slugBeginsWith = substr($slug, 0, 1);
/** Apply your logic */
if($slugBeginsWith == 'a')
{
echo 'content for pages with slug beginning with a';
}
elseif($slugBeginsWith == 'b')
{
echo 'content for pages with slug beginning with b';
}
elseif($slugBeginsWith == 'c')
{
echo 'content for pages with slug beginning with c';
}
但是你没有提到你的目标是什么。也许如果您在问题中提供更多信息,我们可以提供更好的帮助!