关闭
duanbeng1923 2015-10-21 05:33
浏览 48
已采纳

将新WP查询保存到数组以在single.php上使用的函数

Is it possible to run a function that always queries for a related post and saves that array to a variable in Wordpress?

if ( !function_exists( 'the_query_vars' ) ) {
function the_query_vars() {
  global $post;

  if ($post->post_status == 'publish') {  

    $args = array(
    'post_type' => 'sponsor'
    ,'posts_per_page' => 1
    ,'post_belongs' => $post->ID
    ,'post_status' => 'publish'
    ,'suppress_filters' => false
    );

    $sponsor_query = new WP_Query($args);
    return $the_query; 
  }
 add_action( 'init', 'the_sponsor_vars' );
} }

Then I just wanted to use the $the_query "object?" and use it as if I had done a regular new WP_Query() from within the template file? Calling it out with familiar hook like:

echo $the_query->post_title

Tried the simplest thing first: <?php print_r($the_query);?>

Been unsuccessful in returning the array of variables.

I considered that it was because the variable wasn't globally set, but I thought the advantage of the return command was to essentially store the results for use if the function is activated.

  • 写回答

1条回答 默认 最新

  • dqybeh2884 2015-10-21 05:59
    关注

    The function returns the Variable and not make it global. If you want to access the result you have to assign the result of the function to a variable.

    if (!function_exists('the_query_vars')) {
        function the_query_vars()
        {
            global $post;
    
            if ($post->post_status == 'publish') {
    
                $args = array(
                    'post_type' => 'sponsor'
                , 'posts_per_page' => 1
                , 'post_belongs' => $post->ID
                , 'post_status' => 'publish'
                , 'suppress_filters' => false
                );
    
                $sponsor_query = new WP_Query($args);
                return $sponsor_query;
            }
            add_action('init', 'the_sponsor_vars');
        }
    }
    

    and where you want to use the result of the function:

    $the_query = the_query_vars();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部