WordPress Development Asked by dodov on January 14, 2021
When I do something like:
$prevPost = get_previous_post();
I can then do:
$prevPost->post_title;
$prevPost->post_content;
...
Why can’t I get the permalink?
$prevPost->post_url; // NULL
$prevPost->post_permalink; // NULL
Obviously, as stated in the codex, that class doesn’t have these properties. However, it seems logical to have the post URL as part of the post. Why is that not the case?
To get the permalink, I need to do:
get_permalink($prevPost);
But then, I can’t do something like this to get the title:
get_title($prevPost);
What’s the reason for these inconsistencies? Why do I have to get some of the post data via the post object and other – with the get
functions? I’m relatively new to WordPress, so an article explaining it all would be much appreciated.
Are there any other types of data that share these inconsistencies? What are they?
WP_Post is a representation of the post as it exists in the database, and the permalink isn't stored in the database.
It's not stored in the database because it's not a property of the post. The permalink is determined by the site's address, its permalink structure, and the post's slug. Imagine if updating the permalink structure on your site required that every post in the database had to be updated.
But then, I can't do something like this to get the title:
get_title($prevPost);
You can
get_the_title($prevPost);
For consistency's sake, you can also do:
get_the_permalink($prevPost);
Correct answer by Jacob Peattie on January 14, 2021
Try
the_permalink($post_object->ID);
Answered by user193213 on January 14, 2021
While it's possible to access post content directly from the post object, you should not do this. All data should be accessed via the API functions- title, content, etc., so all applicable filters will be applied. Accessing data directly will break formatting and many plugin functions.
Answered by Milo on January 14, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP