Use post ID in functions.php file adminside

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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!


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x