致命错误:未捕获错误:调用未定义的函数get_userdata()

时间:2017-10-24 作者:mohsin

调用此方法时出现此错误$query->the_post();. 我正在尝试获取帖子id以获取帖子元数据。访问$post->ID 从…起global post 返回当前页面id,但我需要用于搜索目的的帖子id。

You can see the error as image here

function search_form_submit(){

$task_name  = isset($_GET[\'taskname\']) ? $_GET[\'taskname\'] : \'\';
$meta_key = \'wp_tasks\';

$args = array(
                    \'post_type\' => \'tasks\',
                    \'post_status\' => \'publish\',
                    \'posts_per_page\' => 5,
                    \'meta_query\' => array(
                        array(
                            \'key\' => $meta_key,
            \'value\' => $task_name,
                            \'compare\' => \'LIKE\',
                        ),
                    ),
                );


$query = new WP_Query($args);
global $post;

if($query->have_posts()){

    $query->the_post();

    $data = get_post_meta($post->ID,$meta_key,true);
     }
 }

 $tasks_obj = new tasks();

  if($_SERVER[\'REQUEST_METHOD\'] == \'GET\') {
  $tasks_obj->search_form_submit();
 }

1 个回复
最合适的回答,由SO网友:cybmeta 整理而成

通常,表格应在init 操作或更高版本(主要在插件文件中,可能在主题的functions.php文件中,而不是在tempalte文件中),因此您可以访问WP函数。

add_action( \'init\', \'search_form_submit\' );
function search_form_submit(){

    $task_name  = isset($_GET[\'taskname\']) ? $_GET[\'taskname\'] : \'\';
    $meta_key = \'wp_tasks\';

    $args = array(
                        \'post_type\' => \'tasks\',
                        \'post_status\' => \'publish\',
                        \'posts_per_page\' => 5,
                        \'meta_query\' => array(
                            array(
                                \'key\' => $meta_key,
                \'value\' => $task_name,
                                \'compare\' => \'LIKE\',
                            ),
                        ),
                    );


    $query = new WP_Query($args);

    if($query->have_posts()){

        $query->the_post();

        $data = get_post_meta(get_the_ID(),$meta_key,true);
         }
     }

     $tasks_obj = new tasks();

     if($_SERVER[\'REQUEST_METHOD\'] == \'GET\') {
      $tasks_obj->search_form_submit();
     }

}

结束

相关推荐

Virtual Pages plugins

我很难让插件正常工作Virtual Pages (WordPress插件可简化虚拟页面的创建)我确实进行了编辑,根据查询创建了一个循环。add_action( \'gm_virtual_pages\', function( $controller ) { /* Creating virtuals pages for companies */ $args = array( \'post_type\' => array(\'companies\',), \'post_status\'