有誰能夠幫我?
我想創建一個正在進行的條件以在 wordpress 上顯示單個帖子。例如,我想先檢查post slug,如果slug的第一個有“news-”字符(例如:domain[dot]com/news-anything-another-text),那么single.php會輸出我想展示什么。但是如果第一個 slug 中沒有“news-”字符,那么 single.php 會顯示與 slug 對應的已發布帖子。但是,如果 slug 中沒有“news-”字符,并且沒有 slug 等公共帖子。然后系統會對錯誤頁面404做一些事情
uj5u.com熱心網友回復:
如果您想在 slug 以“新聞”開頭的情況下為未找到的帖子顯示自定義內容,您需要將用戶重定向到不同的頁面并在那里顯示內容。
在functions.php中添加以下代碼確保在執行此重定向之前已創建該自定義頁面
function rf_custom_redirect() {
$page_slug = $_SERVER['REQUEST_URI'];
$link_array = explode('/',$page_slug);
$page = end($link_array);
$firstword = strtok($page, "-");
if( is_404() && $firstword == "news"){
//Code you want to execute if the first word is news
wp_redirect( home_url( '/custom-page/' ) );
exit();
}
else
{
//Code you want to execute if the first word is not news
}
}
add_action( 'template_redirect', 'rf_custom_redirect' );
如果博客文章 slug 以新聞開頭,則下面的代碼將在 single.php 中顯示特定內容。
首先,您需要在 single.php 檔案(Single Blog Post 模板)中獲取 POST SLUG/URL。為此,請使用以下代碼。
global $post;
$page_slug = $post->post_name;
PHP 中有一個字串函式 (strtok),可用于根據分隔符將字串拆分為更小的字串(標記)。在我們的例子中,分隔符是 hypen(-)。
我們可以使用下面的代碼獲取 page slug 的第一個單詞。
$firstword = strtok($page_slug, "-");
然后,您只需使用簡單的 IF 條件檢查 $firstword 是否為“新聞”。
if($firstword == "news")
{
//Code you want to execute if the first word is news
}
else
{
//Code you want to execute if the first word is not news
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/504030.html
上一篇:想顯示一次表格
