Những đoạn code hay dùng trong lập trình theme WordPress (Phần 22: Code tạo 1 sortcode đơn giản trong wordpress)

Những đoạn code hay dùng trong lập trình theme WordPress (Phần 22: Code tạo 1 sortcode đơn giản trong wordpress)

08/02/2023 - 94

22. Code tạo 1 sortcode đơn giản trong wordpress

function create_shortcode_randompost() {

        $random_query = new WP_Query(array(
                'posts_per_page' => 10,
                'orderby' => 'rand'
        ));

        ob_start();
        if ( $random_query->have_posts() ) :
                "<ol>";
                while ( $random_query->have_posts() ) :
                        $random_query->the_post();?>

                                <li><a href="<?php the_permalink(); ?>"><h5><?php the_title(); ?></h5></a></li>

                <?php endwhile;
                "</ol>";
        endif;
        $list_post = ob_get_contents(); //Lấy toàn bộ nội dung phía trên bỏ vào biến $list_post để return

        ob_end_clean();

        return $list_post;
}
add_shortcode('random_post', 'create_shortcode_randompost');

Đây là sortcode list ra 10 vài viết ngẫu nhiên. Cách dùng là:

<?php 
    echo do_shortcode('[random_post]');
?>

 

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

Bài viết liên quan
Contact Me on Zalo