如何在永久链接之后添加额外参数,特别是在使用自定义帖子类型的情况下?
比如说http://mysite/album/record-name
是permalink。我怎样才能http://mysite/album/record-name/related
没有打开404或重定向?
如果帖子不存在,WordPress似乎不会调用帖子模板。。。所以我有点不知道怎么做。
如何在永久链接之后添加额外参数,特别是在使用自定义帖子类型的情况下?
比如说http://mysite/album/record-name
是permalink。我怎样才能http://mysite/album/record-name/related
没有打开404或重定向?
如果帖子不存在,WordPress似乎不会调用帖子模板。。。所以我有点不知道怎么做。
您可以向URI添加端点来处理特殊请求。
下面是一个插件的基本示例。要了解正在发生的事情,请阅读Christopher Davis\'s精彩教程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\'sadd_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;
}
在模板中,您可以检测相关查询变量何时存在:if( array_key_exists( \'related\' , $wp_query->query_vars ) ):
// current request ends in related
endif;
到add parameter to post url (permalink),我这样使用:
add_filter( \'post_type_link\', \'append_query_string\', 10, 2 );
function append_query_string( $url, $post )
{
return $url.\'?my_pid=\'.$post->ID;
}
输出:http://yoursite.com/pagename?my_pid=12345678
这个我差不多做完了,只剩下一个小问题。希望你能帮助我。我有两个非常简单的自定义循环。一个用于粘性贴子,一个用于非粘性贴子。我已经设法使粘性帖子只显示在第1页上,而不显示在其余页面上(使用分页时),这正是我想要的。问题是:如果我将posts\\u per\\u page设置为8,并且数据库中有1篇粘性文章,那么第一页上会有9篇文章,其余页面上会有8篇文章。我已在循环之间使用此脚本成功更改了posts\\u per\\u page值:$postcount = $wp_query->post_count;