使用AJAX对WordPress帖子进行排序

时间:2018-09-05 作者:Alt C

我有一个自定义帖子类型的搜索结果页。我想要一个ajax排序功能。例如,在不重新加载页面的情况下,按分类法对帖子进行排序。一个非常基本的示例将有所帮助。谢谢enter image description here

搜索表单:

<form id="cptsearch" action="/" method="get">
    <input type="text" name="s" />
    <input type="hidden" name="post_type" value="lat" />
    <input id="searchsubmit" type="submit" alt="Search" value="Search" />
</form>
模板选择器:

function template_chooser($template) {
    global $wp_query;
    $post_type = get_query_var(\'post_type\');
    if( $wp_query->is_search && $post_type == \'lat\' ) {
    return locate_template(\'page_lat.php\');
    }
    return $template;
}
add_filter(\'template_include\', \'template_chooser\');
This is the output template page_lat.php :

搜索结果(当前仅打印标题和帖子类型:

if($_GET[\'s\'] && !empty($_GET[\'s\'])){

  $text =$_GET[\'s\'];
}
 ?>


 <div class="container">

      <?php
        $args = array(
          \'post_per_page\'=> -1,
          \'s\'=>$text
        );

        $query= new WP_Query($args);
        while($query->have_posts()): $query->the_post();
      ?>

      <div>
        <h5><?php the_title(); ?></h5>
        <strong>
          <?php echo get_post_type(); ?>
        </strong>
      </div>
    <?php endwhile; wp_reset_query(); ?>
  </div>

4 个回复
最合适的回答,由SO网友:sakshi ranga 整理而成

所以这是一个很长的问题,所以给你一个简单的例子,它将在步骤1)Cat1 cat2 Cat3中起作用。首先,你需要在表单中调用自定义分类法

步骤2)假设您有cat1 cat2作为复选框,其值为自定义分类id

步骤3)添加单击事件

步骤4)调用ajax函数

转到此示例-http://www.tinyjewelbox.com/product-category/jewelry/ - 我希望您想要实现这个点击复选框是自定义分类法,点击过滤根据分类法排序。

方法-让我们开始:-

这是输出模板页面\\u lat.php:

搜索结果(当前仅打印标题和帖子类型:

            <?php 
            if($_GET[\'s\'] && !empty($_GET[\'s\'])){
              $text =$_GET[\'s\'];
              $posttype = $_GET[\'post_type\'];

            }
            else{
                $posttype = \'custom_post_type\';
            }
            ?>
            //This will fetch your custom taxonomy cat1, cat2 , cat3

            <form action="" method="" class="" id="filter-menu" >
            <?php 
            $terms = get_terms(\'post_tag\',, array(\'hide_empty\' => false) );
            foreach($terms as $filteroption)
            {
                <input type="checkbox"  name="filter[]" value="<?php echo $filteroption->term_id; ?>" onclick="filtermenu()" >  
                <?php echo $filteroption->name; ?>
            }
            <input type="hidden" name="posttype" id="posttype" value="<?php echo $posttype; ?>" />
            ?>
            <form>
             <div class="container">
                 <div class="load_html">

                      <?php
                        $args = array(
                          \'post_per_page\'=> -1,
                          \'s\'=>$text
                        );

                        $query= new WP_Query($args);
                        while($query->have_posts()): $query->the_post();
                      ?>

                      <div>
                        <h5><?php the_title(); ?></h5>
                        <strong>
                          <?php echo get_post_type(); ?>
                        </strong>
                      </div>
                    <?php endwhile; wp_reset_query(); ?>
                  </div>
              </div>
单击时添加单击事件

                <script> //this a click event of checkbox which call ajax action
            function filtermenu(paged)
            {   
            var filtercheckedbox = // get your checkbox value via jquery; 
            var posttype = // get your posttype value; jQuery(\'#posttype\').val(0);
            jQuery.ajax({
                url: AJAXURL,
                data: {
                    \'action\' : \'filter_menu\' ,
                    \'checkbox\': filtercheckedbox, 
                    \'posttype\' :posttype,
                    \'paged\' : 1, 
                },
                type: \'POST\',
                success: function(data) {
                        jQuery(".load_html").html(data);    
                }
            });     

            }   
            </script>
将操作添加到函数中。php

            <?php 
            // add this function to functions.php this is your ajax action 
            add_action( \'wp_ajax_filter_menu\', \'wp_ajax_filter_menu\' );
            add_action( \'wp_ajax_nopriv_filter_menu\', \'wp_ajax_filter_menu\' );

            function wp_ajax_filter_menu()
            {
            global $post, $wp_query;

            $args = array(
                \'post_type\' => \'$_POST[\'post_type\']\',
                \'tax_query\' => array(
                                \'relation\' => \'AND\',
                                 array(
                                    \'taxonomy\' => \'custom_taxonomy name\',
                                    \'field\'    => \'term_id\',
                                    \'terms\'    => array($_POST[\'checkbox\']),
                                 ),
                ),
                \'orderby\'   => \'ASC\',                   
            );

                $filteroption = new WP_Query( $args );
                if ( $filteroption->have_posts() ) :
                while ($filteroption->have_posts()) : $filteroption->the_post();
                  ?>

                  <div>
                    <h5><?php the_title(); ?></h5>

                  </div>
                <?php 
                endwhile; 
                else: 
                    return false; 
                endif;
            }   
            die;
            }
            ?>

SO网友:Dionoh

请再仔细研究一下:

get terms:

$type   = get_terms( array(\'type\') );

Fetch all your taxonomies:

foreach ($type as $t) {
        if(!in_array($t->term_id, $type)){
                    echo \'<label class="filter \'.$t->slug.\'">\';
                    echo \'<input type="checkbox" data-filter=".\'. $t->term_id .\'" class="filter-check \'. $t->term_id .\'" value="\'. $t->term_id .\'" name="type[]" ><div class="filter-title">\'. $t->name .\'</div>\';
                    echo \'</label>\';
        }
}

look into your custom post type

if( !empty( $_POST[\'options_type\'] ) ){
    array_push($args[\'tax_query\'],   array(
              \'taxonomy\' => \'type\',
              \'field\'    => \'term_id\',
              \'terms\'    => $_POST[\'options_type\'],
            )
          );
   }

in js file execute your ajax call

$("input:checkbox").on( "change", function() {

            var options_type = Array();
$( \'input[name="type[]"]:checked\' ).each(function( index, value ) {
          options_type.push( $(this).val() );
            });

  jQuery.ajax({
            url : filters.ajax_filter,
            type : \'post\',
            data : {
                action : \'filter_reports\',
                options_type : options_type,
}}});

SO网友:David Corp

使用xmlhttp请求执行

<button type="button" onclick="loadDoc()">Sort Type X</button>
<div id="result"></div>
<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("result").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "//example.com/s.php", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("search=XXX&sort=YYY");
}
</script>
在s.php中

    <?php
        $xxx = $_POST[\'search\'];
        $yyyy = $_POST[\'sort\'];
        $args = array( //your query
        );
        while ( have_posts() ): the_post();
        // display post
        if ( have_posts() ): // If this is the last post, the loop will start over
                // Do something if this isn\'t the last post
        endif;
endwhile;
        ?>

SO网友:RiddleMeThis

只需将orderby和/或order添加到参数中即可。例如

    $args = array(
      \'post_per_page\'=> -1,
      \'s\'=>$text,
      \'orderby\' => \'title\',
      \'order\'   => \'DESC\',
    );
这里是more info

结束

相关推荐

WP AJAX操作未拾取查询字符串参数

不知道为什么这不起作用。。。我的操作正在被传递,正确的函数正在从ajax中启动,但回调没有接收到query 参数我的ajax(使用bloodhound.js 从管理屏幕运行,因此无需localize):new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace(\'value\'), queryTokenizer: Bloodhound.tokenizers.whitespace, re