Skip to content

Instantly share code, notes, and snippets.

@pvphong90
Created November 3, 2017 06:53
Show Gist options
  • Save pvphong90/3e1034ca0caffa280e48061af5b587c7 to your computer and use it in GitHub Desktop.
Save pvphong90/3e1034ca0caffa280e48061af5b587c7 to your computer and use it in GitHub Desktop.
Các đoạn code hay dùng trong wordpress
Code lấy bài viết mặc đị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 đó!.
2. 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
3. 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.
4. 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 tạo ra các vị trí đặt menu . Bỏ vào file function.php để thực thi.
5. 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
6. Code tạo side bar
if (function_exists('register_sidebar')){
register_sidebar(array(
'name'=> 'Cột bên',
'id' => 'sidebar',
));
}
Code này tạo ra 1 sider bar . Đặt code này trong function.php
7. Code lấy hiển thị sider bar
<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebar') ) : ?><?php endif; ?>
Code này thường đặtở file sider bar nhưng cũng có thể đặt ở bất cứ đâu nếu muốn sider bar này hiển thị.
8. 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 } ?>
Đặt ở nơi muốn xuất hiện phân trang, thường là ở file danh sách post (archive.php).
9. Code crop ảnh
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 sẽ chèn trong file function.php, ảnh up lên sẽ tự động crop thành 4 kích thước như trên
10. Code lấy ảnh thumbnail
<!-- Get thumbnail -->
<?php echo get_the_post_thumbnail( $post_id, 'full', array( 'class' =>'thumnail') ); ?>
<!-- Get thumbnail -->
Thường đặt trong vòng lặp get post
11. Code related post 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>
Code này thường được đặt trong file single.php
12. Lấy bà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>';
}
}
?>
Code này cũng đặt trong file single.php
13. 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;
}
Đặt trong file function.php
Sau đó đặt code này vào single.php để đếm cho từng bài:
<?php
setpostview(get_the_id());
?>
Và hiển thỉ lượt view bằng code sau :
<?php
echo getpostviews(get_the_id());
?>
14. Code lấy bài viết rút gọn (Excerpt)
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!
15. 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 function.php, muốn dùng code này thì gọi function này ra và sử dụng vòng lặp foreach để lấy nội dung trong đó.
16. Code lấy custom filed
<?php
get_post_meta( $post_id, $key, $single );
?>
17. Code chèn box like facebook
<div class="fb-page" data-href="https://facebook.com/huykiradotnet" data-hide-cover="false" data-show-facepile="true" data-show-posts="false"></div>
<div id="fb-root"></div>
<script>
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/vi_VN/sdk.js#xfbml=1&version=v2.7;
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
Chèn ở đâu bạn muốn nó xuất hiện
18. Code share bài viết lên mạng xã hội
<div id="fb-root"></div>
<script>
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/vi_VN/sdk.js#xfbml=1&version=v2.7";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<span class="like">
<div class="fb-like" data-href="<?php the_permalink(); ?>" data-layout="button_count" data-action="like" data-size="small" data-show-faces="true" data-share="true"></div>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<g:plusone size="medium"></g:plusone>
</span>
<span class="social-s">
<a target="_blank" href="https://www.facebook.com/sharer.php?u=<?php the_permalink(); ?>"><i class="fa fa-facebook" aria-hidden="true"></i></a>
<a target="_blank" href="https://plus.google.com/share?url=<?php the_permalink(); ?>"><i class="fa fa-google-plus" aria-hidden="true"></i></a>
<a target="_blank" href="https://twitter.com/share?url=<?php the_permalink(); ?>"><i class="fa fa-twitter" aria-hidden="true"></i></a>
</span>
Chèn ở đâu mình muốn hiển thị
19. Code lấy bài viết theo custom filed
Theo 1 filed
<?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(). ?>
Theo nhiều filed
<?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(). ?>
20. Code lấy bài viết ngẫu nhiên
<?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(); ?>
21. Code lấy 10 comment mới nhất
<?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>
22. Code tạo 1 shortcode đơn giả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');
Đây là shortcode list ra 10 bài ngẫu nhiên
Cách dùng :
<?php
echo do_shortcode('[random_post]');
?>
23. Code tự động lưu ảnh từ website về host khi copy từ website khác
Code này hưu ích khi đi copy bài viết, chèn vào funtion.php sẽ chạy.
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();
24. Code lấy ảnh đầu tiên trong bài viết làm ảnh đại diện
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;
}
Chèn code này vào funtion.php sau đó dùn code sau để hiển thị ảnh:
<img src="<?php echo catch_that_image() ?>" />
25. Code các form tìm kiếm
Tìm theo từ khóa:
<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 theo post type với từ khóa
<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 từ khóa kết hợp với category
<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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment