使用Javascript变量作为WP_查询参数
尝试使用Javascript变量作为WordPress查询参数时遇到一些问题使用Javascript变量作为WP_查询参数,javascript,php,jquery,ajax,wordpress,Javascript,Php,Jquery,Ajax,Wordpress,尝试使用Javascript变量作为WordPress查询参数时遇到一些问题 $COMPARISON_QUERY = new WP_Query(array( 'post_type' => array('Post'), 'post__in' => // this is where the array would be passed as a parameter )); 我正在使用AJAX post请求向Wordpress发送一个包含post\u id的Javascri
$COMPARISON_QUERY = new WP_Query(array(
'post_type' => array('Post'),
'post__in' => // this is where the array would be passed as a parameter
));
我正在使用AJAX post请求向Wordpress发送一个包含post\u id
的Javascript数组
$.post('url',{data:requestIds},函数(响应){console.log(响应)})代码>
我基本上是试图将'requestId'的Javascript数组作为post\u in
WP\u查询参数传递
$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
}
谢谢你的反馈 不要直接发布到php文件中,而应该使用
假设您使用的定制php文件名为process\u 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>
现在您已经设置了ajax操作!现在在functions.php
中创建回调函数。我通常只包含单独的php文件,如下所示:
<?php // Still in functions.php
function my_action_callback(){
include_once('my_code.php');
}
?>
那么您遇到了什么问题呢?为了使用WP_查询,我需要包括以下内容:define('WP_use_THEMES',false);需要_一次('../../../wp load.php');但是,这样做会破坏json_decode函数,使数组的值为“NULL”。也就是说,当我尝试将其用作参数时,我只是将NULL作为post_uuin传递。请只var_dump($\u post)
并编辑您的问题以显示输出-可能您发送的是常规键值对,而不是JSONTANKS Connor-您能否确认var_dump输出是否用于包含定义行和要求行时?你的函数会中断似乎很奇怪,但可能已经有一个函数同名了。你能直接调用json\u decode
吗?永远不要使用require\u一次('../../../wp load.php')
这是一个老生常谈的话题,应该放在某个地方:谢谢!我设法用一种与你上面发布的方法非常相似的方法解决了我的问题!尽管如此,我必须本地化我的ajaxurl,因为我直接从.js文件工作。这段视频非常有帮助,因此对于未来有此问题的人:
<?php
$COMPARISON_QUERY = new WP_Query(array(
'post_type' => array('Post'),
'post__in' => json_decode( $_POST['requestIds'] ),
));