From your comment:
Apparently the function can indeed not be used on the frontend in wp
(see
here),
can anyone confirm this?
I can confirm that the post_exists()
function can be used on the front-end, but you need to manually load the file that defines the function, which is wp-admin/includes/post.php
— see the "File: <path>
" part in the "Source" section of the post_exists()
documentation.
And the file has to be manually loaded because WordPress doesn't load it on the non-admin side of the site, or that the function is only loaded automatically in the wp-admin area.
So I actually get a PHP error saying Call to undefined function MySpace\post_exists()
, why is that so?
I don't know for sure why, but logically thinking, it's because the calling function (MyClass::execute()
) is in the MySpace
namespace. So if it wasn't in a namespace, then the message would have not used "MySpace\", i.e. Call to undefined function post_exists()
.
The problem I get is that wp resolves the post_exists
function to
the namespace instead of falling
back
to the global scope
No, I don't think WordPress would not do that "resolves" thing, and what happened is likely this:
- PHP looked for a function named
post_exists
from the current namespace: MySpace\post_exists()
.
- PHP tried to find and call the global function
post_exists()
.
- Neither found, and so PHP threw the (fatal) error in question.
See the (7th) rule here which says, "For unqualified names, if no import rule applies and the name refers to a function or constant and the code is outside the global namespace, the name is resolved at runtime".
Additional Notes
- The 1st parameter for
post_exists()
is the post title, but it seemed that you've passed an ID (1
) instead. And if so, then you could just use get_post()
to check whether the post exists.