Here’s an example how to prepend a span
tag to the post titles, where the span class is added in the custom field wpse_post_icon_class
.
We could try to restrict it to the Recent Posts widget with:
add_filter( 'widget_display_callback', function( $instance, $obj, $args )
{
// Only target Recent Posts widgets
if( 'recent-posts' === $obj->id_base )
{
// Add filter
add_filter( 'the_title', 'wpse_title_with_icon', 10, 2 );
// Widget output
$obj->widget( $args, $instance );
// Remove filter
remove_filter( 'the_title', 'wpse_title_with_icon', 10, 2 );
// Override the default widget output
return true;
}
return $instance;
}, 10, 3 );
where the filter callback is defined as:
function wpse_title_with_icon( $title, $post_id )
{
// check if the current post has the 'wpse_post_icon_class' custom field
if( $icon = get_post_meta( $post_id, 'wpse_post_icon_class', true ) )
$title = sprintf(
'<span class="%s"></span> %s',
esc_attr( trim( $icon ) ),
$title
);
return $title;
}
Example:
Here’s a Dashicon example where we add the wpse_post_icon_class
custom field with the value of dashicons dashicons-flag
:
Then the Recent Posts widget will display as:
where the corresponding title is prepended with:
<span class="dashicons dashicons-flag"></span>
Notes:
It might be better to store only the flag
string in a custom field, then we should consider a more specific name like wpse_post_dashicon_class
, instead of the generic wpse_post_icon_class
name.
We might also want to extend this and create a metabox where the user can click on the icon she wants to associate the post with.
We must enqueue the Dashicons on the front-end, or the font- or svg icons we choose to use.
Another alternatives would be to write a custom widget or shortcode for more flexibility.
Hope it helps.