2017-01-06 49 views
0

可以說我有在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'; 
} 

如何正確地寫這個

回答

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'; 
} 

但是你沒有提到你的目標是什麼。也許如果你在你的問題中提供更多信息,我們可以幫助更好!

+0

這正是我需要的,謝謝! – benua

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; 
} 
}