【问题标题】:Add ability to search for a category name in ajax search field wordpress添加在 ajax 搜索字段 wordpress 中搜索类别名称的功能
【发布时间】:2015-12-20 00:08:05
【问题描述】:

我有一个用户可以搜索产品的 Wordpress ajax 搜索字段。我也希望能够按产品类别搜索。 “Whats new”、“限量版”等。如何查询和显示类别名称?

我还需要用户能够按位置名称进行搜索,并在单击时直接进入位置页面。因此,如果他们搜索“Walmart”或“Target”,链接将始终转到位置页面。该位置不会是分类法,所以我猜这必须用所有位置名称进行硬编码,这很好。我如何将其硬编码到查询中?

<?php
/*
** Custom search ajax
*/
add_action('wp_ajax_custom-search', 'search_ajax');
add_action('wp_ajax_nopriv_custom-search', 'search_ajax');
function search_ajax() {

 if($_GET['s'] === '') {
wp_send_json(array(
    'results' => [],

));
}
else {
$query = new WP_Query( array('s' => $_GET['s'], 'post_type' =>    array('product', 'tutorial') ) );

$query2 = new WP_Query( array('tag' => sanitize_title_with_dashes($_GET['s'])     . ',' . sanitize_title_with_dashes(preg_replace('/s$/i', '', $_GET['s'])) . ',' . sanitize_title_with_dashes(preg_replace('/es$/i', '', $_GET['s'])) , 'post_type' => array('product', 'tutorial') ) );






    $wp_query = new WP_Query();
    $wp_query->posts = array_merge( $query->posts, $query2->posts );
    $wp_query->post_count = $query->post_count + $query2->post_count;



wp_send_json(array(
    'results' => array_map(function($p) { return array( 'title'=>get_the_title($p),'uri'=>get_permalink($p),'category'=>get_the_category($p->ID, 'search_category'),'postType'=>get_post_type($p),'thumb'=>get_the_post_thumbnail($p->ID,'medium')); }, $wp_query->posts)
));
   }  


 }



?>

【问题讨论】:

    标签: php mysql ajax wordpress


    【解决方案1】:

    因为您可能会在打印页面时查询类别/位置,所以我只需将列表打印到 JS 数组中,然后使用自动完成插件即可。例如:https://jqueryui.com/autocomplete/ 但在某些情况下,我更喜欢 ajax 实时搜索,而不是这种情况。

    【讨论】:

      猜你喜欢
      • 2016-10-16
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      • 2014-04-12
      • 2021-08-14
      • 2021-12-31
      • 1970-01-01
      • 2017-03-21
      相关资源
      最近更新 更多