0

Настроить вывод php кода из созданной страницы я научился. Смотрю документацию, не могу понять, как вывести последние записи из определенной рубрики? Если изменять page.php или index.php, то вывести получается. А если задача стоит, создать новую страницу то как я понял, нужно добавить какой-нибудь цикл вордпресс. Кто разбирается, помогите? Вот код вывода рубрики, который я нашел, но он не работает а созданной странице из админ-панели.

<?php 
$args = array(
	'numberposts' => 3,
	'category' => 5,
	'post_status' => 'publish',
); 

$result = wp_get_recent_posts($args);

foreach( $result as $p ){ 
?>
	— <a href="<?php echo get_permalink($p['ID']) ?>"><?php echo $p['post_title'] ?></a><br />    
<?php 
} 
?>

1
  • Как вы соединяете приведённый код со страницей? 9 сен 2017 в 15:13

1 ответ 1

2

Проще всего организовать вывод своим шорткодом. В админке на страницу добавьте текст такого вида:

[recent_posts category="my_cat" number="5"]

А в functions.php такой примерно код:

/**
 * Shortcode to output recent posts.
 *
 * @param array $atts Shortcode attributes.
 *
 * @return mixed
 */
function recent_posts_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'category'            => '',
        'number'              => -1,
        'order'               => 'DESC',
        'orderby'             => 'date',
        'tag'                 => '',
        'exclude_posts'       => '',
        'ignore_sticky_posts' => true,
    ), $atts );

    $args = array(
        'category_name'       => $atts['category'],
        'showposts'           => $atts['number'],
        'order'               => strtoupper( $atts['order'] ),
        'orderby'             => $atts['orderby'],
        'tag'                 => explode( ',', $atts['tag'] ),
        'post__not_in'        => explode( ',', $atts['exclude_posts'] ),
        'ignore_sticky_posts' => $atts['ignore_sticky_posts'],
    );

    $query = new WP_Query( $args );

    if ( $query->have_posts() ) {
        $return_string = '<ul>';
        while ( $query->have_posts() ) {
            $query->the_post();
            $return_string .= '<li>';
            $return_string .= '<div class="ft-post-title"><a href="' . get_permalink() . '">' . get_the_title() . '</a></div>';
            $return_string .= '<div class="ft-post-date">' . get_the_date( 'j F Y' ) . '</div>';
            $return_string .= '<div class="ft-post-excerpt">' . get_the_excerpt() . '</div>';
            $return_string .= '<div class="ft-post-more"><a href="' . get_permalink() . '">Читать полностью</a></div>';
            $return_string .= '<div class="ft-post-big-date">' . get_the_date( 'j' ) . '</div>';
            $return_string .= '</li>';
        }
        $return_string .= '</ul>';
    } else {
        $return_string = 'Нет записей';
    }

    wp_reset_postdata();

    return $return_string;
}

add_shortcode( 'recent_posts', 'recent_posts_shortcode' );

Эта реализация принимает параметры, описанные в массиве $atts с указанными значениями по умолчанию.

Созданный шорткод можно использовать на любой странице, записи, виджете WordPress - практически где угодно.

Код рабочий, скопирован с одного из моих сайтов.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.