Skip to content

Instantly share code, notes, and snippets.

@yeungon
Last active June 28, 2017 04:20
Show Gist options
  • Save yeungon/bba3f79f7de7531f57e5b9ea3245bf5a to your computer and use it in GitHub Desktop.
Save yeungon/bba3f79f7de7531f57e5b9ea3245bf5a to your computer and use it in GitHub Desktop.
frequently used code for designing Wordpress theme
Đây là những đoạn code bạn sẽ dùng thường xuyên trong quá trình lập trình theme wordpress. Bạn chỉ cần hiểu tác dụng của nó như thế nào sau đó copy và dán nó để chạy thôi. Mình đã viết sẵn cho bạn rồi, không cần phài suy nghĩ chi nhiều nhé he he.
1.Code lấy bài viết mặt định.
PHP:
<!-- 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.
PHP:
<!-- 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
PHP:
<!-- 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
PHP:
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é
5.Code get menu
PHP:
<?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 sidebar
PHP:
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é!
7.Code get sidebar
PHP:
<?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
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 } ?>
Code này thường chèn dưới đoạn code số 1 (Code get post mặt định)
9.Code crop ảnh úp lên media
PHP:
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.
10.Code lấy ảnh thumbnail
PHP:
<!-- 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.
11.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:
<?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
12.Code tính lượt view cho bài viết
PHP:
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:
<?php
setpostview(get_the_id());
?>
Hiển thị lượt view:
<?php
echo getpostviews(get_the_id());
?>
13.Code lấy nội dung bài viết rút gọn.
PHP:
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!
14.Code lấy tất cả hình ảnh trong nội dung bài viết.
PHP:
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é!
15.Code lấy custom filed
PHP:
<?php
get_post_meta( $post_id, $key, $single );
?>
16.Code like box facebook
PHP:
<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>
17.Code share bài viết liên mạng xã hội
PHP:
<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>
18.Code query bài viết theo custom filed
Query 1 custom filed.
PHP:
<?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(). ?>
Query nhiều filed
PHP:
<?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(). ?>
19.Code lấy bài viết ngẫu nhiên.
PHP:
<?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.
20.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>
Đoạn code trên lấy 10 comment mới nhất có hình avatar
21.Code comment bằng facebook cho wordpress
PHP:
<div class="cmt">
<div class="fb-comments" data-width="100%" data-href="<?php the_permalink(); ?>" data-numposts="3"></div>
</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&appId=750688268378229";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
22. Code tạo 1 sortcode đơn giản trong wordpress
PHP:
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à:
PHP:
<?php
echo do_shortcode('[random_post]');
?>
23. Code tự động lưu ảnh về host khi copy bài từ nguồn khác.
PHP:
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();
Cài này chèn vào file functions.php nha!
24. Code lấy ảnh đầu tiên trong bài viết làm ảnh đại diện
PHP:
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ào vào khu vực muốn hiển thị hình đại diện.
PHP:
<img src="<?php echo catch_that_image() ?>" />
25. Một số form tìm kiếm đơn giản.
Tìm kiếm theo từ khóa.
PHP:
<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.
PHP:
<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.
PHP:
<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>
Nguồn: https://huykira.net/webmaster/wordpress/code-hay-lap-trinh-theme-wordpress.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment