Как отобразить произвольный тип записи в WordPress: методы и примеры кода

Чтобы отобразить пользовательский тип записи в WordPress, вы можете использовать несколько методов в зависимости от ваших потребностей и предпочтений. Вот некоторые из наиболее распространенных методов вместе с примерами кода:

Метод 1: использование хука pre_get_posts

function custom_post_type_display($query) {
    if ( !is_admin() && $query->is_main_query() ) {
        if ( is_post_type_archive( 'your_custom_post_type' ) ) {
            $query->set( 'posts_per_page', 10 ); // Set the number of posts to display
            $query->set( 'orderby', 'date' ); // Set the order of posts
            $query->set( 'order', 'DESC' ); // Set the sorting order
        }
    }
}
add_action( 'pre_get_posts', 'custom_post_type_display' );

Метод 2: использование пользовательского WP_Query

$args = array(
    'post_type'      => 'your_custom_post_type',
    'posts_per_page' => 10,
    'orderby'        => 'date',
    'order'          => 'DESC'
);
$custom_query = new WP_Query( $args );
if ( $custom_query->have_posts() ) {
    while ( $custom_query->have_posts() ) {
        $custom_query->the_post();
        // Display your custom post type content here
    }
    wp_reset_postdata();
} else {
    // No posts found
}

Метод 3. Использование короткого кода

function custom_post_type_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'posts_per_page' => 10,
        'orderby'        => 'date',
        'order'          => 'DESC',
    ), $atts );
    $args = array(
        'post_type'      => 'your_custom_post_type',
        'posts_per_page' => $atts['posts_per_page'],
        'orderby'        => $atts['orderby'],
        'order'          => $atts['order']
    );
    $custom_query = new WP_Query( $args );
    if ( $custom_query->have_posts() ) {
        while ( $custom_query->have_posts() ) {
            $custom_query->the_post();
            // Display your custom post type content here
        }
        wp_reset_postdata();
    } else {
        // No posts found
    }
}
add_shortcode( 'custom_post_type', 'custom_post_type_shortcode' );

Метод 4. Использование файла пользовательского шаблона.
Создайте новый файл с именем archive-your_custom_post_type.phpв папке вашей темы. Внутри этого файла вы можете настроить отображение произвольного типа публикации по своему усмотрению.