在Bainternet上面的答案的基础上,我编写了这个快速插件,使其更加通用。您可能可以修改底部的链接构建函数,以更准确地执行您想要的操作。
<?php
/*
Plugin Name: Search Context
Description: Use search context on single post pages when they\'re reached from a search results page to adjust the prev/next post links.
Author: Otto
*/
add_action(\'init\',\'search_context_setup\');
function search_context_setup() {
global $wp;
$wp->add_query_var(\'sq\');
add_filter(\'previous_post_link\',\'search_context_previous_post_link\');
add_filter(\'next_post_link\',\'search_context_next_post_link\');
if (is_search()) {
add_filter(\'post_link\',\'search_context_add_search_context\');
}
}
function search_context_add_search_context($link) {
$sq = get_search_query();
if ( !empty( $sq ) )
$link = add_query_arg( array( \'sq\' => $sq ), $link );
return $link;
}
function search_context_previous_post_link($link) {
$sq = get_query_var(\'sq\');
if (empty($sq)) return $link;
return get_search_context_adjacent_link($link, $sq, true);
}
function search_context_next_post_link($link) {
$sq = get_query_var(\'sq\');
if (empty($sq)) return $link;
return get_search_context_adjacent_link($link, $sq, false);
}
function get_search_context_adjacent_link($link, $sq, $previous) {
global $post, $search_context_query;
if ( !$post ) return $link;
if (empty($search_context_query)) {
$search_context_query = get_posts(array(
\'posts_per_page\' => -1,
\'post_type\' => \'post\',
\'post_status\' => \'publish\',
\'fields\' => \'ids\',
\'s\' => $sq,
)
);
}
$key = array_search($post->ID, $search_context_query);
if ($previous) $key--;
else $key++;
if (!isset($search_context_query[$key])) return \'\';
$adjpost = get_post($search_context_query[$key]);
$title = $previous ? \'Previous Post\' : \'Next Post\';
$rel = $previous ? \'prev\' : \'next\';
$permalink = add_query_arg( array( \'sq\' => $sq ), get_permalink($adjpost) );
$string = \'<a href="\'.$permalink.\'" rel="\'.$rel.\'">\';
$output = $string . $title . \'</a>\';
return $output;
}
对于自定义帖子类型,您可能必须将“post\\u link”过滤器更改为“post\\u type\\u link”过滤器。您还需要调整函数以检查自定义帖子类型。像这样:
...
if (is_search()) {
add_filter(\'post_type_link\',\'search_context_add_search_context\',10,2);
}
...
以及
function search_context_add_search_context($link, $post) {
if ($post->post_type != \'YOUR-CUSTOM-TYPE\') return $link;
$sq = get_search_query();
if ( !empty( $sq ) )
$link = add_query_arg( array( \'sq\' => $sq ), $link );
return $link;
}
在get\\u search\\u context\\u neighboration\\u link函数中,您还需要更改查询中的post\\u type值。