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

时间:2016-02-12 08:04:17

标签: javascript php wordpress

我需要找到一种在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,我想在循环中获取帖子。

1 个答案:

答案 0 :(得分:0)

你说它确实涉及ajax。你需要做类似下面的事情(我没有测试过,但它应该让你走上正轨):

Javascript(假设您已加载jQuery,并且您已使用PHP将管理网址输出为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
        }
    });
});

这将POST数据发送到我们的服务器,变量'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的更多信息,请参阅the wordpress codex