Mẹo nhỏ: Để tìm kiếm chính xác các chia sẻ của f4vnn.com, hãy search trên Google với cú pháp: "Từ khóa" + "f4vnn". (Ví dụ: tắt update windows f4vnn). Tìm kiếm ngay

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

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

Có thể bạn quan tâm: thêm Menu Bootstrap 5 cho WordPress

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 THEO CHUYÊN MỤC DÙNG I++

<?php
$vnkings = new WP_Query(array(
'post_type'=>'post',
'post_status'=>'publish',
'cat' => id_của_category,
//thay id_của_category bằng id danh mục bạn muốn hiển thị nhé
'orderby' => 'ID',
'order' => 'DESC',
'posts_per_page'=> 5));
?>
<?php $i=1; while ($vnkings->have_posts()) : $vnkings->the_post(); ?>
<?php if($i==1){ ?>
<div class="bai_dau_tien">
    <a href="<?php the_permalink() ;?>" class="anh_bai_viet"> 
        <?php the_post_thumbnail("thumbnail",array( "title" => get_the_title(),"alt" => get_the_title() ));?>
    </a>
    <a href="<?php the_permalink() ;?>" class="tieu_de_bai_viet"><?php the_title() ;?></a>
    <p class="trich_dan">
        <?php the_excerpt() ;?>
    </p>
</div>
<?php } else { ?>
<div class="cac_bai_con_lai"><a href="<?php the_permalink() ;?>"><?php the_title() ;?></a> </div>
<?php } ?>
<?php $i++; endwhile ; wp_reset_query() ;?>

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

BÀI VIẾT MẶC ĐỊNH TRÊN TRANG CHHỦ THEO I++

            <?php
            $vnkings = new WP_Query(array(
                'post_type' => 'post',
                'post_status' => 'publish',
                'orderby' => 'ID',
                'order' => 'DESC',
            ));
            ?>
            <?php $i = 1; while ($vnkings->have_posts()) : $vnkings->the_post(); ?>
            <?php if($i == 1){ ?>
                <div class="col-lg-6 mb-4">
                    <div class="big-box">
                        <div class="card text-bg-dark">
                            <?php echo get_the_post_thumbnail( get_the_id(), 'full', array( 'class' =>'thumnail') ); ?>
                            <div class="card-img-overlay">
                              <a href="<?php the_permalink(); ?>"><h3 class="card-title lh-base text-light"><?php the_title(); ?></h3></a>
                              <p class="card-text"><small><?php echo get_the_date('d/m/y'); ?></small></p>
                          </div>
                      </div>
                  </div>
              </div>
              <div class="col-lg-6 small">
              <?php } else { ?>
                <div class="small-box mb-4">
                    <div class="thumbnail-small-box">
                        <a href="<?php the_permalink(); ?>"><?php echo get_the_post_thumbnail( get_the_id(), 'full', array( 'class' =>'thumnail') ); ?></a>
                    </div>
                    <div class="title-small-box">
                        <a href="<?php the_permalink(); ?>"><h3 class="lh-base h5"><?php the_title(); ?></h3></a>
                        <div class="info">
                            <i class="fa-regular fa-clock"></i> <?php echo get_the_date('d/m/y'); ?>
                        </div>
                    </div>
                </div>
            <?php } ?>
            <?php $i++; endwhile; wp_reset_query(); ?>

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();
?>
<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>

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

ADD CSS VÀO DASHBOARD

Đầu tiên tạo file custom-admin-styles.css trong thư mục gốc của theme đang dùng. Sau đó chèn đoạn code sau vào functions.

function enqueue_custom_css() {
   wp_enqueue_style( 'icon-style', get_template_directory_uri() . '/css/all.min.css' );
   wp_enqueue_style( 'bootstrap-style', get_template_directory_uri() . '/css/bootstrap.min.css' );
   wp_enqueue_style( 'player-style', get_template_directory_uri() . '/css/player.css' );
   wp_enqueue_style( 'custom-style', get_template_directory_uri() . '/css/style.css' );
}
add_action( 'wp_enqueue_scripts', 'enqueue_custom_css' );

