Reputation: 59
I've created the following shortcode to display blockquotes :
// Add Shortcode
function quote_shortcode( $atts , $content = null ) {
// Attributes
$atts = shortcode_atts(
array(
'author' => 'author',
'author_job' => 'author_job',
),
$atts
);
return
'<div data-module="expert_quote"><blockquote class="full no-picture"><p>“' . $content . '”</p><footer class="quote-footer"><cite><span class="name">' . esc_attr($atts['author']) . '</span> <span class="title">' . esc_attr($atts['author_job']) . '</span></cite></footer></blockquote></div>';
}
add_shortcode( 'quote', 'quote_shortcode' );
I'd like to not return
<span class="name">' . esc_attr($atts['author']) . '</span>
if author
is not set in the shortcode. Same goes with author_job
.
How can I achieve this?
Upvotes: 1
Views: 362
Reputation: 1036
You need to create your return string conditionally. You can use following code:
function quote_shortcode( $atts , $content = null ) {
// Attributes
$atts = shortcode_atts(
array(
'author' => 'author',
'author_job' => 'author_job',
),
$atts
);
$return_string = '<div data-module="expert_quote">';
$return_string .= '<blockquote class="full no-picture">';
$return_string .= '<p>“' . $content . '”</p>';
$return_string .= '<footer class="quote-footer">';
$return_string .= '<cite>';
if (isset($atts['author'])) {
$return_string .= '<span class="name">' . esc_attr($atts['author']) . '</span>';
}
if (isset($atts['author_job'])) {
$return_string .= '<span class="title">' . esc_attr($atts['author_job']) . '</span>';
}
$return_string .= '</cite>';
$return_string .= '</footer">';
$return_string .= '</blockquote">';
$return_string .= '</div">';
return $return_string;
}
add_shortcode( 'quote', 'quote_shortcode' );
Upvotes: 3
Reputation: 59
I've managed to make it work but not sure my code is well optimized :
function quote_shortcode( $atts , $content = null ) {
// Attributes
$atts = shortcode_atts(
array(
'author' => '',
'author_job' => '',
),
$atts
);
$return_string = '<div data-module="expert_quote">';
$return_string .= '<blockquote class="full no-picture">';
$return_string .= '<p>“' . $content . '”</p>';
if (!empty($atts['author']) || !empty($atts['author_job'])) {
$return_string .= '<footer class="quote-footer">';
$return_string .= '<cite>';
}
if (!empty($atts['author'])) {
$return_string .= '<span class="name">' . esc_attr($atts['author']) . '</span>';
}
if (!empty($atts['author_job'])) {
$return_string .= '<span class="title">' . esc_attr($atts['author_job']) . '</span>';
}
if (!empty($atts['author']) && !empty($atts['author_job'])) {
$return_string .= '</cite>';
$return_string .= '</footer>';
}
$return_string .= '</blockquote>';
$return_string .= '</div>';
return $return_string;
}
add_shortcode( 'quote', 'quote_shortcode' );
Upvotes: 1