Những đoạn code hay dùng trong lập trình theme WordPress

Những đoạn code hay dùng trong lập trình theme WordPress

Đây là những đoạn mã bạn có thể sử dụng thường xuyên khi phát triển theme WordPress. Sau khi hiểu được tác dụng của từng đoạn mã, bạn có thể dễ dàng sao chép và dán chúng vào để sử dụng mà không cần phải suy nghĩ quá nhiều. Mình đã viết sẵn cho bạn rồi đấy, chỉ cần sử dụng thôi!

Code lấy bài viết mặt định.

<!-- Get post mặt định -->
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

<?php endwhile; else : ?>
<p>Không có</p>
<?php endif; ?>
<!-- Get post mặt định -->

Đoạn code đặt trong index sẽ lấy list bài viết mới nhất, Đặt trong category sẽ lấy danh sách bài viết của category đó, đặt trong single sẽ lấy nội dung của bài đó!.

Code lấy 10 bài viết mới nhất theo category.

<!-- Get post News Query -->
<?php $getposts = new WP_query(); $getposts->query('post_status=publish&showposts=10&post_type=post&cat=1'); ?>
<?php global $wp_query; $wp_query->in_the_loop = true; ?>
<?php while ($getposts->have_posts()) : $getposts->the_post(); ?>

<?php endwhile; wp_reset_postdata(); ?>
<!-- Get post News Query -->
  • showposts=10 sẽ lấy 10 bài viết mới nhất
  • cat=1  chỉ lấy các bài viết có cat_id bằng 1

Code lấy danh sách chuyên mục

<!-- Get category -->
<?php $args = array(
'hide_empty' => 0,
'taxonomy' => 'category',
'orderby' => id,
);
$cates = get_categories( $args );
foreach ( $cates as $cate ) { ?>
<li>
<a href="<?php echo get_term_link($cate->slug, 'category'); ?>"><?php echo $cate->name ?></a>
</li>
<?php } ?>
<!-- Get category -->

Đây là đoạn code lấy danh sách các chuyên mục, ‘taxonomy’ => ‘category’ có nghĩa là lấy theo category.

Code tạo menu

add_action( 'init', 'register_my_menus' );
function register_my_menus(){
register_nav_menus(
array(
'main_nav' => 'Menu chính',
'link_nav' => 'Liên kết',
'info_nav' => 'Thông tin',
)
);
}

Code này sẽ tạo 3 vị trí đặt menu như trên, Bỏ đoạn code nào vào file functions.php nhé

Code get menu

<?php wp_nav_menu(
array(
'theme_location' => 'main_nav',
'container' => 'false',
'menu_id' => 'header-menu',
'menu_class' => 'menu-main'
)
); ?>

Đây là code get menu, chú ý ‘theme_location’ => ‘main_nav’,  đây là điểu kiệu chúng ta sẽ lấy menu nào, code này thường được chèn vào file header.php

Code tạo sidebar

if (function_exists('register_sidebar')){
register_sidebar(array(
'name'=> 'Cột bên',
'id' => 'sidebar',
));
}

Đây là code tạo ra 1 sidebar. Đặt code này vào file functions.php nhé!

Code get sidebar

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebar') ) : ?><?php endif; ?>

Đây là code lấy sidebar ra ngoài, code này thường được đặt trong file sidebar.php

Code phân trang.

<?php if(paginate_links()!='') {?>
<div class="quatrang">
<?php
global $wp_query;
$big = 999999999;
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'prev_text' => __('«'),
'next_text' => __('»'),
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages
) );
?>
</div>
<?php } ?>

Code này thường chèn dưới đoạn code số 1 (Code get post mặt định)

Code crop ảnh úp lên media

add_action( 'after_setup_theme', 'wpdocs_theme_setup' );
function wpdocs_theme_setup() {
add_image_size( 'slider-thumb', 750, 375, true);
add_image_size( 'post-thumb', 300, 200, true);
add_image_size( 'tour-thumb', 270, 200, true);
add_image_size( 'video-thumb', 215, 130, true);
}

