как создать короткий код для отображения определенного отзыва, используя его идентификатор сообщения?

Я создал пользовательский тип сообщения для отзывов в wordpress. Я добавил 89 отзывов и хочу отобразить 2, которые я хочу отобразить на домашней странице. поэтому хотел создать шорткод, который будет отображать отзывы в соответствии с их идентификатором сообщения. Может ли кто-нибудь сказать мне код для шорткода.

Ниже я показываю код, который я написал для создания пользовательского типа сообщения для отзыва. Пожалуйста, скажите мне код для создания такого шорткода: - [testimonial posts_per_page="5" testimonial_id="123,145"]

function custom_post_testimonial_type() {

// Set UI labels for Custom Post Type
$labels = array(
    'name'=> _x( 'Testimonials', 'Post Type General Name', 'walker_theme' ),
 'singular_name'=> _x( 'Testimonial', 'Post Type Singular Name', 'walker_theme' ),
   'menu_name'=> __( 'Testimonials', 'walker_theme' ),
'parent_item_colon' => __( 'Testimonial', 'walker_theme' ),
'all_items'  => __( 'All Testimonials', 'walker_theme' ),
'view_item' => __( 'View Testimonial', 'walker_theme' ),
'add_new_item' => __( 'Add New Testimonial','walker_theme' ),
'add_new'  => __( 'Add New', 'walker_theme' ),
'edit_item'  => __( 'Edit Testimonial','walker_theme' ),
'update_item' => __( 'Update Testimonial','walker_theme' ),
'search_items' => __( 'Search Testimonial', 'walker_theme' ),
'not_found'           => __( 'Not Found', 'walker_theme' ),
'not_found_in_trash'  => __( 'Not found in Trash','walker_theme' ),
);

  // Set other options for Custom Post Type

$args = array(
'label'               => __( 'testimonials', 'walker_theme' ),
'description'         => __( 'Home page testimonials', 'walker_theme' ),
'labels'              => $labels,
    // Features this CPT supports in Post Editor
'supports' => array( 'title', 'editor', 'author','thumbnail', 'tags'),
    // You can associate this CPT with a taxonomy or custom 
      taxonomy. 
    'taxonomies'          => array( 'genres', 'post_tag' ),
    /* A hierarchical CPT is like Pages and can have
    * Parent and child items. A non-hierarchical CPT
    * is like Posts.
    */  
    'hierarchical'        => false,
    'public'              => true,
    'show_ui'             => true,
    'show_in_menu'        => true,
    'show_in_nav_menus'   => true,
    'show_in_admin_bar'   => true,
    'menu_position'       => 5,
    'can_export'          => true,
    'has_archive'         => true,
    'exclude_from_search' => false,
    'publicly_queryable'  => true,
    'capability_type'     => 'page',
);

// Registering your Custom Post Type
register_post_type( 'testimonials', $args );

    }

    add_action( 'init', 'custom_post_testimonial_type', 0 );

person Poonam Katpara    schedule 30.05.2019    source источник
comment
пожалуйста ответьте как можно скорее....   -  person Poonam Katpara    schedule 30.05.2019


Ответы (2)


Используйте атрибуты шорткода с известными атрибутами и заполните значения по умолчанию, когда это необходимо.

 function testimonials($atts) {
    $a = shortcode_atts( array(
        'posts_per_page' => '',
        'testimonial_id'  =>  ''
    ), $atts );

    $testimonials = '';
    $post_in = esc_attr($a['testimonial_id']);
    $posts_per_page = esc_attr($a['posts_per_page']);

    $post_artay = explode(',', $post_in);
    $args = array(
        'post__in' => $post_artay,
        'posts_per_page' => $posts_per_page,
        'post_type'        => 'testimonials',
        'order_by' => 'post__in',
    );

    // the query
    $the_query = new WP_Query( $args );

    if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : $the_query->the_post();
        $testimonials.= '<div class="title">'.get_the_title().'</div>';
        $testimonials.= '<div class="content">'.get_the_content().'</div>';
        $testimonials.='<div class="date">'.get_the_date().'</div>';
        $testimonials.='<div class="author">'.get_the_author().'</div>';
    endwhile;
    endif;
    return $testimonials;
}
add_shortcode('testimonial', 'testimonials' );

используйте шорткод, например.

[testimonial posts_per_page="5" testimonial_id="29,23"]
person Shivendra Singh    schedule 30.05.2019
comment
Я забыл обновить «post_type» в коде после завершения тестирования. Теперь я редактирую свой код и обновляю 'post_type'. Теперь это должно работать. - person Shivendra Singh; 30.05.2019
comment
я хочу отображать дату и имя автора, не могли бы вы сказать мне, пожалуйста - person Poonam Katpara; 30.05.2019
comment
Я обновляю код на дату и автора, пожалуйста, посмотрите. - person Shivendra Singh; 30.05.2019
comment
Пожалуйста. Не могли бы вы проголосовать и отметить эти ответы как одобренные. Это будет более уместно. Спасибо. - person Shivendra Singh; 30.05.2019

Привет, давайте добавим этот код в файл functions.php темы.

add_shortcode( 'testimonial', 'testimonial_shortcode_callback' );

function testimonial_shortcode_callback( $atts ) {
ob_start();

extract( shortcode_atts( array(
    'posts_per_page' => 5,
    'testimonial_id' => '',
), $atts ) );

// define query parameters based on attributes
$options = array(
    'post_type'      => 'testimonials',
    'posts_per_page' => $posts_per_page,
);

if ( ! empty( $testimonial_id ) ) {
    $options['post__in'] = array_map( 'trim', explode( ',', $testimonial_id ) );
}

$testimonial_query = new WP_Query( $options );
// run the loop based on the query
if ( $testimonial_query->have_posts() ) :
    ?>
    <ul class="testimonial-listing">
        <?php
        while ( $testimonial_query->have_posts() ) : $testimonial_query->the_post();
            ?>
            <li id="testimonial-<?php the_ID(); ?>">
                <?php the_content(); ?>
            </li>
        <?php
        endwhile;
        wp_reset_postdata();
        ?>
    </ul>
    <?php
    $testimonial_output = ob_get_clean();

    return $testimonial_output;
endif;
}

Затем используйте этот шорткод в качестве примера [testimonial posts_per_page="2" testimonial_id="123,145"]

person devthebuilder    schedule 30.05.2019
comment
еще одна проблема @devthebuilder, я хочу показать дату и имя автора муравья? пожалуйста, помогите мне - person Poonam Katpara; 30.05.2019