The source of the text in question lives in wp-includes/widgets/class-wp-widget-recent-comments.php
I found it by searching the WP files for the id of the widget, recentcomments
, which I gathered by inspecting the HTML of the widget. So, here's where that on is coming from, with a bit of extra code for context:
foreach ( (array) $comments as $comment ) {
$output .= '<li class="recentcomments">';
/* translators: comments widget: 1: comment author, 2: post link */
$output .= sprintf( _x( '%1$s on %2$s', 'widgets' ),
'<span class="comment-author-link">' . get_comment_author_link( $comment ) . '</span>',
'<a href="' . esc_url( get_comment_link( $comment ) ) . '">' . get_the_title( $comment->comment_post_ID ) . '</a>'
);
$output .= '</li>';
}
Here we can see that $output .= sprintf( _x( '%1$s on %2$s', 'widgets' ),
is the string we need to change. We can use the gettext_with_context
filter to take out the author and the word on in one pass.
/**
* @param string $translated
* @param string $text
* @param string $context
* @param string $domain
* @return string
*/
function wpse238430_recent_comments_text( $translated, $text, $context, $domain ) {
// Use guard clauses to bail as soon as possible if we're not looking
// at the things we want. Bailing early is a good practice because
// translation filters are called frequently, so code in this function could be run many times, causing an impact on performance.
// Our string identified above used the 'widgets' context, so make sure that's what we're looking at.
if ( $context !== 'widgets' ) {
return $translated;
}
// WordPress uses the 'default' text domain, even though one is not explicitly specified. Bail if the text domain is not 'default';
if ( 'default' !== $domain ) {
return $translated;
}
// $text contains the string to be evaluated for translation.
switch ( $text ) {
case '%1$s on %2$s' : // If $text == '%1$s on %2$s', do something..
//$translated = '%1$s on %2$s'; // original string. %1$s is the comment author and %2$s is the post they commented on
$translated = '%2$s'; // Remove the author and 'on'
break;
}
// Return our modified string. Now the original `sprintf()` function will simply output the link to the post that the author commented on.
return $translated;
}
add_filter( 'gettext_with_context', 'wpse238430_recent_comments_text', 20, 4 );