0

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'];
}
}
1

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.

| improve this answer | |
  • It works! Thank you so much. – Asbjørn Skødt May 25 '19 at 14:11
  • You're welcome. :) – Sally CJ May 25 '19 at 23:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.