Dưới dây là tổng hợp những đoạn code thường dùng trong WordPress, phục cho việc tùy chỉnh theme, tùy chỉnh hiển thị. Nó rất tiện lợi cho công việc lập trình WordPress của bạn. Bởi bạn chỉ việc copy và paste thôi. Các code này sẽ hoạt động ngay. Test it!
CODE LẤY BÀI POST
Code lấy bài viết mặc định
1 2 3 4 5 6 7 8 |
<!-- Get post mặc định --> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <?php endwhile; else : ?> <p>Không có</p> <?php endif; ?> <!-- Get post mặc định --> |
Code lấy 10 bài viết mới nhất theo category.
1 2 3 4 5 6 7 |
<!-- 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
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!-- 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 lấy custom filed
1 2 3 |
<?php get_post_meta( $post_id, $key, $single ); ?> |
Code query bài viết theo custom field
Với 1 custome field
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?php // args $args = array( 'numberposts' => -1, 'post_type' => 'event', 'meta_key' => 'location', 'meta_value' => 'Melbourne' ); // query $the_query = new WP_Query( $args ); ?> <?php if( $the_query->have_posts() ): ?> <ul> <?php while( $the_query->have_posts() ) : $the_query->the_post(); ?> <li> <a href="<?php the_permalink(); ?>"> <img src="<?php the_field('event_thumbnail'); ?>" /> <?php the_title(); ?> </a> </li> <?php endwhile; ?> </ul> <?php endif; ?> <?php wp_reset_query(); // Restore global post data stomped by the_post(). ?> |
Với nhiều field
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
<?php // args $args = array( 'numberposts' => -1, 'post_type' => 'event', 'meta_query' => array( 'relation' => 'AND', array( 'key' => 'location', 'value' => 'Melbourne', 'compare' => '=' ), array( 'key' => 'attendees', 'value' => 100, 'type' => 'NUMERIC', 'compare' => '>' ) ) ); // query $the_query = new WP_Query( $args ); ?> <?php if( $the_query->have_posts() ): ?> <ul> <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <li> <a href="<?php the_permalink(); ?>"> <img src="<?php the_field('event_thumbnail'); ?>" /> <?php the_title(); ?> </a> </li> <?php endwhile; ?> </ul> <?php endif; ?> <?php wp_reset_query(); // Restore global post data stomped by the_post(). ?> |
CODE DANH SÁCH BÀI VIẾT
Code lấy bài viết cùng chuyên mục
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<!-- Lấy Post cùng chuyên mục --> <div id="relatedpostcats" class="relatedpost"> <?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'=>8, // 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 cùng chuyên mục</h3><ul class="relatedpost_list">'; while ($my_query->have_posts()) { $my_query->the_post(); ?> <li> <div class="new-img"><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'medium' ); ?></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>'; } } ?> </div> |
Code bài viết liên quan
Hiển thị bài viết liên quan theo tag
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<!-- Hiển thị bài viết theo Tag --> <div id="relatedposttags" class="relatedpost"> <?php $tags = wp_get_post_tags($post->ID); if ($tags) { $tag_ids = array(); foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id; $args=array( 'tag__in' => $tag_ids, 'post__not_in' => array($post->ID), // Loại trừ bài viết hiện tại 'showposts'=>8, // 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="relatedpost_list">'; while ($my_query->have_posts()) { $my_query->the_post(); ?> <li> <div class="new-img"><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'medium' ); ?></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>'; } } ?> </div> |
Hiển thị vài viết liên quan theo category
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?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 lấy bài viết ngẫu nhiên
1 2 3 4 5 6 7 8 9 10 |
<?php $postquery = new WP_Query(array('posts_per_page' => 35, 'orderby' => 'rand')); if ($postquery->have_posts()) { while ($postquery->have_posts()) : $postquery->the_post(); $do_not_duplicate = $post->ID; ?> <li> <a href="<?php the_permalink();?>"><?php the_title();?></a> </li> <?php endwhile; } wp_reset_postdata(); ?> |
Đoạn code trên lấy 35 bài viết ngẫu nhiên.
Code lấy 8 bài viết xem nhiều
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<div class="widget"> <h3> Bài viết xem nhiều </h3> <div class="content-w"> <ul> <?php $getposts = new WP_query(); $getposts->query('post_status=publish&showposts=8&post_type=post&meta_key=views&orderby=meta_value_num'); ?> <?php global $wp_query; $wp_query->in_the_loop = true; ?> <?php while ($getposts->have_posts()) : $getposts->the_post(); ?> <li> <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4> </li> <?php endwhile; wp_reset_postdata(); ?> </ul> </div> </div> |
CODE HỮU DỤNG CHO POST
Code tính lượt view cho bài viết
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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
1 2 3 |
<?php setpostview(get_the_id()); ?> |
Hiển thị lượt view:
1 2 3 |
<?php echo getpostviews(get_the_id()); ?> |
Code lấy nội dung bài viết rút gọn
1 2 3 4 5 6 7 8 9 10 11 |
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 10 comment mới nhất
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php $cmt = get_comments(array( 'status' => 'approve', 'number'=> 10, )); ?> <div class="content-w content-news"> <ul> <?php foreach ($cmt as $value) { ?> <li> <a href="<?php the_permalink($value->comment_post_ID);?>#comment-<?php echo $value->comment_ID; ?>"><?php echo get_avatar($value->comment_author_email, 150 ); ?></a> <a href="<?php the_permalink($value->comment_post_ID); ?>#comment-<?php echo $value->comment_ID; ?>"><?php echo $value->comment_author; ?></a> - <span style="color: #cd8a35;font-size: 12px;"><?php echo $value->comment_date; ?></span> <p style="font-size: 13px;"><?php echo cuttitle($value->comment_content); ?></p> <div class="clear"></div> </li> <?php } ?> </ul> </div> |
Đoạn code trên lấy 10 comment mới nhất có hình avatar
Code phân trang
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?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 LIÊN QUAN ĐẾN HÌNH ẢNH TRONG POST
Code lấy tất cả hình ảnh trong nội dung bài viết
1 2 3 4 5 6 |
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 crop ảnh úp lên media
1 2 3 4 5 6 7 |
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); } |
Code này để bạn tùy chỉnh kích thước ảnh cho post, nó sẽ tự động crop ảnh khi bạn up ảnh lên. Đặt trong file function nhé.
Code tự động lưu ảnh về host khi copy bài từ nguồn khác.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
class Auto_Save_Images{ function __construct(){ add_filter( 'content_save_pre',array($this,'post_save_images') ); } function post_save_images( $content ){ if( ($_POST['save'] || $_POST['publish'] )){ set_time_limit(240); global $post; $post_id=$post->ID; $preg=preg_match_all('/<img.*?src="(.*?)"/',stripslashes($content),$matches); if($preg){ foreach($matches[1] as $image_url){ if(empty($image_url)) continue; $pos=strpos($image_url,$_SERVER['HTTP_HOST']); if($pos===false){ $res=$this->save_images($image_url,$post_id); $replace=$res['url']; $content=str_replace($image_url,$replace,$content); } } } } remove_filter( 'content_save_pre', array( $this, 'post_save_images' ) ); return $content; } function save_images($image_url,$post_id){ $file=file_get_contents($image_url); $post = get_post($post_id); $posttitle = $post->post_title; $postname = sanitize_title($posttitle); $im_name = "$postname-$post_id.jpg"; $res=wp_upload_bits($im_name,'',$file); $this->insert_attachment($res['file'],$post_id); return $res; } function insert_attachment($file,$id){ $dirs=wp_upload_dir(); $filetype=wp_check_filetype($file); $attachment=array( 'guid'=>$dirs['baseurl'].'/'._wp_relative_upload_path($file), 'post_mime_type'=>$filetype['type'], 'post_title'=>preg_replace('/\.[^.]+$/','',basename($file)), 'post_content'=>'', 'post_status'=>'inherit' ); $attach_id=wp_insert_attachment($attachment,$file,$id); $attach_data=wp_generate_attachment_metadata($attach_id,$file); wp_update_attachment_metadata($attach_id,$attach_data); return $attach_id; } } new Auto_Save_Images(); |
Code lấy ảnh đầu tiên trong bài viết làm ảnh đại diện
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function catch_that_image() { global $post, $posts; $first_img = ''; ob_start(); ob_end_clean(); $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); $first_img = $matches [1] [0]; if(empty($first_img)){ //Defines a default image $first_img = "/images/default.jpg"; //Duong dan anh mac dinh khi khong tim duoc anh dai dien } return $first_img; } |
Cách sử dùng: Chèn đoạn code này vào khu vực muốn hiển thị hình đại diện.
1 |
<img src="<?php echo catch_that_image() ?>" /> |
MỘT SỐ CODE HỮU DỤNG KHÁC TRONG WORDPRESS
Code tạo menu
1 2 3 4 5 6 7 8 9 10 |
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', ) ); } |
Bỏ đoạn code nào vào file functions.php nhé
Code get menu
1 2 3 4 5 6 7 8 |
<?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
1 2 3 4 5 6 |
if (function_exists('register_sidebar')){ register_sidebar(array( 'name'=> 'Cột bên', 'id' => 'sidebar', )); } |
Đặt code này vào file functions.php nhé!
Code get sidebar
1 |
<?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 tạo 1 sortcode đơn giản trong wordpress
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
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à:
1 2 3 |
<?php echo do_shortcode('[random_post]'); ?> |
Một số form tìm kiếm đơn giản
Tìm kiếm theo từ khóa.
1 2 3 4 5 6 |
<form action="<?php bloginfo('url'); ?>/" method="GET" role="form"> <div class="form-group"> <input type="text" name="s" class="form-control" id="" placeholder="Từ khóa"> </div> <button type="submit" class="btn btn-primary">Tìm kiếm</button> </form> |
Tìm kiếm theo 1 post_type nhất định với từ khóa.
1 2 3 4 5 6 7 |
<form action="<?php bloginfo('url'); ?>/" method="GET" role="form"> <input type="hidden" name="post_type" value="page"> <div class="form-group"> <input type="text" name="s" class="form-control" id="" placeholder="Từ khóa"> </div> <button type="submit" class="btn btn-primary">Tìm kiếm</button> </form> |
Tìm kiếm theo từ khóa kết hợp với category.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<form action="<?php bloginfo('url'); ?>/" method="GET" role="form"> <div class="form-group"> <input type="text" name="s" class="form-control" id="" placeholder="Từ khóa"> </div> <div class="form-group"> <select name="cat" id="input" class="form-control" required="required"> <option value="">Chọn chuyên mục</option> <?php $args = array( 'hide_empty' => 0, 'taxonomy' => 'category', 'orderby' => id, 'parent' => 0 ); $cates = get_categories( $args ); foreach ( $cates as $cate ) { ?> <option value="<?php echo $cate->term_id ?>"><?php echo $cate->name; ?></option> <?php } ?> </select> </div> <button type="submit" class="btn btn-primary">Tìm kiếm</button> </form> |
Kết
Okay! Trên đây là những code thường dùng hay có thể gọi là cực kỳ hữu dụng khi làm WordPress, đây thực sự là những code mà mình ước có thể biết khi mới bắt đầu đấy.
Nguồn tham khảo: Huykira
[…] trường tùy chọn trong Tùy Biến theme WordPress khá tương tự với phần tạo vùng tùy chọn widget cho theme WordPress. Tuy nhiên trường trong phần Tùy Biến có thể gọi là nâng nao hơn. Bởi nó hạn […]
Chào bác ạ. bác cho em hỏi là em muốn hiển thị Widget chỉ ở dưới header thì thay ” top_header” thành ” bottom_header” ạ. Muốn hiển thị ở trên trang chủ thôi thì viết đoạn code như này ” TRANG CHỦ ” đúng không ạ