javascript - 使用 Javascript 变量作为 WP_Query 参数

标签 javascript php jquery ajax wordpress

我在尝试使用 Javascript 变量作为 WordPress 查询参数时遇到了一些问题。

我正在使用 AJAX 发布请求向 Wordpress 发送 post_ids 的 Javascript 数组。

$.post('url', { data: requestIds }, function(response) { console.log(response) });

我基本上是在尝试将“requestIds”的 Javascript 数组作为 post__in WP_Query 参数传递。

$COMPARISON_QUERY = new WP_Query(array(
    'post_type' => array('Post'),
    'post__in' => // this is where the array would be passed as a parameter
));

这是处理请求的 PHP:

$response_object = DecodeJSONString($_POST['data']);

function DecodeJSONString($string) {
    $decoded_string = json_decode($string);
    return $decoded_string; // this would be the query parameter
}

感谢任何反馈!

最佳答案

您应该使用 WordPress ajax functions 执行 ajax 请求,而不是直接发布到您的 php 文件中。 .

假设您正在使用的自定义 php 文件名为 process_post.php。不要直接发布到您的自定义 php 文件,而是发布到 admin-ajax.php 并在您的 functions.php 文件中处理该帖子。

在您的前端页面上:

<script>
    var ajaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>"; // This will get the approriate ajax url using wordpress functionality
    $.post(  ajaxUrl, 
         { 
            'action': 'my_action',
            'requestIds': requestIds // Assuming you have your requestIds var populated already 
         },
         function(response) {
           console.log(response)
         });
</script>

现在在 php 端有一个关于注册你的 ajax 操作 my_action 的棘手/不直观的部分。这是一种命名约定,您可以在 wp_ajaxwp_ajax_no_priv 之后附加操作名称 my_action。请注意,如果普通用户不应该触摸它,则您不会将您的操作连接到 wp_ajax_no_priv

第一个参数是命名约定,第二个参数是您的自定义函数名称:

<?php // in functions.php
add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
?>

现在您已经设置了 ajax 操作!现在创建回调函数,也在 functions.php 中。我经常像这样从这一点开始包含单独的 php 文件:

<?php // Still in functions.php
function my_action_callback(){
    include_once('my_code.php');
}
?>

现在您已经正确设置了所有这些,您不再需要包含不同的核心 WordPress 类!这是以这种方式设置它的所有麻烦的主要原因。

my_code.php 中,在我的示例中将驻留在您的主题中:

<?php
$COMPARISON_QUERY = new WP_Query(array(
    'post_type' => array('Post'),
    'post__in' => json_decode( $_POST['requestIds'] ),
));

关于javascript - 使用 Javascript 变量作为 WP_Query 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34132847/

相关文章:

JQuery UI 菜单 - 第一个 li 有额外的高度

javascript - Google Chrome 扩展程序中的 JSONP 通信

javascript - CoffeeScript:对象初始化器中的 Getter/Setter

php - godaddy 托管中的 Laravel 安装,如何使用 .htaccess 防止访问/公开

php - 用 PHP 正则表达式替换单词或单词组合

javascript - 在javascript中部分修改 anchor href的最佳方法是什么

javascript - JS 跨浏览器不一致/差异

javascript - Android 将未知字符串传递给 javascript

PHP:foreach中的glob与每一行相乘?

javascript - 如何让我的 CSS slider 自动播放?