Question

I hope you can help.

I have two pieces of code that I do not know how to pair. I want my widget to only appear on posts and furthermore only if one specific category is picked. Whenever I try to put the condition in front of the public function it informs of a php error on the line of the condtion.

Here is my conditional code:

if (is_single() && in_category('pladeanmeldelser'))

Here is my display widget code:

public function widget( $args, $instance ) {
  $title = apply_filters( 'widget_title', $instance[ 'title' ] );
  $selskab = get_field( "selskab" );
  $related = get_field( "related" );
  $udgivet = get_field( "udgivet" );
  echo $args['before_widget'];
    if ( $title ) {
    echo $args['before_title'] . $title . $args['after_title']; } ?>

    <?php   global $post;
    if ( has_post_thumbnail( $post->ID ) )
    echo get_the_post_thumbnail( $post->ID, 'medium' ); 
    ?>

<div class="textwidget">
    <?php if(isset($selskab)) { echo "<p><strong>Pladeselskab:</strong> $selskab </p>"; } ?>
    <?php if(isset($related)) { echo "<p><strong>Musikalske slægtninge:</strong> $related </p>"; } ?>
    <?php if(isset($udgivet)) { echo "<p><strong>Udgivelsesår:</strong> $udgivet </p>"; } ?>
</div>

  <?php echo $args['after_widget'];
}
}
Was it helpful?

Solution

You should put the conditional at the start of the widget() function:

public function widget( $args, $instance ) {
    // Not single post or not in the pladeanmeldelser category.
    if ( ! is_single() || ! in_category('pladeanmeldelser') ) {
        return;
    }

    $title = apply_filters( 'widget_title', $instance[ 'title' ] );
    // ... other code.

}

And that should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top