WordPress как на ладони

Атрибут nofollow к ссылкам в виджет «последние комментарии».

Здравствуйте, перелопатил море инфы по функциям comment_link, get_comment_link и т.д. Не могу найти рабочий хук, чтобы добавить атрибут nofollow к ссылкам виджета последних комментариев. Тоесть там идёт вывод к примеру: admin к записи "название". И вот это "название" имеет ссылку без nofollow.

0
Jinflark
5.2 года назад
  • 1
    campusboy4754 www.youtube.com/c/wpplus

    Хуков там нет под это дело. Вижу лишь один вариант - создание своего виджета. Но чтобы не писать всё самому, просто отнаследуем класс оригинального виджета последних комментариев и лишь доработаем метод widget() (добавим нужный атрибут к ссылке), который отвечает за вывод самих комментариев.Код ниже вставляете в functions.php или оформляете в виде плагина.

    Так как ничего по сути не было изменено, то это сработает так, что наш класс автоматом "заменит" оригинальный. Вам даже не придётся ничего в админке убирать/добавлять. Как будто ничего и не произошло, ну кроме что добавится новый атрибут rel="nofollow".

    1 вариант

    Наследуем оригинальный виджет и полностью повторяем код метода widget(). В месте формирования ссылки на запись добавляет атрибут rel="nofollow".

    add_action( 'widgets_init', 'register_my_widget_recent_comments' );
    
    function register_my_widget_recent_comments() {
    	class My_Widget_Recent_Comments extends WP_Widget_Recent_Comments {
    		/**
    		 * Outputs the content for the current Recent Comments widget instance.
    		 *
    		 * @since 2.8.0
    		 *
    		 * @param array $args     Display arguments including 'before_title', 'after_title',
    		 *                        'before_widget', and 'after_widget'.
    		 * @param array $instance Settings for the current Recent Comments widget instance.
    		 */
    		public function widget( $args, $instance ) {
    			if ( ! isset( $args['widget_id'] ) ) {
    				$args['widget_id'] = $this->id;
    			}
    
    			$output = '';
    
    			$title = ( ! empty( $instance['title'] ) ) ? $instance['title'] : __( 'Recent Comments' );
    
    			/** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
    			$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
    
    			$number = ( ! empty( $instance['number'] ) ) ? absint( $instance['number'] ) : 5;
    			if ( ! $number ) {
    				$number = 5;
    			}
    
    			/**
    			 * Filters the arguments for the Recent Comments widget.
    			 *
    			 * @since 3.4.0
    			 * @since 4.9.0 Added the `$instance` parameter.
    			 *
    			 * @see   WP_Comment_Query::query() for information on accepted arguments.
    			 *
    			 * @param array $comment_args An array of arguments used to retrieve the recent comments.
    			 * @param array $instance     Array of settings for the current widget.
    			 */
    			$comments = get_comments( apply_filters( 'widget_comments_args', [
    				'number'      => $number,
    				'status'      => 'approve',
    				'post_status' => 'publish',
    			], $instance ) );
    
    			$output .= $args['before_widget'];
    			if ( $title ) {
    				$output .= $args['before_title'] . $title . $args['after_title'];
    			}
    
    			$output .= '<ul id="recentcomments">';
    			if ( is_array( $comments ) && $comments ) {
    				// Prime cache for associated posts. (Prime post term cache if we need it for permalinks.)
    				$post_ids = array_unique( wp_list_pluck( $comments, 'comment_post_ID' ) );
    				_prime_post_caches( $post_ids, strpos( get_option( 'permalink_structure' ), '%category%' ), false );
    
    				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 ) ) . '" rel="nofollow">' . get_the_title( $comment->comment_post_ID ) . '</a>'
    					);
    					$output .= '</li>';
    				}
    			}
    			$output .= '</ul>';
    			$output .= $args['after_widget'];
    
    			echo $output;
    		}
    	}
    
    	register_widget( 'My_Widget_Recent_Comments' );
    }

    2 вариант

    Наследуем оригинальный виджет и перегружаем метод widget(). Вызываем родительский метод widget() и прогоняем сгенерированный им html-код через регулярное выражение, которое находит ссылки и добавляет к ним атрибут rel="nofollow".

    add_action( 'widgets_init', 'register_my_widget_recent_comments' );
    
    function register_my_widget_recent_comments() {
    	class My_Widget_Recent_Comments extends WP_Widget_Recent_Comments {
    		public function widget( $args, $instance ) {
    			ob_start();
    
    			parent::widget( $args, $instance );
    
    			$html = ob_get_clean();
    			$html = preg_replace( '/(<a\b[^><]*)>/i', '$1 rel="nofollow">', $html );
    
    			echo $html;
    		}
    	}
    
    	register_widget( 'My_Widget_Recent_Comments' );
    }
    Комментировать
На вопросы могут отвечать только зарегистрированные пользователи. Вход . Регистрация