Question

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?

Était-ce utile?

La solution

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!

Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange
scroll top