我在WordPress中运行查询,需要稍后在我的脚本中重复使用$my_query_results
变量。
function init() {
$args = array(
'post_type' => 'post'
);
$my_query_results = new WP_Query( $args );
}
-
function process() {
// I need to process $my_query_results here.
}
add_action( 'wp_ajax_myaction', 'process' );
我不想在process()
内重新运行查询。如何使$my_query_results
功能可以使用process()
?
背景信息 process()
函数处理通过AJAX请求发送的数据。处理完毕后,它会向浏览器发送响应。例如:echo json_encode( $response )
答案 0 :(得分:5)
如果这些函数存在于同一个类中,则可以将其分配给类属性:
class Class
{
public $my_query_results;
function init(){
$args = array(
'post_type' => 'post'
);
$this->my_query_results = new WP_Query( $args );
}
function process() {
// access $this->my_query_results
}
}
答案 1 :(得分:1)
您可以将变量作为参数传递
function init(&$my_query_results) {
$args = array(
'post_type' => 'post'
);
$my_query_results = new WP_Query( $args );
}
function process(&$my_query_results) {
// I need to process $my_query_results here.
}
使用
init($my_query_results);
process($my_query_results);
答案 2 :(得分:-3)
或者你可以简单地做全局变量:
$my_query_results = null;
function init() {
$args = array(
'post_type' => 'post'
);
$my_query_results = new WP_Query( $args );
}