Archived topic
Display related articles from that category on sidebar widget
2 replies · Started by Hilton on June 25, 2020
Hi, I would like to use a widget in the sidebar of the single posts with the most recent articles in the category to which it belongs. How can I do this, preferably in the simplest way that does not overload the database or that does not need to install any plugin. Thanks
Just complementing, I want to display in the article sidebar a list of 5 recent articles from that category to which it belongs. I'm using the code below in functions.php to show the 5 posts (from category 62 in this case). Is there a way to write this code so that it is optimised, and I don't have to rewrite everything for each new category? I have several categories. Thanks
/**
* function to add recent posts widget
*/
function wpcat_postsbycategory_musculacao() {
// the query
$the_query = new WP_Query( array( 'cat' => '62', 'posts_per_page' => 5 ) );
// The Loop
if ( $the_query->have_posts() ) {
$string .= '<ul class="postsbytag widget_recent_entries">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
if ( has_post_thumbnail() ) {
$string .= '<li>';
$string .= '<a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_post_thumbnail($post_id, array( 80, 80) ) . get_the_title() .'</a></li>';
} else {
// if no featured image is found
$string .= '<li><a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_title() .'</a></li>';
}
}
} else {
// no posts found
}
$string .= '</ul>';
return $string;
/* Restore original Post Data */
wp_reset_postdata();
}
// Add a shortcode
add_shortcode('categoryposts-musculacao', 'wpcat_postsbycategory_musculacao');
/**
* function to change search widget placeholder
*/
function db_search_form_placeholder( $html ) {
$html = str_replace( 'placeholder="Pesquisar ', 'placeholder="Buscar ', $html );
return $html;
}
add_filter( 'get_search_form', 'db_search_form_placeholder' );
Hi there,
I'm not sure where that code comes from but a plugin like this would probably be your best bet if you aren't comfortable with custom coding:
https://en-ca.wordpress.org/plugins/contextual-related-posts/