I am building a plugin and have used the simple query:

function getTotal($postType){
  $total = 0;

  $args = array(
   'post_type' => $postType,
  $metrics = new WP_Query( $args );

  foreach( $metrics->get_posts() as $post ) {


  return $total;

But the moment I add this code to my plugin, the following error:

Fatal error: Uncaught Error: Call to undefined function is_user_logged_in() in C:\xampp\htdocs\sam\wp-includes\class-wp-query.php:2352 Stack trace: #0 C:\xampp\htdocs\sam\wp-includes\class-wp-query.php(3222): WP_Query->get_posts() #1 C:\xampp\htdocs\sam\wp-includes\class-wp-query.php(3328): WP_Query->query(Array) #2 C:\xampp\htdocs\sam\wp-content\plugins\sample_plugin\Models\dataModels.php(62): WP_Query->__construct(Array) #3 C:\xampp\htdocs\sam\wp-content\plugins\sample_plugin\Views\counselorTable.php(3): getCounselors() #4 C:\xampp\htdocs\sam\wp-content\plugins\sample_plugin\sample_plugin.php(20): require('C:\xampp\htdocs...') #5 C:\xampp\htdocs\sam\wp-settings.php(305): include_once('C:\xampp\htdocs...') #6 C:\xampp\htdocs\sam\wp-config.php(91): require_once('C:\xampp\htdocs...') #7 C:\xampp\htdocs\sam\wp-load.php(37): require_once('C:\xampp\htdocs...') #8 C:\xampp\htdocs\sam\wp-blog-header.php(13): require_once('C:\xampp\htdocs...') #9 C:\xampp\htdocs\sam\index.php(17): require('C:\xampp\htdocs. in C:\xampp\htdocs\sam\wp-includes\class-wp-query.php on line 2352

I've been looking for some time now, but can't find any direct explanation for the issue here. Guidance please?

  • I'm sorry. I'm an idiot. It looks like I may have solved the issue. I believe the function call was being initiated in the global scope, rather then from within another function. When I move the function call out of the global space, the error went away. I apologize for this post. – Uriah Jeshurun Jan 19 '18 at 16:42
  • 2
    Don't apologise! Write it as an answer, that way other people who have the same issue can see your solution, and people can upvote! ( with rep you get the adverts removed and priviledges, and the anti-spam system is friendlier to you ) – Tom J Nowell Jan 19 '18 at 17:02

One of the function call was written in the global scope, and firing before all the scripts could be properly loaded. Moving the function call out of the global space, the error went away. Functions that require or use WordPress functions should not be called before WordPress has successfully loaded it's scripts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.