0

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

<?php
//method 1
global $post;
my_function($post->ID);

//method 2
my_function($post_id);

//method 3
my_function(get_queried_object_id());
?>

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

Who can help me?

2
  • 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
    Apr 22 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
    Apr 22 at 14:13
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!

    do_something($post->ID);
}

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

    do_something($post->ID);
}

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); ?>

or

<?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, privacy policy and cookie policy

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