【问题标题】:How do i use a javascript variable in wordpress query string?如何在 wordpress 查询字符串中使用 javascript 变量?
【发布时间】:2016-02-12 08:04:17
【问题描述】:

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

【问题讨论】:

标签: javascript php wordpress


【解决方案1】:

你说得对,它确实涉及 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
        }
    });
});

这会将数据发布到我们的服务器,$_POST 变量中的变量 'category' 设置为 x。要访问此内容,请在您的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 2011-11-30
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 2021-09-16
    • 2011-03-12
    相关资源
    最近更新 更多