我正在编写一个创建多个自定义帖子类型 (CPT) 的 Wordpress 插件。因为他们有自己的自定义字段,需要显示在搜索结果中,我需要自定义搜索结果输出。
我是否需要为此编写自己的主题,或者在我的插件代码中是否有一个钩子(或其他方式)来解决这个问题?
我正在编写一个创建多个自定义帖子类型 (CPT) 的 Wordpress 插件。因为他们有自己的自定义字段,需要显示在搜索结果中,我需要自定义搜索结果输出。
我是否需要为此编写自己的主题,或者在我的插件代码中是否有一个钩子(或其他方式)来解决这个问题?
您可以挂钩get_the_content
并get_the_excerpt
过滤并测试is_search()
以查看是否应该更改返回值。
未经测试,但这是一个想法:
add_filter( 'get_the_excerpt', 'my_search_excerpt' );
add_filter( 'get_the_content', 'my_search_excerpt' );
function my_search_excerpt( $content ) {
if ( is_search() )
$content = 'This is a search excerpt for ' . get_the_title();
// maybe add a read more link
// also, you can use global $post to access the current search result
}
return $content;
}
我看到四种可能性:
template_include
)the_content
或the_excerpt
最简单的方法可能是复制已安装主题的search.php
文件并对其进行修改以满足您的需求。然后,您可以使用第一种或第二种方式将其挂钩。第一个要求您创建一个子主题,第二个要求您创建一个插件。后者可能更复杂,所以我建议创建一个主题(查看子主题的模板文件以获得解释)。