按标签WP

时间:2017-07-28 09:34:01

标签: javascript php jquery ajax wordpress

我已经在我的WordPress主题中创建了自定义搜索表单。她看起来像:

<form role="search" class="form" method="get" action="<?php echo home_url('/');?>">
  <input type="search" id="keyword" class="inp-search" onclick="showNewTag()" oninput="searchTags()" onkeyup="fetch()" placeholder="search by tag" value="<?php echo get_search_query() ?>" name="s" title="Search" />

我通过POST标题实现了自定义AJAX搜索。但我的任务是按标签搜索。我不知道我怎么能这样做。我的帖子标题搜索位于functions.php,看起来像:

add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
  function fetch(){

    jQuery.ajax({
    url: '<?php echo admin_url('admin-ajax.php'); ?>',
    type: 'post',
    data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
    success: function(data) {
        jQuery('#grid').html( data );
    }
});

}
</script>

<?php
}

 add_action('wp_ajax_data_fetch' , 'data_fetch');
 add_action('wp_ajax_nopriv_data_fetch','data_fetch');
 function data_fetch(){

   $the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => 
 esc_attr( $_POST['keyword'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) :
    while( $the_query->have_posts() ): $the_query->the_post(); 

        if(get_field('type') == "box") {
            ?>
            <div class="grid-item grid-item--<?php echo get_field('type');?> <?php echo get_field('position');?>" data-tooltitle="Hood Baroque" data-tooltip="Design | 3D modeling | Drawings">
                <a class="linkpost" href="<?php echo get_post_permalink()?>"><img src="<?php the_field('picture');?>" alt=""></a>
                <a href="<?php echo get_post_permalink()?>" class="text">
                    <img src="<?php the_field('svg_picture');?>" alt="">
                </a>
            </div>
    <?php

        } else {
    ?>
    <div class="grid-item grid-item--<?php echo get_field('type');?> left" data-tooltitle="Hood Baroque" data-tooltip="Design | 3D modeling | Drawings">
        <a class="linkpost" href="<?php echo get_post_permalink()?>"><img src="<?php echo get_field('picture');?>" alt=""></a>
            <a href="<?php echo get_post_permalink()?>" class="text">
                <img src="<?php echo get_field('svg_picture');?>" alt="">
            </a>
    </div>

    <?php 
        }

     endwhile;
    wp_reset_postdata();  
endif;

die();
}

我如何才能通过标签实现搜索?

1 个答案:

答案 0 :(得分:0)

来自codex

显示多个标签的帖子

显示包含以下任一标签的帖子:

$query = new WP_Query( array( 'tag' => 'bread,baking' ) );

显示包含“所有”这些标记的帖子:

$query = new WP_Query( array( 'tag' => 'bread+baking+recipe' ) );