I'm new to wordpress and I'm trying to accomplish the following goal:
I have a custom type albums seeded by a plugin and I would like to display this data in a list.
I installed the Code Snippets Plugin and was able to create a following working shortcode:
function display_albums_shortcode() {
$query = new WP_Query(
array(
'post_type' => 'albums'
));
$output = '<section>';
if ($query->have_posts()):
while ( $query->have_posts() ):
$album = $query->the_post();
$output .= '<div><figure>' . get_the_title($album) . ' </figure></div>';
endwhile;
endif;
$output .= '</section>';
wp_reset_postdata();
return $output;
}
add_shortcode('display_albums', 'display_albums_shortcode');
However, I would like to make it modularize it a bit. I would like to have an isolated function (code snippet) called render_album_list_item that takes the album as an argument and returns the HTML:
function render_album_list_item($album) {
$output = '<div><figure>' . get_the_title($album) . ' </figure></div>';
return $output;
}
Subsequently, I would like to call render_album_list_item inside of the first code snippet, something like:
function display_albums_shortcode() {
$query = new WP_Query(
array(
'post_type' => 'albums'
));
$output = '<section>';
if ($query->have_posts()):
while ( $query->have_posts() ):
$album = $query->the_post();
$output .= render_album_list_item($album);
endwhile;
endif;
$output .= '</section>';
wp_reset_postdata();
return $output;
}
add_shortcode('display_albums', 'display_albums_shortcode');
Unfortunately, I cannot make the snippet above work and haven't found anything in the documentation.
Also: is this the only way how to display the data - by manually creating a HTML string? Coming from a ReactJS world, this approach is pretty nasty. Any ideas, advice would be appreciated!
Thanks!
the_post
does not return the post,$foo = $query->the_post()
resolves tonull
/undefined, not a post object – Tom J Nowell♦ Oct 27 '20 at 14:54<?php /** Plugin name: 1 line plugin */
) – Tom J Nowell♦ Oct 27 '20 at 14:58