繁体   English   中英

使用Javascript变量作为WP_Query参数

[英]Using Javascript Variables as WP_Query Parameters

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

我正在使用AJAX Post Request向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函数执行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的棘手/不直观的部分。 这是一个命名约定,您my_actionwp_ajaxwp_ajax_no_priv之后追加操作名称wp_ajax_no_priv 注意,如果普通用户不应该触摸它,你就不会将你的动作挂钩到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'] ),
));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM