Combine sprintf with IF condition

I am stuck with a silly problem. I was prompted to make some changes to the php site template. So, here is the code for the title / hyperlink:

<?php the_title( sprintf( '<h1 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h1>' ); ?>

      

And that should be combined with:

<?php if( in_category('local-msr') ) { echo 'target="_blank" '; } ?>

      

I've tried something like this:

<?php the_title( sprintf( '<h1 class="entry-title"><a href="%s" rel="bookmark" if( in_category('local-msr') ), echo 'target="_blank">', esc_url( get_permalink() ) ), '</a></h1>' ); ?>

      

But without success.

Any ideas on how to make this work? Thank!

+3


source to share


1 answer


I'll add a third parameter to sprintf

.

You can do it all in one line, but for clarity, I'll write out:



// set a variable that has the target or is empty if the condition is not met
$target = in_category('local-msr') ? 'target="_blank"' : '';
the_title( sprintf( '<h1 class="entry-title"><a href="%s" %s rel="bookmark">', esc_url( get_permalink() ), $target ), '</a></h1>' );
//                                                        ^^ add the variable here
//                                                                                                         ^^^^^^^ the value

      

+3


source







All Articles