Support » Fixing WordPress » Limit Characters in Widgets.php output – Comment Author

  • Hi, I have found the code for the recent comments widget in the widgets.php file.

    What I would like to be able to do is change this code so that it will truncate the number of characters output for “comment author’s” name. I have a lot of comments and lately, they are doing silly things like using names like “mindy in a bedazzled hot pink leather jacket in new jersey” as their comment author name and it is WACK.

    So, here is the code I need help with.

    function wp_widget_recent_comments($args) {
    	global $wpdb, $comments, $comment;
    	extract($args, EXTR_SKIP);
    	$options = get_option('widget_recent_comments');
    	$title = empty($options['title']) ? __('Recent Comments') : $options['title'];
    	if ( !$number = (int) $options['number'] )
    		$number = 5;
    	else if ( $number < 1 )
    		$number = 1;
    	else if ( $number > 15 )
    		$number = 15;
    	if ( !$comments = wp_cache_get( 'recent_comments', 'widget' ) ) {
    		$comments = $wpdb->get_results("SELECT comment_author, comment_author_url, comment_ID, comment_post_ID FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT $number");
    		wp_cache_add( 'recent_comments', $comments, 'widget' );
    		<?php echo $before_widget; ?>
    			<?php echo $before_title . $title . $after_title; ?>
    			<ul id="recentcomments"><?php
    			if ( $comments ) : foreach ($comments as $comment) :
    			echo  '<li class="recentcomments">' . sprintf(__('%1$s on %2$s'), get_comment_author_link(), '<a href="'. get_permalink($comment->comment_post_ID) . '#comment-' . $comment->comment_ID . '">' . get_the_title($comment->comment_post_ID) . '</a>') . '</li>';
    			endforeach; endif;?></ul>
    		<?php echo $after_widget; ?>

    I will buy you a nice beverage if you help. 🙂

Viewing 1 replies (of 1 total)
  • You probably have your situation figured out but I am posting this
    for anyone else that might look at this post.

    If wordpress already has a function like this and anyone has found
    it, please let me know.

    I modified a version of code taken from
    “This will also round the text to the nearest whole word instead
    of cutting off part way through a word.”

    I added the strip_tags function because when I used shorten_text(),
    it would cut the string half way through a html tag which leaves
    an open html tag when the page is rendered. (left the <p> tags in)

    This is a simplified version of what I have so hopefully it works.

    function shorten_text($text, $chars) {
    	$text = strip_tags($text, '<p>');	
    	$text = trim($text);
    			echo $text;
    			$text = $text." ";
    			$text = substr($text,0,$chars);
    			$text = $text."...";
    			echo $text;
Viewing 1 replies (of 1 total)
  • The topic ‘Limit Characters in Widgets.php output – Comment Author’ is closed to new replies.