function my_custom_script() {
    wp_enqueue_script( 'jquery-script', get_template_directory_uri() . '/js/jquery.min.js', array(), '1.0', true );
    wp_enqueue_script( 'bootstrap-script', get_template_directory_uri() . '/js/bootstrap.bundle.min.js', array(), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_custom_script' );

Sau đó vào trang quản trị và thêm css trong file custom-admin-styles.css để thêm css cho trang quan trị

ĐĂNG NHẬP HIỆN NỘI DUNG

add_shortcode( 'userview', 'vnkings_check_user_login' );
function vnkings_check_user_login($atts, $content = null) {
    if( is_user_logged_in() ) {return '<p>' . $content . '</p>';}
    else {return "Bạn cần đăng nhập để xem nội dung này!";}
}

Cách dùng: chèn shortcode [userview] Nội dung [/userview]

BÀI VIẾT LIÊN QUAN THEO TAXONOMY

      <?php
$taxonomyName = 'the-loai'; // Replace 'the-loai' with the actual taxonomy name
if ($taxonomyName){
   echo '<div class="relatedcat-tl">';
   $category_ids = wp_get_post_terms(get_the_ID(), $taxonomyName, array('fields' => 'ids'));
   $args = array( 
      'post_type' =>  $postType, // Replace $postType with the actual post type
      'post__not_in' => array(get_the_ID()),
      'posts_per_page' => 5,
      'tax_query' => array(
         array(
            'taxonomy' => $taxonomyName,
            'field'    => 'term_id',
            'terms'    => $category_ids,
         ),
      )
   );
   $my_query = new WP_Query($args);
   if( $my_query->have_posts() ):
     echo '<h3>Truyện cùng thể loại</h3>';
     ?>
     <div class="row row-cols-2 row-cols-sm-3 row-cols-md-4 row-cols-lg-5 row-cols-xl-5">
      <?php
      while ($my_query->have_posts()):$my_query->the_post();
         ?>
         <div class="col mb-4">
            <div class="main-post">
               <div class="card">
                  <a href="<?php the_permalink(); ?>"><?php echo get_the_post_thumbnail( get_the_id(), 'full', array( 'class' =>'thumnail') ); ?></a>
                  <span class="status"><?php echo get_post_meta(get_the_ID(), 'tinh_trang', true) ?></span>
                  <div class="card-body">
                   <h4 class="card-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
                   <ul class="slide-detail">
                     <li><span class="cat-card"><i class="bi bi-people-fill"></i> <?php the_category(', ')?></span></li>
                     <li><i class="bi bi-calendar-check"></i> Update: <?php echo get_the_date('d/m/y'); ?></li>
                  </ul>
               </div>
            </div>
         </div>
      </div>
      <?php
   endwhile;
endif; wp_reset_query();
echo '</div>';
}
?>

HIDE VERSION CSS – JS

function remove_css_js_version( $src ) {
  if( strpos( $src, '?ver=' ) )
    $src = remove_query_arg( 'ver', $src );
  return $src;
}
add_filter( 'style_loader_src', 'remove_css_js_version', 9999 );
add_filter( 'script_loader_src', 'remove_css_js_version', 9999 );

GET MÔ TẢ NGẮN

function custom_excerpt_length( $length ) {
        return 30;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
<?php the_excerpt(); ?>

SHARE POST

function add_social_share_buttons() {
    if (is_single()) {
        $post_title = urlencode(get_the_title());
        $post_url = urlencode(get_permalink());
        $twitter_url = 'https://twitter.com/intent/tweet?text=' . $post_title . '&url=' . $post_url;
        $facebook_url = 'https://www.facebook.com/sharer/sharer.php?u=' . $post_url;
        $linkedin_url = 'https://www.linkedin.com/shareArticle?mini=true&url=' . $post_url . '&title=' . $post_title;
        $pinterest_url = 'https://pinterest.com/pin/create/button/?url=' . $post_url . '&media=' . get_the_post_thumbnail_url() . '&description=' . $post_title;
        $instagram_url = 'https://www.instagram.com/';
        
        echo '<div class="social-share-buttons">';
        echo '<a href="' . $twitter_url . '" target="_blank" rel="nofollow"><i class="fab fa-twitter"></i></a>';
        echo '<a href="' . $facebook_url . '" target="_blank" rel="nofollow"><i class="fab fa-facebook"></i></a>';
        echo '<a href="' . $linkedin_url . '" target="_blank" rel="nofollow"><i class="fab fa-linkedin"></i></a>';
        echo '<a href="' . $pinterest_url . '" target="_blank" rel="nofollow"><i class="fab fa-pinterest"></i></a>';
        echo '<a href="' . $instagram_url . '" target="_blank" rel="nofollow"><i class="fab fa-instagram"></i></a>';
        echo '</div>';
    }
}
add_action('wp_footer', 'add_social_share_buttons');
<?php if (function_exists('add_social_share_buttons')) { add_social_share_buttons(); } ?>

TẠO CUSTOM TAXONOMY

Tạo Custom Taxonomy

function custom_taxonomy() {
    $labels = array(
        'name'              => _x( 'Taxonomy', 'taxonomy general name', 'textdomain' ),
        'singular_name'     => _x( 'Taxonomy', 'taxonomy singular name', 'textdomain' ),
        'search_items'      => __( 'Search Taxonomies', 'textdomain' ),
        'all_items'         => __( 'All Taxonomies', 'textdomain' ),
        'parent_item'       => __( 'Parent Taxonomy', 'textdomain' ),
        'parent_item_colon' => __( 'Parent Taxonomy:', 'textdomain' ),
        'edit_item'         => __( 'Edit Taxonomy', 'textdomain' ),
        'update_item'       => __( 'Update Taxonomy', 'textdomain' ),
        'add_new_item'      => __( 'Add New Taxonomy', 'textdomain' ),
        'new_item_name'     => __( 'New Taxonomy Name', 'textdomain' ),
        'menu_name'         => __( 'Taxonomy', 'textdomain' ),
    );

    $args = array(
        'hierarchical'      => true,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'rewrite'           => array( 'slug' => 'taxonomy' ),
    );

    register_taxonomy( 'taxonomy', array( 'post' ), $args );
}
add_action( 'init', 'custom_taxonomy', 0 );

Bài viết cùng custom taxonomy

   <div class="relat-0">
      <?php
$taxonomyName = 'tac-gia'; // Replace 'the-loai' with the actual taxonomy name
if ($taxonomyName){
   echo '<div class="relatedcat-tg">';
   $category_ids = wp_get_post_terms(get_the_ID(), $taxonomyName, array('fields' => 'ids'));
   $args = array( 
      'post_type' =>  $postType, // Replace $postType with the actual post type
      'post__not_in' => array(get_the_ID()),
      'posts_per_page' => 4,
      'tax_query' => array(
         array(
            'taxonomy' => $taxonomyName,
            'field'    => 'term_id',
            'terms'    => $category_ids,
         ),
      )
   );
   $my_query = new WP_Query($args);
   if( $my_query->have_posts() ):
    echo '<h3>Truyện cùng tác giả</h3>';
    ?>
    <div class="row row-cols-2 row-cols-sm-3 row-cols-md-4 row-cols-lg-4 row-cols-xl-4">
      <?php
      while ($my_query->have_posts()):$my_query->the_post();
         ?>
         <div class="col">
            <div class="main-post">
               <div class="card">
                  <a href="<?php the_permalink(); ?>"><?php echo get_the_post_thumbnail( get_the_id(), 'full', array( 'class' =>'thumnail') ); ?></a>
                  <span class="status"><?php echo get_post_meta(get_the_ID(), 'tinh_trang', true) ?></span>
                  <div class="card-body">
                    <h4 class="card-title tg"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
                    <ul class="slide-detail">
                     <li><span class="cat-card"><i class="bi bi-people-fill"></i> <?php the_category(', ')?></span></li>
                     <li><i class="bi bi-calendar-check"></i> Update: <?php echo get_the_date('d/m/y'); ?></li>
                  </ul>
               </div>
            </div>
         </div>
      </div>
      <?php
   endwhile;
endif; wp_reset_query();
echo '</div>';
}
?>
</div>
</div>

TẠO METABOX

Tạo thu mục metabox và tạo form.php và chèn code dưới vào

<div class="hcf_box">
    <style scoped>
        .hcf_box{
            display: grid;
            grid-template-columns: max-content 1fr;
            grid-row-gap: 10px;
            grid-column-gap: 20px;
        }
        .hcf_field{
            display: contents;
        }
    </style>
    <p class="meta-options hcf_field">
        <label for="hcf_version">Version</label>
        <input id="hcf_version"
            type="text"
            name="hcf_version"
            value="<?php echo esc_attr( get_post_meta( get_the_ID(), 'hcf_version', true ) ); ?>">
    </p>
        <p class="meta-options hcf_field">
        <label for="hcf_developer">Tính năng</label>
        <input id="hcf_developer"
            type="text"
            name="hcf_developer"
            value="<?php echo esc_attr( get_post_meta( get_the_ID(), 'hcf_developer', true ) ); ?>">
    </p>
            <p class="meta-options hcf_field">
        <label for="hcf_geton">Get On</label>
        <input id="hcf_geton"
            type="text"
            name="hcf_geton"
            value="<?php echo esc_attr( get_post_meta( get_the_ID(), 'hcf_geton', true ) ); ?>">
    </p>
</div>

Chèn vào functions.php

function hcf_register_meta_boxes() {
  add_meta_box( 'hcf-1', __( 'Giới thiệu ứng dụng', 'hcf' ), 'hcf_display_callback', 'post' );
}
add_action( 'add_meta_boxes', 'hcf_register_meta_boxes' );

function hcf_display_callback( $post ) {
  include plugin_dir_path( __FILE__ ) . '/metabox/form.php';
}
function hcf_save_meta_box( $post_id ) {
  if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
  if ( $parent_id = wp_is_post_revision( $post_id ) ) {
    $post_id = $parent_id;
  }
  $fields = [
    'hcf_version',
    'hcf_developer',
    'hcf_geton',
  ];
  foreach ( $fields as $field ) {
    if ( array_key_exists( $field, $_POST ) ) {
      update_post_meta( $post_id, $field, sanitize_text_field( $_POST[$field] ) );
    }
  }
}
add_action( 'save_post', 'hcf_save_meta_box' );

Hiển thị MetaBox

<ul class="lh-base">
	<li>Feature: <?php
		$meta_value = get_post_meta( get_the_ID(), 'hcf_developer', true );
		if ( ! empty( $meta_value ) ) {
			echo esc_attr( $meta_value );
		} else {
			echo 'Đang cập nhật';
		}
	?></li>
	<li>Version: <?php $meta_value = get_post_meta( get_the_ID(), 'hcf_version', true );
		if ( ! empty( $meta_value ) ) { echo esc_attr( $meta_value ); } else { echo 'Đang cập nhật'; } ?></li>
		<li>Get it On: <a href="<?php $meta_value = get_post_meta( get_the_ID(), 'hcf_geton', true ); if ( ! empty( $meta_value ) ) { echo esc_attr( $meta_value ); } else { echo home_url(); } ?>" target="_blank" rel="nofollow"><span class="fw-bolder text-danger">Google Play</span></a></li>
		<li>Download Apk: <span class="fw-bolder dload"><a href="#download">Download</a></span></li>
</ul>

TẠO REPEATER

add_action('admin_init', 'hhs_add_meta_boxes', 1);
function hhs_add_meta_boxes() {
  add_meta_box( 'repeatable-fields', 'Link download', 'hhs_repeatable_meta_box_display', 'post', 'normal', 'default');
}
function hhs_repeatable_meta_box_display() {
  global $post;
  $repeatable_fields = get_post_meta($post->ID, 'repeatable_fields', true);
  wp_nonce_field( 'hhs_repeatable_meta_box_nonce', 'hhs_repeatable_meta_box_nonce' );
  ?>
  <script type="text/javascript">
    jQuery(document).ready(function( $ ){
      $( '#add-row' ).on('click', function() {
        var row = $( '.empty-row.screen-reader-text' ).clone(true);
        row.removeClass( 'empty-row screen-reader-text' );
        row.insertBefore( '#repeatable-fieldset-one tbody>tr:last' );
        return false;
      });
      $( '.remove-row' ).on('click', function() {
        $(this).parents('tr').remove();
        return false;
      });
    });
  </script>
  <table id="repeatable-fieldset-one" width="100%">
    <thead>
      <tr>
        <th width="50%">Name</th>
        <th width="50%">URL</th>
        <th width="10%"></th>
      </tr>
    </thead>
    <tbody>
      <?php
      if ( $repeatable_fields ) :
        foreach ( $repeatable_fields as $field ) {
          ?>
          <tr>
            <td><input type="text" class="widefat" name="name[]" value="<?php if($field['name'] != '') echo esc_attr( $field['name'] ); ?>" /></td>
            <td><input type="text" class="widefat" name="url[]" value="<?php if ($field['url'] != '') echo esc_attr( $field['url'] ); else echo 'https://'; ?>" /></td>
            <td><a class="button remove-row" href="#">Remove</a></td>
          </tr>
          <?php
        }
      else :
        ?>
        <tr>
          <td><input type="text" class="widefat" name="name[]" /></td>
          <td><input type="text" class="widefat" name="url[]" value="https://" /></td>
          <td><a class="button remove-row" href="#">Remove</a></td>
        </tr>
      <?php endif; ?>
      <!-- empty hidden one for jQuery -->
      <tr class="empty-row screen-reader-text">
        <td><input type="text" class="widefat" name="name[]" /></td>
        <td><input type="text" class="widefat" name="url[]" value="https://" /></td>
        <td><a class="button remove-row" href="#">Remove</a></td>
      </tr>
    </tbody>
  </table>
  <p><a id="add-row" class="button" href="#">Add another</a></p>
  <?php
}
add_action('save_post', 'hhs_repeatable_meta_box_save');
function hhs_repeatable_meta_box_save($post_id) {
  if ( ! isset( $_POST['hhs_repeatable_meta_box_nonce'] ) ||
    ! wp_verify_nonce( $_POST['hhs_repeatable_meta_box_nonce'], 'hhs_repeatable_meta_box_nonce' ) )
    return;
  if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
    return;
  if (!current_user_can('edit_post', $post_id))
    return;
  $old = get_post_meta($post_id, 'repeatable_fields', true);
  $new = array();
  $names = $_POST['name'];
  $selects = $_POST['select'];
  $urls = $_POST['url'];
  $count = count( $names );
  for ( $i = 0; $i < $count; $i++ ) {
    if ( $names[$i] != '' ) :
      $new[$i]['name'] = stripslashes( strip_tags( $names[$i] ) );

      if ( $urls[$i] == 'https://' )
        $new[$i]['url'] = '';
      else
        $new[$i]['url'] = stripslashes( $urls[$i] ); // and however you want to sanitize
    endif;
  }
  if ( !empty( $new ) && $new != $old )
    update_post_meta( $post_id, 'repeatable_fields', $new );
  elseif ( empty($new) && $old )
    delete_post_meta( $post_id, 'repeatable_fields', $old );
}

Hiển thị Repeater

<?php if ($field['name'] != '') echo '<span class="field">' . esc_attr($field['name']) . '</span>'; ?>

Tạo Option Page

Tạo option.php

<?php
define('WS247_GE_FIELDS_GROUP', 'theme_options');

add_action('admin_init', 'apkcombo_register_option_fields' );
function apkcombo_register_option_fields(){
    //Khai báo các trường dữ liệu cho theme option tại đây
    register_setting( WS247_GE_FIELDS_GROUP, 'wpshare247_facebook');
    register_setting( WS247_GE_FIELDS_GROUP, 'wpshare247_massage');
    register_setting( WS247_GE_FIELDS_GROUP, 'wpshare247_slogan');
    register_setting( WS247_GE_FIELDS_GROUP, 'wpshare247_des');
    register_setting( WS247_GE_FIELDS_GROUP, 'wpshare247_footer');
    register_setting( WS247_GE_FIELDS_GROUP, 'wpshare247_license');
}
add_action("admin_menu", 'wpshare247_create_theme_option_page');
function wpshare247_create_theme_option_page(){
    $page_title = 'Theme Config';
    $menu_title = $page_title;
    $capability = 'manage_options';
    $menu_slug = 'wpshare247-theme-options';
    $function_callback = 'wpshare247_the_content_option_fields';
    $icon_url = '';
    $position = 60;
    add_menu_page($page_title, $menu_title, $capability, $menu_slug , $function_callback, $icon_url, $position);
}
function wpshare247_the_content_option_fields(){
    ?>
    <div id="poststuff" class="w366-options-area">
        <div class="postbox-container">
            <div class="meta-box-sortables ui-sortable">
                <div class="postbox ">
                    <h2 class="hndle ui-sortable-handle">THEME OPTION APPYN</h2>
                    <div class="wle-tab-content">
                        <form method="post" action="options.php">
                            <?php settings_fields( WS247_GE_FIELDS_GROUP ); ?>
                            <?php do_settings_sections( WS247_GE_FIELDS_GROUP ); ?>
                            <div class="wpshare247-option-fields">

                                <!-----------------------SLOGAN---------------------->

                                <table class="form-table">
                                    <p style="margin-left: 10px;color: red; font-weight: bold;font-size: 13px;">&#9745; TEXT HEADER</p>
                                    <tr valign="top">
                                        <td style="width:30%"><strong><?php esc_html_e("Slogan", 'f4vnn.com'); ?></strong></td>
                                        <td>
                                            <?php $wpshare247_slogan = get_option('wpshare247_slogan');?>
                                            <input style="width:100%" placeholder="Slogan" type="text" id="<?php echo esc_html('wpshare247_slogan'); ?>" name="<?php echo esc_html('wpshare247_slogan'); ?>" value="<?php echo esc_attr($wpshare247_slogan); ?>" />
                                        </td>
                                    </tr>
                                    <tr valign="top">
                                        <td style="width:30%"><strong><?php esc_html_e("Mô tả ngắn", 'f4vnn.com'); ?></strong></td>
                                        <td>
                                            <?php $wpshare247_des = get_option('wpshare247_des');?>
                                            <textarea style="width:100%" placeholder="Nội dung text" type="text" id="<?php echo esc_html('wpshare247_des'); ?>" name="<?php echo esc_html('wpshare247_des'); ?>"><?php echo esc_textarea($wpshare247_des); ?></textarea>
                                        </td>
                                    </tr>
                                    <tr valign="top">
                                        <td colspan="2"><?php submit_button(); ?></td>
                                    </tr>
                                </table>

                                <!-----------------------SOCIAL---------------------->

                                <table class="form-table">
                                    <p style="margin-left: 10px;color: red; font-weight: bold;font-size: 13px;">&#9745; SOCIAL</p>
                                    <tr valign="top">
                                        <td style="width:30%"><strong><?php esc_html_e("Facebook", 'f4vnn.com'); ?></strong></td>
                                        <td>
                                            <?php $wpshare247_facebook = get_option('wpshare247_facebook');?>
                                            <input style="width:100%" placeholder="Facebook" type="text" id="<?php echo esc_html('wpshare247_facebook'); ?>" name="<?php echo esc_html('wpshare247_facebook'); ?>" value="<?php echo esc_attr($wpshare247_facebook); ?>" />
                                        </td>
                                    </tr>
                                    <tr valign="top">
                                        <td style="width:30%"><strong><?php esc_html_e("Massage FB", 'f4vnn.com'); ?></strong></td>
                                        <td>
                                            <?php $wpshare247_massage = get_option('wpshare247_massage');?>
                                            <input style="width:100%" placeholder="Massage" type="text" id="<?php echo esc_html('wpshare247_massage'); ?>" name="<?php echo esc_html('wpshare247_massage'); ?>" value="<?php echo esc_attr($wpshare247_massage); ?>" />
                                        </td>
                                    </tr>
                                    <tr valign="top">
                                        <td colspan="2"><?php submit_button(); ?></td>
                                    </tr>
                                </table>

                                <!-----------------------FOOTER---------------------->

                                <table class="form-table">
                                    <p style="margin-left: 10px;color: red; font-weight: bold;font-size: 13px;">&#9745; FOOTER</p>
                                    <tr valign="top">
                                        <td style="width:30%"><strong><?php esc_html_e("Mô tả ngắn chân trang", 'f4vnn.com'); ?></strong></td>
                                        <td>
                                            <?php $wpshare247_footer = get_option('wpshare247_footer');?>
                                            <textarea style="width:100%" placeholder="Nội dung text footer" type="text" id="<?php echo esc_html('wpshare247_footer'); ?>" name="<?php echo esc_html('wpshare247_footer'); ?>"><?php echo esc_textarea($wpshare247_footer); ?></textarea>
                                        </td>
                                    </tr>
                                    <tr valign="top">
                                        <td style="width:30%"><strong><?php esc_html_e("Bản quyền", 'f4vnn.com'); ?></strong></td>
                                        <td>
                                            <?php $wpshare247_license = get_option('wpshare247_license');?>
                                            <input style="width:100%" placeholder="Bản quyền" type="text" id="<?php echo esc_html('wpshare247_license'); ?>" name="<?php echo esc_html('wpshare247_license'); ?>" value="<?php echo esc_attr($wpshare247_license); ?>" />
                                        </td>
                                    </tr>
                                    <tr valign="top">
                                        <td colspan="2"><?php submit_button(); ?></td>
                                    </tr>
                                </table>
                            </div>
                        </form>
                    </div>
                    <div style="clear:both;"></div>
                </div>
            </div>
        </div>
    </div>
    <?php
}

Chèn vào Functions.php

require_once get_parent_theme_file_path( '/option.php' );

Hiển thị option

<?php
	$wpshare247_slogan = get_option('wpshare247_slogan');
	if (!empty($wpshare247_slogan)) {
		echo "$wpshare247_slogan";
	}

ẨN PAGE KHỎI TÌM KIẾM

function exclude_page_from_search($query) {
    if ( $query->is_search ) {
        $query->set( 'post_type', 'post' );
    }
    return $query;
}
add_filter('pre_get_posts','exclude_page_from_search');

NÉN HTML

class FLHM_HTML_Compression
{
protected $flhm_compress_css = true;
protected $flhm_info_comment = true;
protected $flhm_remove_comments = true;
protected $html;

public function __construct($html)
{
    if (!empty($html))
    {
        $this->flhm_parseHTML($html);
    }
}

public function __toString()
{
    return $this->html;
}

protected function flhm_bottomComment($raw, $compressed)
{
    $raw = strlen($raw);
    $compressed = strlen($compressed);
    $savings = ($raw-$compressed) / $raw * 100;
    $savings = round($savings, 2);
    return '<!--HTML compressed, size saved '.$savings.'%. From '.$raw.' bytes, now '.$compressed.' bytes-->';
}

protected function flhm_minifyHTML($html)
{
    $pattern = '/<(?<script>script).*?<\/script\s*>|<(?<style>style).*?<\/style\s*>|<!(?<comment>--).*?-->|<(?<tag>[\/\w.:-]*)(?:".*?"|\'.*?\'|[^\'">]+)*>|(?<text>((<[^!\/\w.:-])?[^<]*)+)|/si';
    preg_match_all($pattern, $html, $matches, PREG_SET_ORDER);
    $overriding = false;
    $raw_tag = false;
    $html = '';
    foreach ($matches as $token)
    {
        $tag = (isset($token['tag'])) ? strtolower($token['tag']) : null;
        $content = $token[0];
        if (is_null($tag))
        {
            if (!empty($token['script']))
            {
                $strip = $this->flhm_compress_js;
            }
            else if (!empty($token['style']))
            {
                $strip = $this->flhm_compress_css;
            }
            else if ($content == '<!--wp-html-compression no compression-->')
            {
                $overriding = !$overriding;
                continue;
            }
            else if ($this->flhm_remove_comments)
            {
                if (!$overriding && $raw_tag != 'textarea')
                {
                    $content = preg_replace('/<!--(?!\s*(?:\[if [^\]]+]|<!|>))(?:(?!-->).)*-->/s', '', $content);
                }
            }
        }
        else
        {
            if ($tag == 'pre' || $tag == 'textarea')
            {
                $raw_tag = $tag;
            }
            else if ($tag == '/pre' || $tag == '/textarea')
            {
                $raw_tag = false;
            }
            else
            {
                if ($raw_tag || $overriding)
                {
                    $strip = false;
                }
                else
                {
                    $strip = true;
                    $content = preg_replace('/(\s+)(\w++(?<!\baction|\balt|\bcontent|\bsrc)="")/', '$1', $content);
                    $content = str_replace(' />', '/>', $content);
                }
            }
        }
        if ($strip)
        {
            $content = $this->flhm_removeWhiteSpace($content);
        }
        $html .= $content;
    }
    return $html;
}

public function flhm_parseHTML($html)
{
    $this->html = $this->flhm_minifyHTML($html);
    if ($this->flhm_info_comment)
    {
        $this->html .= "\n" . $this->flhm_bottomComment($html, $this->html);
    }
}

protected function flhm_removeWhiteSpace($str)
{
    $str = str_replace("\t", ' ', $str);
    $str = str_replace("\n", '', $str);
    $str = str_replace("\r", '', $str);
    $str = str_replace("// The customizer requires postMessage and CORS (if the site is cross domain).", '', $str);
    while (stristr($str, '  '))
    {
        $str = str_replace('  ', ' ', $str);
    }
    return $str;
}

}

function flhm_wp_html_compression_finish($html)
{
return new FLHM_HTML_Compression($html);
}

function flhm_wp_html_compression_start()
{
ob_start(‘flhm_wp_html_compression_finish’);
}

add_action(‘get_header’, ‘flhm_wp_html_compression_start’);

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.

Theo dõi trên

Logo Google new
5/5 - (8 bình chọn)