Khi chèn đoạn code này vào file functions.php, hình ảnh upload lên media sẽ được từ động crop thành 4 kích thước như trên.

Code lấy ảnh thumbnail

<!-- Get thumbnail -->
<?php echo get_the_post_thumbnail( $post_id, 'full', array( 'class' =>'thumnail') ); ?>
<!-- Get thumbnail -->

Code này thường được đặt trong vòng lặp get post.

Code bài viết liên quan

Hiển thị bài viết liên quan theo tag

<!-- Hiển thị bài viết theo Tag -->
<div id="relatedposttags">
<?php
$tags = wp_get_post_tags($post->ID);
if ($tags)
{
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
// lấy danh sách các tag liên quan
$args=array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID), // Loại trừ bài viết hiện tại
'showposts'=>5, // Số bài viết bạn muốn hiển thị.
'caller_get_posts'=>1
);
$my_query = new wp_query($args);
if( $my_query->have_posts() )
{
echo '<h3>Bài viết liên quan</h3><ul>';
while ($my_query->have_posts())
{
$my_query->the_post();
?>
<li><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
<?php
}
echo '</ul>';
}
}
?>
</div>

Hiển thị vài viết liên quan theo category

<?php
$categories = get_the_category($post->ID);
if ($categories)
{
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;

$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'showposts'=>5, // Số bài viết bạn muốn hiển thị.
'caller_get_posts'=>1
);
$my_query = new wp_query($args);
if( $my_query->have_posts() )
{
echo '<h3>Bài viết liên quan</h3><ul class="list-news">';
while ($my_query->have_posts())
{
$my_query->the_post();
?>
<li>
<div class="new-img"><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(array(85, 75)); ?></a></div>
<div class="item-list">
<h4><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h4>
<?php the_excerpt(); ?>
</div>
</li>
<?php
}
echo '</ul>';
}
}
?>

2 đoạn code này thường được đặt dưới nội dung bài viết, tức phần dưới của file single.php

Code tính lượt view cho bài viết

function setpostview($postID){
$count_key ='views';
$count = get_post_meta($postID, $count_key, true);
if($count == ''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
} else {
$count++;
update_post_meta($postID, $count_key, $count);
}
}
function getpostviews($postID){
$count_key ='views';
$count = get_post_meta($postID, $count_key, true);
if($count == ''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0";
}
return $count;
}

Đây là code tính lượt view cho bài viết. Code này được đặt trong file functions.php

Sử dụng: 

Chèn code này vào trong file single.php 

<?php
setpostview(get_the_id());
?>

Hiển thị lượt view:

<?php
echo getpostviews(get_the_id());
?>

Code lấy nội dung bài viết rút gọn.

function teaser($limit) {
$excerpt = explode(' ', get_the_excerpt(), $limit);
if (count($excerpt)>=$limit) {
array_pop($excerpt);
$excerpt = implode(" ",$excerpt).'[...]';
} else {
$excerpt = implode(" ",$excerpt);
}
$excerpt = preg_replace('`\[[^\]]*\]`','',$excerpt);
return $excerpt.'...';
}

Đây là code lấy nội dung bài viết được chỉ định số từ nhất định. Cách dùng <?php echo teaser(30); ?>, Với được code trên mình sẽ lấy 30 từ đầu tiên trong bài viết!

Code lấy tất cả hình ảnh trong nội dung bài viết.

function get_link_img_post(){
global $post;
preg_match_all('/src="(.*)"/Us',get_the_content(),$matches);
$link_img_post = $matches[1];
return $link_img_post;
}

Chèn code này trong file functions.php, để hiển thị chúng ta dùng forech nó ra nhé!

Code lấy custom filed

<?php 
get_post_meta( $post_id, $key, $single );
?>

Code like box facebook

0 0 đánh giá
Article Rating
Theo dõi
Thông báo của
guest
0 Comments
Cũ nhất
Mới nhất Được bỏ phiếu nhiều nhất
Phản hồi nội tuyến
Xem tất cả bình luận
0
Rất thích suy nghĩ của bạn, hãy bình luận.x