Как отобразить виджет последних записей в WordPress

Короткий обзор свежего контента повышает показатели популярности сайта. В этой статье я расскажу, как создать плагин для отображения списка недавних записей.

Зарегистрируйте плагин

После регистрации плагин будет отображаться в списке плагинов, установленных в WordPress.

/*
Plugin Name: Recent Posts widget extended
Description: This plugin creates a widget for displaying recent posts on the front end.
Version: 1.X
Author: WordPress Recent Posts Widget
 
*/
class RecentPostsWithExcerpts extends WP_Widget {
function __construct() {
$widget_ops = array('classname' => 'recent_with_excerpt', 'description' => __( 'Your most recent posts, with optional excerpts', 'recent_posts_with_excerpts') );
parent::__construct('RecentPostsWithExcerpts', __('Recent Posts with Excerpts', 'recent_posts_with_excerpts'), $widget_ops);
}

В приведенном выше коде функция RecentPostsWithExprects() регистрирует плагин. Так он отображается в списке установленных плагинов в панели администрирования.

Как отобразить виджет последних записей в WordPress

Код виджета

Приведенный выше код создает виджет для вывода списка последних публикаций на сайте. Затем он извлекает последние опубликованные записи и отображает отрывки записей в цикле. После этого функция wp_reset_query() восстанавливает значение $wp_query и данные запроса записи.

function widget( $args, $instance ) {
    	global $before_widget,$instance;
    	extract( $args );
    	$title = apply_filters('widget_title', $instance['title']);
    	echo $before_widget,$title;
    	$ul_classes = 'recent_posts_with_excerpts';
    	$ul_classes = apply_filters('recent_posts_with_excerpts_list_classes', $ul_classes);
    	if ( !empty( $ul_classes ) )
        	$ul_classes = ' class="'.$ul_classes.'"';
    	$li_classes = '';
    	$li_classes = apply_filters('recent_posts_with_excerpts_item_classes', $li_classes);
    	if ( !empty( $li_classes ) )
        	$li_classes = ' class="'.$li_classes.'"';
    	$h2_classes = 'recent_posts_with_excerpts';
    	$h2_classes = apply_filters('recent_posts_with_excerpts_heading_classes', $h2_classes);
    	if ( !empty( $h2_classes ) )
        	$h2_classes = ' class="'.$h2_classes.'"';
        do_action('recent_posts_with_excerpts_begin');
    	echo '<ul'.$ul_classes.'>';
    	// извлекаем последние n записей в блоге
    	$q = array('posts_per_page' => $instance['numposts']);
    	if (!empty($instance['tag']))
        	$q['tag'] = $instance['tag'];
    	$q = apply_filters('recent_posts_with_excerpts_query', $q, $instance);
    	$rpwe = new wp_query($q);
    	// Цикл
    	if ($rpwe->have_posts()) :
        	while ($rpwe->have_posts()) : $rpwe->the_post();
            	echo '<li'.$li_classes.'>';
            	echo '<h2'.$h2_classes.'><a href="'.get_permalink().'">'.get_the_title().'</a></h2>';
            	if (!empty($date))
                    echo '<h3 class="date">'.get_the_time($date).'</h3>';
            	{ // выводим отрывок записи
                    ?>
                <blockquote> <?php
  	              // отрывок записи
                	if (function_exists('the_excerpt_reloaded'))
                        the_excerpt_reloaded($instance['words'], $instance['tags'], 'content', FALSE, '', '', '1', '');
                    else
                        the_excerpt(); 
               	if (!empty($instance['more_text'])) { ?><p class="alignright"><small><a href="<?php the_permalink(); ?>"><?php echo $instance['more_text']; } ?></a></small></p>
                </blockquote> <?php
                }?></li>
        	<?php endwhile; endif; ?>
	</ul>
	<?php
    	do_action('recent_posts_with_excerpts_end');
        wp_reset_query();
    }

Форма для размещения виджета

Следующий фрагмент кода создает простую форму виджета с пользовательскими настройками.

function form( $instance ) {
	if (get_option('show_on_front') == 'page')
    	$link = get_permalink(get_option('page_for_posts'));
	else
    	$link = home_url();
	//По умолчанию
	$instance = wp_parse_args( (array) $instance, array(
    	'title' => __('Recent Posts', 'recent_posts_with_excerpts'),
    	'numposts' => 5,
    	'numexcerpts' => 5,
    	'date' => get_option('date_format'),
    	'more_text' => __('Read More', 'recent_posts_with_excerpts'),
    	'words' => '25',
    	'tag' => '',
	));
	?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:', 'recent_posts_with_excerpts'); ?></label>
	<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $instance['title']; ?>" /></p>
<p><label for="<?php echo $this->get_field_id('numposts'); ?>"><?php _e('Number of posts to show:', 'recent_posts_with_excerpts'); ?></label>
	<input class="widefat" id="<?php echo $this->get_field_id('numposts'); ?>" name="<?php echo $this->get_field_name('numposts'); ?>" type="text" value="<?php echo $instance['numposts']; ?>" /></p>
<p>
	<label for="<?php echo $this->get_field_id('more_text'); ?>"><?php _e('"More" link text:', 'recent_posts_with_excerpts'); ?></label>
	<input class="widefat" id="<?php echo $this->get_field_id('more_text'); ?>" name="<?php echo $this->get_field_name('more_text'); ?>" type="text" value="<?php echo $instance['more_text']; ?>" />
	<br </p>
<?php
	if (function_exists('the_excerpt_reloaded')) { ?>
	<p>
    	<label for="<?php echo $this->get_field_id('words'); ?>"><?php _e('Limit excerpt to how many words?', 'recent_posts_with_excerpts'); ?></label>
    	<input class="widefat" id="<?php echo $this->get_field_id('words'); ?>" name="<?php echo $this->get_field_name('words'); ?>" type="text" value="<?php echo $instance['words']; ?>" />
	</p>
	<p>
    	<label for="<?php echo $this->get_field_id('tags'); ?>"><?php _e('Allowed HTML tags:', 'recent_posts_with_excerpts'); ?></label>
    	<input class="widefat" id="<?php echo $this->get_field_id('tags'); ?>" name="<?php echo $this->get_field_name('tags'); ?>" type="text" value="<?php echo htmlspecialchars($instance['tags'], ENT_QUOTES); ?>" />
    	<br /><small><?php
 printf( __('E.g.: %s', 'recent_posts_with_excerpts'));
    	?>
    </small></p>
	<?php } ?>
<?php
}

Вот как будет выглядеть форма виджета:

Как отобразить виджет последних записей в WordPress

Как настроить и использовать плагин

Создайте папку recent-post-widget-extended и разместите в ней файл latest-post-widget-extended.php. Активируйте плагин и включите виджет в панели администрирования WordPress.

Как отобразить виджет последних записей в WordPress

Чтобы настроить и запустить плагин, создайте папку ecent-post-widget-extended в директории плагинов WordPress. В этой папке создайте файл latest-post-widget-extended.php и вставьте в него исходный код плагина. После этого вы  сможете вставить виджет в любое место на сайте.

Как отобразить виджет последних записей в WordPress

После развертывания виджет будет выглядеть следующим образом.

Как отобразить виджет последних записей в WordPress

Полный код плагина

<?php
/*
Plugin Name: Recent Posts widget extended
Description: Insert description with the help of content writer.
Version: 1.X
Author: WordPress Recent Posts Widget
 
*/
class RecentPostsWithExcerpts extends WP_Widget {
function __construct() {
$widget_ops = array('classname' => 'recent_with_excerpt', 'description' => __( 'Your most recent posts, with optional excerpts', 'recent_posts_with_excerpts') );
parent::__construct('RecentPostsWithExcerpts', __('Recent Posts with Excerpts', 'recent_posts_with_excerpts'), $widget_ops);
}
function widget( $args, $instance ) {
global $before_widget,$intance;
extract( $args );
$title = apply_filters('widget_title', $instance['title']);
echo $before_widget,$title;
$ul_classes = 'recent_posts_with_excerpts';
$ul_classes = apply_filters('recent_posts_with_excerpts_list_classes', $ul_classes);
if ( !empty( $ul_classes ) )
$ul_classes = ' class="'.$ul_classes.'"';
$li_classes = '';
$li_classes = apply_filters('recent_posts_with_excerpts_item_classes', $li_classes);
if ( !empty( $li_classes ) )
$li_classes = ' class="'.$li_classes.'"';
$h2_classes = 'recent_posts_with_excerpts';
$h2_classes = apply_filters('recent_posts_with_excerpts_heading_classes', $h2_classes);
if ( !empty( $h2_classes ) )
$h2_classes = ' class="'.$h2_classes.'"';
do_action('recent_posts_with_excerpts_begin');
echo '<ul'.$ul_classes.'>';
// извлекаем последние n записей в блоге
$q = array('posts_per_page' => $instance['numposts']);
if (!empty($instance['tag']))
$q['tag'] = $instance['tag'];
$q = apply_filters('recent_posts_with_excerpts_query', $q, $intance);
$rpwe = new wp_query($q);
// Цикл
if ($rpwe->have_posts()) :
while ($rpwe->have_posts()) : $rpwe->the_post();
echo '<li'.$li_classes.'>';
echo '<h2'.$h2_classes.'><a href="'.get_permalink().'">'.get_the_title().'</a></h2>';
if (!empty($date))
echo '<h3 class="date">'.get_the_time($date).'</h3>';
{ // выводим отрывок записи
?>
<blockquote> <?php
 
if (function_exists('the_excerpt_reloaded'))
the_excerpt_reloaded($instance['words'], $instance['tags'], 'content', FALSE, '', '', '1', '');
else
the_excerpt();
if (!empty($instance['more_text'])) { ?><p class="alignright"><small><a href="<?php the_permalink(); ?>"><?php echo $instance['more_text']; } ?></a></small></p>
</blockquote> <?php
}?></li>
<?php endwhile; endif; ?>
</ul>
<?php
do_action('recent_posts_with_excerpts_end');
 
wp_reset_query();
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = sanitize_text_field($new_instance['title']);
$instance['numposts'] = intval($new_instance['numposts']);
$instance['more_text'] = sanitize_text_field($new_instance['more_text']);
$instance['date'] = sanitize_text_field($new_instance['date']);
$instance['words'] = intval($new_instance['words']);
$instance['tags'] = $new_instance['tags'];
$instance['tag'] = sanitize_text_field($new_instance['tag']);
return $instance;
}
function form( $instance ) {
if (get_option('show_on_front') == 'page')
$link = get_permalink(get_option('page_for_posts'));
else
$link = home_url();
//По умолчанию
$instance = wp_parse_args( (array) $instance, array(
'title' => __('Recent Posts', 'recent_posts_with_excerpts'),
'numposts' => 5,
'numexcerpts' => 5,
'date' => get_option('date_format'),
'more_text' => __('Read More', 'recent_posts_with_excerpts'),
'words' => '25',
'tag' => '',
));
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:', 'recent_posts_with_excerpts'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $instance['title']; ?>" /></p>
<p><label for="<?php echo $this->get_field_id('numposts'); ?>"><?php _e('Number of posts to show:', 'recent_posts_with_excerpts'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('numposts'); ?>" name="<?php echo $this->get_field_name('numposts'); ?>" type="text" value="<?php echo $instance['numposts']; ?>" /></p>
<p>
<label for="<?php echo $this->get_field_id('more_text'); ?>"><?php _e('"More" link text:', 'recent_posts_with_excerpts'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('more_text'); ?>" name="<?php echo $this->get_field_name('more_text'); ?>" type="text" value="<?php echo $instance['more_text']; ?>" />
<br />
</p>
<?php
if (function_exists('the_excerpt_reloaded')) { ?>
<p>
<label for="<?php echo $this->get_field_id('words'); ?>"><?php _e('Limit excerpt to how many words?', 'recent_posts_with_excerpts'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('words'); ?>" name="<?php echo $this->get_field_name('words'); ?>" type="text" value="<?php echo $instance['words']; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('tags'); ?>"><?php _e('Allowed HTML tags:', 'recent_posts_with_excerpts'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('tags'); ?>" name="<?php echo $this->get_field_name('tags'); ?>" type="text" value="<?php echo htmlspecialchars($instance['tags'], ENT_QUOTES); ?>" />
<br /><small><?php
printf( __('E.g.: %s', 'recent_posts_with_excerpts'));
?>
</small></p>
<?php } ?>
<?php
}
}
function recent_posts_with_excerpts_init() {
register_widget('RecentPostsWithExcerpts');
}
add_action('widgets_init', 'recent_posts_with_excerpts_init');

Заключение

Этот плагин позволяет отобразить список недавно опубликованного контента на сайте. Все, что вам нужно сделать, это заполнить простую форму.

Источник

Просмотров:

Добавить комментарий