I created my Custom Widget with a category filter select. The widget show me the related posts of the current taxonomy term and filter by the selected category.
I would like to hide the widget title if the widget is empty (if there's no related posts).
How can I do?
Here's my code:
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
$limit = $instance['limit'];
$cat = $instance['cat'];
$show_thumbnail = isset( $instance['show_thumbnail'] ) ? $instance['show_thumbnail'] : false;
echo $args[ 'before_widget' ];
if ( !empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];
$cat_select = array(
'numberposts' => $limit,
'cat' => $cat,
); ?>
/******* function to get the posts of current taxonomy term *******/
<?php if ( function_exists( 'get_related_posts_widget' ) ) { ?>
<?php $related_posts = get_related_posts_widget( 'authors', $cat_select );
if ( $related_posts ) { ?>
<ul class="related-cat">
<!-- Widget loop -->
Thank you in advance
EDIT
I use the code you suggested me here
And I call the function get_related_posts_widget from functions.php. I adapted the query with the selected cat ($cat).
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
$limit = $instance['limit'];
$cat = $instance['cat'];
$show_thumbnail = isset( $instance['show_thumbnail'] ) ? $instance['show_thumbnail'] : false;
echo $args[ 'before_widget' ];
$cat_select = array(
'numberposts' => $limit,
'cat' => $cat,
);
if ( function_exists( 'get_related_posts_widget' ) ) { ?>
<?php $related_posts = get_related_posts( 'authors', $cat_select );
if ( $related_posts ) {
if ( !empty( $title ) )
echo $args['before_title'] . $title . $args['after_title']; ?>
<ul class="related-cat">
<?php foreach ( $related_posts as $post ) {
setup_postdata( $post ); ?>
<li>
<?php if ( $show_thumbnail ) : ?>
<figure class="post-thumbnail">
<?php the_post_thumbnail('tie-large'); ?>
</figure>
<?php endif; ?>
<h3><a href="<?php echo get_the_permalink($post->ID); ?>"> <?php echo get_the_title($post->ID);?> </a></h3>
</li>
<?php } //foreach ( $related_posts as $post ) ?>
</ul>
<?php } // end if ?>
<?php echo $args[ 'after_widget' ]; ?>
<?php } // end if function ?>
<?php } // end Widget Function
It's like the $after_widget doesn't work.
SOLVE
Thanks to @PieterGoosen! Read his code below. Wonderful!