如何在WordPress查询字符串中使用javascript变量


How do i use a javascript variable in wordpress query string?

我需要找到一种方法在wordpress查询字符串中使用js变量。我知道它涉及ajax,但我不知道该怎么做。请帮忙!

 <script>
$(document).ready(function(e) {
var x=$(this).find('.resp-tabs-list li').attr('id');
//alert(x);
});
 $('.resp-tabs-list').on('click',function(e){
        var x   =   $(this).find('.resp-tab-active').attr('id');
        //alert(x);
});
</script>

在上面的代码中,我获取了"x",这是类别 ID,我想基于它循环获取帖子。

你是对的,它确实涉及ajax。 您需要执行以下操作(我还没有测试过它,但它应该会让您走上正确的轨道):

Javascript(假设你已经加载了jQuery,并且你已经使用PHP将管理url输出为javascript变量ajaxurl):

$(document).ready(function() {
    bindCategoryFilter();
}
function bindCategoryFilter() {
     $('.resp-tabs-list').on('click',function(e){
        var x   =   $(this).find('.resp-tab-active').attr('id');
        $.ajax({
           type: 'POST',
           url: ajaxurl,
           data: {
              //this is the name of our Wordpress action we'll perform
              'action' : 'get_ajax_posts',
              //this is the important line--send 'x' to the server as category
              'category' : x
           },
           success: function(data) {
            //do whatever with the data you're getting back
            //with the PHP below, it's an array of the post objects
        }
    });
});

这会将数据发布到我们的服务器,变量'category'设置为 x$_POST变量中。 要访问它,您需要在functions.php中添加如下所示的内容:

//add our action hooks--wp_ajax_XXXXX is defined in the ajax query as 'action'
//the second argument is the name of the PHP function we're calling
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
function get_ajax_posts() {
    if(isset($_POST['category'])) {
         //get all the posts in the category, add more arguments as needed
         $posts = get_posts(array('category' => $_POST['category']));
        //data is returned to javascript by echoing it back out
        //for example, to return all of the post objects (which you probably don't wnat to do)
        echo json_encode($posts);
        //we're done
        die();
    }
}

有关 AJAX 和 Wordpress 的更多信息,请参阅 wordpress codex。