【问题标题】:Use Ajax in Wordpress在 Wordpress 中使用 Ajax
【发布时间】:2017-04-12 05:31:27
【问题描述】:

我当前的查询是

$args=array(
    'post_type'=>'product',
    'post_per_page'=>'10',
    'tax_query' => array(
            array(
            'taxonomy' => 'product_cat',
            'field'    => 'slug',
            'terms'    => 'car',
                ),
                        ),
            );
    $loop=new WP_Query($args);

我有复选框Bus<input type="checkbox" class="ve-select" value="bus">

Boat<input type="checkbox" class="ve-select" value="boat">.

目前我所做的是当有人单击复选框时,我使用 javascript 重新加载页面并通过“ve”变量传递值。

$args=array(
    'post_type'=>'product',
    'post_per_page'=>'10',
    'tax_query' => array(
            array(
            'taxonomy' => 'product_cat',
            'field'    => 'slug',
            'terms'    => $_REQUEST['ve'],
                ),
                        ),
            );
    $loop=new WP_Query($args);

请任何人建议我如何更改查询并在不重新加载的情况下显示结果。

请帮助朋友。

【问题讨论】:

    标签: jquery json ajax wordpress wordpress-theming


    【解决方案1】:

    请尝试以下代码::

    在您的 post_page 中

    <script>
        function getPostList(val)
        {
            jQuery.ajax({
                url: '<?= admin_url('admin-ajax.php') ?>',
                data: {action:'my_action', term: val, secret: '<?php wp_create_nonce('listPost_byCat'); ?>'},
                method: 'POST',
                success: function(res){
                    jQuery('#post-div').html(res);
                }
            });   
        }
    
        jQuery(document).ready(function(){
            jQuery('.ve-select).on('click', function(){
                getPostList(jQuery(this).val());
            });
        });
    </script>
    

    在functions.php中

    <?php
        add_action('wp_ajax_my_action', 'my_action_handler');
        add_action('wp_ajax_nopriv_my_action', 'my_action_handler');
    
        function my_action_handler()
        {
            if(wp_verify_nonce($_POST['secret'], 'listPost_byCat')) 
            {
                $args=array(
                    'post_type'=>'product',
                    'post_per_page'=>'10',
                    'tax_query' => array(
                            array(
                                'taxonomy' => 'product_cat',
                                'field'    => 'slug',
                                'terms'    => $_POST['term'],
                            ),
                        ),
                    );
                $loop=new WP_Query($args);
    
                if(!empty($loop))
                {
                    foreach($loop as $post)
                    {
                        echo $post->post_title() . '<br/>';
                    }
                }
            }
        }
    ?>
    

    【讨论】:

    • 我会检查这个解决方案
    • 但我不知道这个。秘密:''
    猜你喜欢
    • 1970-01-01
    • 2021-10-22
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    • 2014-11-29
    • 2016-04-13
    • 2014-11-09
    相关资源
    最近更新 更多