(@joyously)
The first line, setting $args
, is not needed (the variable is not used).
Read about the wp_get_recent_posts
function here: https://developer.wordpress.org/reference/functions/wp_get_recent_posts/
It says that the default return is an array, so when you use the result, you need to reference inside the array for the post ID to pass to get_post_type
like you did for get_the_date
.
You’re right, I forgot to delete the $args line, that came from a test with two variables. And thanks for the hint with the wp_get_recent_posts function! Maybe I can figure out how to realise it. For non-developers like me the official documentation is a bit cryptic. We’ll see. Thanks a lot anyway!
Wait, there’s more! 🙂 You’re running a simple PHP loop and not the formal WP “The Loop®” which iterates several global values behind the scene. This means template functions like get_the_*() which rely upon these globals will not work correctly without some extra help. Help by using setup_postdata() within your loop. It performs a similar function to the_post()
used in “The Loop®”.
Don’t forget to do global $post;
within scope of your code anytime you use setup_postdata()
.
(@joyously)
You shouldn’t need the global variables or the standard loop, because the data is in the array, and all the functions being called take a post ID as a parameter.
Indeed, I didn’t look close enough. Apologies for any confusion.
Thanks a lot for your help! I think I got in the right direction, also to understand the Loop a litte bit better. As suggested I read the post type with get_post_type and put it in a variable, then read it out with a if/else statement. And it seems to work! Here’s the final code:
$args = array( 'numberposts' => '1', 'post_type' => array('talks','post') , 'post_status' => 'publish', 'orderby' => 'date' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
$post_type = get_post_type($recent["ID"]);
if ($post_type == 'talks') {
echo 'Latest Talk from '. get_the_date('d F Y', $recent["ID"]) .':<br/><a href="' . get_permalink($recent["ID"]) . '">'. get_the_title( $recent["ID"] ) .'</a>';
} else {
echo 'Latest News from '. get_the_date('d F Y', $recent["ID"]) .':<br/><a href="' . get_permalink($recent["ID"]) . '">'. get_the_title( $recent["ID"] ) .'</a>';
}
}
I am very aware that the code can be beautified or simplified. For now, however, what counts is that it works, thanks to your help!