I am using the WP "query" filter and in my function I want to use wp_get_current_user(). But I get a fatal error when I call it. Because the function isn't loaded by WP yet. Is there a fix. ?

public  function __construct() {
   add_filter('query', array($this,'my_func'), 10, 1);


function my_func($param){
   $current_user = wp_get_current_user(); // Getting fatal error here
  • can you post some code please? when are you hooking your function? – bynicolas Aug 11 '16 at 18:19
  • @bynicolas just did. – Adeel Aug 11 '16 at 18:22
  • Ok, maybe it would help if you gave more context in your question and tell what your end goal is to achieve. Maybe this filter is not the best one for your objective? – bynicolas Aug 11 '16 at 18:36

since the query filter is "applied to all queries (at least all queries run after plugins are loaded)" as stated here in the wordpress codex you should do a further test to make sure that you are in the query you want to be. Perhaps a certain query or queries is/are run before the one(s) you are targeting and this is why the function isn't loaded yet.

Possible options:

  • You could check that the function wp_get_current_user() exists before using it.
  • You could check is_user_logged_in(), but you may still need to check that this function exists as well
  • maybe you need to use a filter that runs at a later time, I don't know exactly why you chose this filter though, perhaps this isn't an option for you.
  • 1
    Indeed this was the case. I called it outside the specific condition and the issue was caused by that. thanks a lot @KnightHawk – Adeel Aug 11 '16 at 19:04

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.