For a functions I need the post ID in my functions.php file. I must have the ID if the editpage is active.

What I tried so far

//method 1
global $post;

//method 2

//method 3

If I echo $post->ID or $post_id or get_queried_object_id() they give nothing / empty

Who can help me?

  • Is your function hooked to a particular action or filter hook? It'll help us a lot if you edit your question to show us more of your code.
    – Pat J
    Commented Apr 22, 2021 at 0:42
  • In functions.php the query has not happened yet, WordPress hasn't parsed the URL or fetched posts yet
    – Tom J Nowell
    Commented Apr 22, 2021 at 14:13

1 Answer 1


It depends on, where you are calling these functions. That is the point, where you enter the var into the function.

First, remove the global $post from your functions.php! It makes no sense there! In the functions.php you declare the functions, not call them!

I assume, you call your function in some template. So the functions.php should look like this:

function myfunction($post) {
    // $post is now a copy of the $post object, it needs to be passed in the call. See below!


Or you could use the global keyword, to make the $post variable available inside the function:

function myFunction() {
    global $post;
    // now you can use $post from the global scope


So, you could use $post globally, using the global keyword inside the function (second example), or you can pass the $post variable as a function parameter (first example). Both have their pros and cons, e.g. if you pass it as a parameter, PHP copies the $post object for usage inside the function, whereas using global it uses the original. I recommend reading up on PHP scopes. :)

Now you have a correct declaration of the function - you are ready to call it! In your template, or whereever you are, do this:

<?php myFunction($post); ?>


<?php myFunction(); ?>

depending on which version you decided on. In any case, you'll probably need to do this inside the_loop!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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