我正在嘗試使用 獲取當前頁面 slug get_post_field( 'post_name', get_post() ),但是,這將回傳多個值。
我的代碼看起來像這樣(我在自定義插件中撰寫):
function prefix_filter_query( $query_string, $grid_id, $action ) {
// If the content is not filtered on first render.
if ( 'render' === $action && empty( $query_string ) ) {
$slug = get_post_field( 'post_name', get_post() );
$query_string = [
'categories' => [ $slug ]
];
_error_log($slug);
}
return $query_string;
}
function _error_log ($value) {
error_log(print_r($value, true), 3, __DIR__ . '/log.txt');
error_log("\r\n\r\n", 3, __DIR__ . '/log.txt');
}
add_filter( 'wp_grid_builder/facet/query_string', 'prefix_filter_query', 10, 3 );
日志首先顯示當前頁面(這里是一個類別,如“連帽衫”),然后是我網站的主頁slug,如下所示:
hoodies
home
我知道顯示主頁是因為我將網站的主頁設定為靜態默認主頁。我試圖禁用它,看看它是否解決了我的問題,但日志回傳的第二個值只是一個空白空間:
hoodies
我只想得到但hoodies我不明白為什么會有第二個值,無論是家還是空值。
為了提供一些背景關系,我正在為電子商務網站中的產品使用過濾器插件,并且該插件提供了一個內置功能來在呈現內容之前對其進行過濾。https://docs.wpgridbuilder.com/resources/filter-facet-query-string/
在我們的示例中,另一個有趣的事實hoodies將成功過濾專案網格以僅顯示連帽衫,但 URL 中的查詢將為?_categories=home.
uj5u.com熱心網友回復:
您只是想獲取當前頁面 slug 嗎?您可以通過服務器請求 uri $_SERVER['REQUEST_URI']:
PHP >= 8.0.0
<?php
/**
* Retrieve the current page slug.
*
* @return String The current page slug.
*/
if ( ! function_exists( 'get_the_current_slug' ) ) {
function get_the_current_slug() {
$url = $_SERVER['REQUEST_URI'];
if ( str_contains( $url, '?' ) ) {
$url = substr( $url, 0, strpos( $url, '?' ) );
};
$slugs = ( str_ends_with( $url, '/' ) ? explode( '/', substr( $url, 1, -1 ) ) : explode( '/', substr( $url, 1 ) ) );
return end( $slugs );
};
};
PHP < 8.0.0(如:7.x.x)
<?php
/**
* Checks if a string ends with a given substring.
*
* @param String $haystack The string to search in.
* @param String $needle The substring to search for in the haystack.
*
* @return Integer < 0 if haystack from position offset is less than needle, > 0 if it is greater than needle, and 0 if they are equal. If offset is equal to (prior to PHP 7.2.18, 7.3.5) or greater than the length of haystack, or the length is set and is less than 0, substr_compare() prints a warning and returns false.
*
* @see https://www.php.net/manual/en/function.substr-compare.php
*/
if ( ! function_exists( 'startsWith' ) ) {
function startsWith( $haystack, $needle ) {
return substr_compare( $haystack, $needle, 0, strlen( $needle ) ) === 0;
};
};
/**
* Retrieve the current page slug.
*
* @return String The current page slug.
*/
if ( ! function_exists( 'get_the_current_slug' ) ) {
function get_the_current_slug() {
$url = $_SERVER['REQUEST_URI'];
if ( strpos( $url, '?' ) !== false ) {
$url = substr( $url, 0, strpos( $url, '?' ) );
};
$slugs = ( startsWith( $url, '/' ) ? explode( '/', substr( $url, 1, -1 ) ) : explode( '/', substr( $url, 1 ) ) );
return end( $slugs );
};
};
在前端:
<?php
echo get_the_current_slug();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/394707.html
標籤:php WordPress的
上一篇:驗證檔案的擴展名是否足以知道該檔案沒有隱藏病毒(或可以滲透到我的服務器的東西)?
下一篇:Azure登錄-新手機號碼
