TODO: To change the header's content go to Dr.Explain menu Options : Project Settings : HTML (CHM) Export : Setup HTML Template and Layout
×
Menu
Index

Tạo shortcode

* Tạo shortcode trong wordpress chúng ta sử dụng hàm add_shortcode. Ví dụ dưới đây mình tạo shortcode có tên 'testfilter'.
function simple_shortcode($atts) {
 
     $pairs=array('name' => 'Mr.Hoang','age' => '24');
 
     extract(shortcode_atts($pairs,$atts,'testfilter'));
 
     echo $name.'-'.$age;
}
add_shortcode( 'testfilter', 'simple_shortcode' );
 
Chú ý: tên shortcode không được viết hoa.
bạn khai báo thuộc tính mặc định cho shortcode trong trường hợp người dùng không thay đổi giá trị này. Sử dụng hàm shortcode_atts để kết hợp các thuộc tính của shortcode đang gọi.
 
Gọi shortcode: ví dụ
[testfilter name="Q.Huy" age="25"]
 
* Nội dung của shortcode:
Là chuỗi nội dung dài truyền vào shortcode không thông qua thuộc tính. Nội dung này bạn thiết lập chứa trong cặp  mở và đóng shortcode. VD:
[shortcode1]Nội dung shortcode ở đây[/shortcode1]
 
Lấy nội dung của shortcode ở tham số thứ 2 của hàm sử lý nội dung shortcode.
function create_shortcode_thamso($args, $content) {
        return "Đây là số ". $args['thamso1'];
}
add_shortcode( 'shortcode_thamso', 'create_shortcode_thamso' );
Giải thích:
 
 
Kiến thức:
 
Một ví dụ khác, shortcode hiển thị 10 bài viết ngẫu nhiên:
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');
 
 
 
Made with help of Dr.Explain

Unregistered version