I am also banging my head against the ‘my_custom_popular_posts_html_list’ examples in documentation in case that is a better approach but I am a little in over my head ??
Yeah, I know that feeling. That’s the reason why I recently implemented a new filter hook that a lot easier to use: wpp_parse_custom_content_tags. And we’re going to use it right now.
I’m sure you’re aware that the post_html
parameter accepts what I call “Content Tags” (eg. {thumb}
), which are basically placeholders that are replaced with predefined HTML content. Since version 4.2.0, you can add your own custom Content Tags by registering them via the filter hook I linked above.
Since we’re both developers, I’m sure you want to see some actual code to understand what I’m talking about so here it goes:
/**
* Parses custom content tags in WordPress Popular Posts.
*
* @param string $html The HTML markup from the plugin.
* @param integer $post_id The post/page ID.
* @return string
*/
function wpp_parse_tags_in_popular_posts( $html, $post_id ){
// Replace custom content tag {acf_video} with an actual video
if ( false !== strpos($html, '{acf_video}') ) {
// Get the video from ACF
$acf_video = get_field( 'featured_video', $post_id );
// This post has a video assigned via ACF,
// so let's display it
if ( $acf_video ) {
// Replace {acf_video} with the video returned by ACF
$html = str_replace( '{acf_video}', $acf_video, $html );
} // No video found
else {
// Replace {acf_video} with an empty string
$html = str_replace( '{acf_video}', '', $html );
}
}
return $html;
}
add_filter( "wpp_parse_custom_content_tags", "wpp_parse_tags_in_popular_posts", 10, 2 );
This is what the above function does:
- The function gets the HTML string passed to
post_html
and the ID of the post being rendered by WPP,
- Next, it checks if there’s a Content Tag called
{acf_video}
present and, if so, also checks if there’s a video assigned to the post via AFC’s get_field() function.
- If AFC’s get_field() returns a value, then we assume we have a video and so we’ll replace the
{acf_video}
tag with the value returned by ACF.
- If AFC’s get_field() returns false, we remove the
{acf_video}
tag (or you can display something else instead if you prefer).
- Finally, we return the parsed HTML string back to WPP.
Now, all you need to do is add {acf_video}
to the post_html
parameter and WPP will replace it with the actual video:
<?php
$args = array(
'wpp_start' => '<div class="main-carousel">',
'wpp_end' => '</div>',
'post_html' => '<div class="carousel-cell"><div class="image">{thumb}</div><div class="data"><span class="cats">{category}</span><span class="date">{date} </span></div><h4><a href="{url}">{text_title}</a></h4>{acf_video}</div>',
'thumbnail_width' => '298',
'thumbnail_height' => '203',
'stats_date' => '1',
'stats_category' => '1',
'limit' => '8'
);
wpp_get_mostpopular( $args );
?>
If you have any questions don’t hesitate to ask, alright?