I’m trying to create a shortcode that displays a banner containing a post content (thumbnail, title and excerpt), using ID attribute. My goal is to be able to use a shortcode like [postbanner id=123] to display any post by its ID.
Here is my code (in function.php child theme):
function post_banner_shortcode($atts) {
$atts = shortcode_atts( array(
'id' => ''
), $atts );
$post_id = $atts['id'];
$HTML = '<div class="postbanner">';
$HTML .= '<div class="pb-thumb">' . get_the_post_thumbnail($post_id, 'medium') . '</div>';
$HTML .= '<div class="pb-ttl-txt">';
$HTML .= '<h4>' . get_the_title($post_id) . '</h4>';
$HTML .= '<p>' . get_the_excerpt($post_id) . '</p>';
$HTML .= '</div>';
$HTML .= '</div>';
return $html;
}
add_shortcode( 'postbanner', 'post_banner_shortcode' );
Actually this code return nothing and I don’t understant why. I’m missing something here. I’m still a rookie with PHP so that’s why I need some help guys 🙂
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Try $HTML instead of $html Linux based systems are case-sensitive …
function post_banner_shortcode($atts) {
$atts = shortcode_atts( array(
'id' => ''
), $atts );
$post_id = $atts['id'];
$HTML = '<div class="postbanner">';
$HTML .= '<div class="pb-thumb">' . get_the_post_thumbnail($post_id, 'medium') . '</div>';
$HTML .= '<div class="pb-ttl-txt">';
$HTML .= '<h4>' . get_the_title($post_id) . '</h4>';
$HTML .= '<p>' . get_the_excerpt($post_id) . '</p>';
$HTML .= '</div>';
$HTML .= '</div>';
return $HTML;
}
add_shortcode( 'postbanner', 'post_banner_shortcode' );
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0