【问题标题】:Wordpress custom search page for custom post type用于自定义帖子类型的 Wordpress 自定义搜索页面
【发布时间】:2012-11-12 17:03:55
【问题描述】:

我有一个自定义帖子类型recipes,它使用archive-recipes.php 模板在网站上显示食谱的分页列表。

我需要能够使用页面顶部的搜索表单来搜索这些食谱:

<form role="search" method="get" class="searchbox" action="/recipes/">
    <input type="text" class="textbox strong" name="s" id="s" value="" placeholder="Search..." />
    <input type="hidden" name="post_type" value="recipes" />                     
    <button type="submit" class="button icon"></button>
</form>

是否可以在搜索完成后返回此食谱列表页面并以与列表相同的样式显示结果?

我似乎找不到任何可以让我为自定义帖子类型创建自定义搜索页面的内容。

感谢您的帮助。

【问题讨论】:

    标签: wordpress custom-post-type


    【解决方案1】:

    您可以使用“template_include”过滤器。

    例如在你的函数文件中。

    function template_chooser($template)
    {
      global $wp_query;
      $post_type = get_query_var('post_type');
      if( $wp_query->is_search && $post_type == 'recipes' )
      {
        return locate_template('archive-recipes.php');
      }
      return $template;
    }
    add_filter('template_include', 'template_chooser');
    

    这应该检查“食谱”自定义帖子类型的搜索,并使用您的存档页面模板获取结果。

    【讨论】:

    • 谢谢@noisymask。看起来它应该像我需要的那样工作,但是在调试 $wp_query 时,我注意到 sql 请求包含对所有帖子类型的搜索,而不仅仅是“食谱”。有什么想法吗?
    • nvm,我使用的 WP Roots 框架搞砸了重写。再次感谢。
    • 上述方案效果很好;但是我发现get_query_var('post_type') 返回了一个包含所有已注册帖子类型的数组。相反,我会使用$post_type = get_post_type();。此外,要保存对多种帖子类型的一些条件检查:return locate_template('archive-' . $post_type . '.php');
    猜你喜欢
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多