問題描述
如何在固定鏈接之後添加額外的參數,具體來説,如果我使用自定義的帖子類型?
例如,讓我們説 http://mysite/album/record-name
是永久鏈接。如何使 http://mysite/album/record-name/related
不會變成 404 或重定向?
如果帖子不存在,WordPress 似乎沒有調用帖子模板… 所以我有點失落如何做到這一點。
最佳解決方案
您可以向 URI 添加一個端點來處理特殊請求。
這是插件的一個基本示例。瞭解發生了什麼事 Christopher Davis 的夢幻教程 A (Mostly) Complete Guide to the WordPress Rewrite API 。
<?php # -*- coding: utf-8 -*-
/**
* Plugin Name: T5 Endpoint Example
* Description: Adds a permalink endpoint to posts named <code>epex</code>
*/
add_action( 'init', 't5_add_epex' );
function t5_add_epex()
{
add_rewrite_endpoint( 'epex', EP_PERMALINK );
}
add_action( 'template_redirect', 't5_render_epex' );
/**
* Handle calls to the endpoint.
*/
function t5_render_epex()
{
if ( ! is_singular() or ! get_query_var( 'epex' ) )
{
return;
}
// You will probably do something more productive.
$post = get_queried_object();
print '<pre>' . htmlspecialchars( print_r( $post, TRUE ) ) . '</pre>';
exit;
}
add_filter( 'request', 't5_set_epex_var' );
/**
* Make sure that 'get_query_var( 'epex' )' will not return just an empty string if it is set.
*
* @param array $vars
* @return array
*/
function t5_set_epex_var( $vars )
{
isset( $vars['epex'] ) and $vars['epex'] = true;
return $vars;
}
次佳解決方案
您可以使用 Rewrite API 的 add_rewrite_endpoint:
add_action( 'init', 'wpse51444_endpoint' );
function wpse51444_endpoint(){
add_rewrite_endpoint( 'related', EP_ALL );
}
add_filter( 'query_vars', 'wpse51444_query_vars' );
function wpse51444_query_vars( $query_vars ){
// add related to the array of recognized query vars
$query_vars[] = 'related';
return $query_vars;
}
在模板中,您可以檢測何時存在相關的查詢 var:
if( array_key_exists( 'related' , $wp_query->query_vars ) ):
// current request ends in related
endif;
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。