簡體   English   中英

Wordpress PHP if statement to detect URL and server specific header.php page

[英]Wordpress PHP if statement to detect URL and server specific header.php page

In WordPress I would like to to show a custom header.php if the URL contains a specific string (in this case /support/ also to include /support/forums/). 我環顧四周並嘗試了許多不同的組合,但似乎無法讓它發揮作用。 以下是我的代碼,任何幫助將不勝感激!!!

if (substr($_SERVER['REQUEST_URI'], 0, 5) !== 'support') {
get_header('XXXXXX');
} else {
get_header();
}

僅供參考...我需要它以這種方式工作(我認為),因為我使用的是自定義帖子類型,因此不能使用標准的 WordPress 調用,因為它只是一個 slug 而不是 Post/Category/.etc。

謝謝!!

另一種非常相似的方式是:

<?php $uri_segments = explode( '/', $_SERVER['REQUEST_URI'] );
if ( in_array('support', $uri_segments) ) { get_header('xxxx'); }else{ get_header(); }
?>

你忘記你的代碼了嗎? 什么都沒有出現。

無論如何$_SERVER['QUERY_STRING']是您所追求的值,然后您可以使用 PHP 的字符串操作函數(如explode()或更好的strpos()來查找和響應您所追求的任何內容,查找有關 function 的更多信息explode PHP手冊頁strpos PHP 手冊頁和關於_SERVER 保留變量

假設您的 URI 始終在 position (第一個)處具有“支持”字符串,那么您的代碼看起來不錯,我看不到任何錯誤。 但請記住, get_header()的參數 function 是文件名必須為 append 的后綴。 所以,如果你有:

get_header('test');

您的 header 文件應命名為: header-test.php

此外,為了確保即使它在 URI 中更改 position 也能始終找到該字符串,您可以這樣做:

$params= explode('/',$_SERVER['REQUEST_URI'] );

if(in_array('support', $params)) {
    get_header('support');
} else {
    get_header();
}
  1. 比較字符串的長度,支持不是5個字符長,所以if語句總是假的。

  2. URI 通常在 position 0 處以/開頭,因此將其包含在字符串中以進行比較或在 position 1 處開始比較。

我會使用:

if (substr($_SERVER['REQUEST_URI'], 0, 9) !== '/support/') {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM