WordPress thì chắc các bạn đã quá biết là nó phổ biến như thế nào rồi, nên mình cũng sẽ không nói nhiều về nó nữa. Tuy nhiên khi bạn muốn tự tạo cho mình một giao diện đẹp và theo ý của mình thì bạn sẽ phải nhớ một số đoạn code mà bạn hay dùng. Trong bài viết này mình sẽ chia sẻ với bạn tổng hợp những đoạn code hay dùng trong lập trình theme Worpdress mà mình hay dùng.

code hay dung trong lap trinh theme wordpress

Tổng hợp những đoạn code hay dùng trong lập trình theme Worpdress

CODE GET TỔNG HỢP

<?php get_header(); ?>
<?php get_footer(); ?>
<?php get_template_part('bai-viet-moi'); ?> 
<?php bloginfo('template_directory'); ?>
<?php the_permalink(); ?> // Get đường dẫn
<?php the_title(); ?> // Get tiêu đề
<?php echo get_the_date(); ?> // Get ngày đăng bài
<?php echo get_the_post_thumbnail( get_the_id(), 'full', array( 'class' =>'thumnail') ); ?> // Get ảnh đại diện
<?php the_archive_title() ?> // Get tiêu đề trang archive
<?php single_cat_title() ?> // Get tiêu đề trang chuyên mục

CODE GET TITLE WEBSITE

Chèn vào Functions

function svl_wp_title( $title, $sep ) {
 global $paged, $page;
 if ( is_feed() )
  return $title;
$title .= get_bloginfo( 'name', 'display' );
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) )
  $title = "$title $sep $site_description";
if ( ( $paged >= 2 || $page >= 2 ) && ! is_404() )
  $title = "$title $sep " . sprintf( __( 'Trang %s', 'devvn' ), max( $paged, $page ) );
return $title;
}
add_filter( 'wp_title', 'svl_wp_title', 10, 2 );

Chèn vào header

<title><?php wp_title( '|', 'true', 'right' ); ?></title>

CODE GET THUMBNAIL

add_theme_support( 'post-thumbnails' );

CODE ẨN PHẦN TỬ

<?php if(is_home() && !is_paged()) { ?>
Nội dung
<?php } ?>

<?php if ( is_single() ) { ?>
Nội dung
<?php } ?>

GET BÀI VIẾT MỚI NHẤT

<?php 
	$args = array(
		'post_status' => 'publish', // Chỉ lấy những bài viết được publish
		'post_type' => 'post', // Lấy những bài viết thuộc post, nếu lấy những bài trong 'trang' thì để là page 
		'showposts' => 12, // số lượng bài viết
		'cat' => 1, // lấy bài viết trong chuyên mục có id là 1 ( Xóa này đi là bài viết mới nhất)
	);
?>
<?php $getposts = new WP_query($args); ?>
<?php global $wp_query; $wp_query->in_the_loop = true; ?>
<?php while ($getposts->have_posts()) : $getposts->the_post(); ?>
	<?php //các thành phần cần lấy  ?>
<?php endwhile; wp_reset_postdata(); ?>

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(); ?>
	Nội dung hiển thị
<?php endwhile; wp_reset_postdata(); ?>
<!-- Get post News Query -->

GET BÀI VIẾT MỚI NHẤT THEO CHUYÊN MỤC VÀ BỎ QUA BÀI VIẾT ĐẦU TIÊN

<?php 
	$args = array(
		'post_status' => 'publish', // Chỉ lấy những bài viết được publish
		'post_type' => 'post', // Lấy những bài viết thuộc post, nếu lấy những bài trong 'trang' thì để là page 
		'showposts' => 12, // số lượng bài viết
		'cat' => 1, // lấy bài viết trong chuyên mục có id là 1 ( Xóa này đi là bài viết mới nhất)
                'offset' => 1, //Bỏ qua bài viết đầu tiên
	);
?>
<?php $getposts = new WP_query($args); ?>
<?php global $wp_query; $wp_query->in_the_loop = true; ?>
<?php while ($getposts->have_posts()) : $getposts->the_post(); ?>
	<?php //các thành phần cần lấy  ?>
<?php endwhile; wp_reset_postdata(); ?>

GET BÀI VIẾT MẶC ĐỊNH TRÊN TRANG CHỦ

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

Nội dung cần lấy
<?php endwhile; ?>
<?php endif; ?>

PHÂN TRANG

Chèn vào Functions

function wp_corenavi_table($custom_query = null) {
  global $wp_query;
  if($custom_query) $main_query = $custom_query;
  else $main_query = $wp_query;
  $big = 999999999;
  $total = isset($main_query->max_num_pages)?$main_query->max_num_pages:'';
  if($total > 1) echo '<div class="paginate_links">';
  echo paginate_links( array(
   'base'        => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
   'format'   => '?paged=%#%',
   'current'  => max( 1, get_query_var('paged') ),
   'total'    => $total,
   'mid_size' => '10',
   'prev_text'    => __('Trước','devvn'),
   'next_text'    => __('Tiếp','devvn'),
) );
  if($total > 1) echo '</div>';
}

Chèn vào nơi hiển thị

<?php wp_corenavi_table();?>

CSS

.paginate_links{overflow:hidden;text-align:center;display:table;margin:20px auto}
.paginate_links .page-numbers{width:32px;height:32px;display:inline-block;float:left;margin:0 5px;padding-top:5px;color:#2473fd;border:1px solid #2473fd;margin-bottom:5px}
.paginate_links .page-numbers:hover{background:#2473fd;color:#fff}
.paginate_links .page-numbers.prev,.paginate_links .page-numbers.next{background:transparent;width:auto;border:none}
.paginate_links .page-numbers.prev:hover,.paginate_links .page-numbers.next:hover{text-decoration:underline;color:#2473fd}
.paginate_links .page-numbers.current{background:#2473fd;color:#fff}

TÍNH LƯỢT XEM BÀI VIẾT

Chèn vào Functions

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;
}

Chèn vào Single

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

Chèn hiển thị lượt xem

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

TAG

<div class="tag-single">
   <p><?php the_tags('Từ khóa: '); ?></p>
</div>

CODE LẤY BÀI VIẾT XEM NHIỀU

Chèn vào Functions

function setPostViews($postID) {
    $countKey = 'post_views_count';
    $count = get_post_meta($postID, $countKey, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $countKey);
        add_post_meta($postID, $countKey, '0');
    }else{
        $count++;
        update_post_meta($postID, $countKey, $count);
    }
}

Chèn vào Single

<?php setPostViews(get_the_ID()); ?>

Chèn vào nơi cần hiển thị

<?php
query_posts('meta_key=post_views_count&showposts=8&orderby=meta_value_num&order=DESC');
if (have_posts()) : while (have_posts()) : the_post();
?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
endwhile; endif;
wp_reset_query();
?>

BÀI VIẾT LIÊN QUAN

<?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 LẤY NỘI DUNG 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.'...';
}

Thêm vào nơi muốn hiển thị

<?php echo teaser(30); ?>

FORM TÌM KIẾM

Form tìm kiếm

<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>

Form tìm kiếm theo danh mục

<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>

GET BREADCRUMB

function the_breadcrumb() {
  echo '<ul id="crumbs">';
  if (!is_home()) {
    echo '<a href="';
    echo get_option('home');
    echo '">';
    echo 'Home';
    echo "</a> / ";
    if (is_category() || is_single()) {
      the_category(' / ');
    }
  }
  elseif (is_tag()) {single_tag_title();}
  elseif (is_day()) {echo"<li>Archive for "; the_time('F jS, Y'); echo'</li>';}
  elseif (is_month()) {echo"<li>Archive for "; the_time('F, Y'); echo'</li>';}
  elseif (is_year()) {echo"<li>Archive for "; the_time('Y'); echo'</li>';}
  elseif (is_author()) {echo"<li>Author Archive"; echo'</li>';}
  elseif (isset($_GET['paged']) && !empty($_GET['paged'])) {echo "<li>Blog Archives"; echo'</li>';}
  elseif (is_search()) {echo"<li>Search Results"; echo'</li>';}
  echo '</ul>';
}

Chèn vào Single

<?php the_breadcrumb(); ?>

Chèn vào Functions

add_theme_support( 'custom-logo' );
function themename_custom_logo_setup() {
	$defaults = array(
		'height'               => 100,
		'width'                => 400,
		'flex-height'          => true,
		'flex-width'           => true,
		'header-text'          => array( 'site-title', 'site-description' ),
		'unlink-homepage-logo' => true, 
	);
	add_theme_support( 'custom-logo', $defaults );
}
add_action( 'after_setup_theme', 'themename_custom_logo_setup' );

Chèn vào header

$custom_logo_id = get_theme_mod( 'custom_logo' );
$logo = wp_get_attachment_image_src( $custom_logo_id , 'full' );
if ( has_custom_logo() ) {
	echo '<img src="' . esc_url( $logo[0] ) . '" alt="' . get_bloginfo( 'name' ) . '">';
} else {
	echo '<h1>' . get_bloginfo('name') . '</h1>';
}

Kết luận

Trên đây là tổng hợp những đoạn code hay dùng trong lập trình theme Worpdress mà bạn có thể tham khảo. Nó còn rất nhiều nữa nhưng các bạn tự tìm hiểu thêm nhé. Chúc bạn thành công.

Xem Thêm Bài Viết
Nhạc DJ Nhạc Trend TikTok Truyện Ma

5/5 - (5 bình chọn)