3 Loại Short Code thường sử dụng trong WordPress

Hi anh em, bài này tổng hợp các cách tạo Shortcode nhanh chóng dễ sử dụng cho anh em nhé

1. Shortcode cơ bản

Đơn giản nhất là loại này tạo 1 shortcode sc_nguyenson thực thi function create_shortcode_nguyenson còn anh em thích nhét gì vào function thì nhét

function create_shortcode_nguyenson() {
//Nội dung
}
add_shortcode('sc_nguyenson', 'create_shortcode_nguyenson');

2. Shortcode có return

Sao phải return vì không return thì kết quả shortcode nó trả về đầu trang luôn, return để nó trả về đúng vị trí đặt shortcode thôi anh em nhé.

//SHORTCODE RETURN
function create_shortcode_toolsql() {
    ob_start();
    ?>
//Nhét vào đây
    <?php
    $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('ns_toolsql', 'create_shortcode_toolsql');

3. Shortcode có tham số

Đây là một shortcode có chứa tham số anh em nhé, mình viết để tùy chỉnh hàm gọi theo danh mục bài viết sẽ tùy biến hơn.

// TẠO SHORTCODE HIEN THI BAI VIET
function create_shortcode_randompost($ts) {
$nguyenson_query = new WP_Query(array(
	'posts_per_page' => 10,
	'cat' => $ts['idcat'],
	'orderby' => 'DESC'
));
$i=0;
ob_start();
if ( $nguyenson_query->have_posts() ) :
	"<ol>";
	while ( $nguyenson_query->have_posts() ) :
		$nguyenson_query->the_post();
		<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></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('nguyenson_post', 'create_shortcode_randompost');

Cách gọi shortcode thì cũng rất đơn giản thôi

[nguyenson_post idcat="2"]

Trên đây là mấy cái cơ bản anh em nắm được cũng đỡ vất vả phần nào khi sử lý code trong wordpress nhé.