Mình không phải code Pro lắm đâu chịu khó mò mẫm là ra hết, ae có cái gì hay muốn chia sẻ thì nhắn mình update lên bài….. Bài viết này mính chỉ viết các hàm hữu ích + cơ bản còn về Woocommerce mình sẽ viết 1 bài riêng nó chuyên biệt hơn.
Những đoạn mã WordPress hay
1. Tắt Thanh công cụ dành cho quản trị viên
Nếu bạn muốn tắt thanh công cụ quản trị WordPress trên tất cả các trang cho người dùng đã đăng nhập, hãy sử dụng đoạn mã bên dưới trong các chủ đề functions.php của bạn.
1 2 |
//Disable WordPress admin bar for all logged in users add_filter('show_admin_bar', '__return_false'); |
2. Hiển thị hình thu nhỏ bài đăng của trong nguồn RSS
Theo mặc định, WordPress chỉ hiển thị văn bản trong nguồn cấp dữ liệu RSS. Nhưng nếu bạn muốn bao gồm hình ảnh đại diện của bài viết, hãy sử dụng đoạn mã này.
1 2 3 4 5 6 7 8 9 10 11 12 |
//This will prepend your WordPress RSS feed content with the featured image add_filter('the_content', 'hwp_featured_image_in_rss_feed'); function hwp_featured_image_in_rss_feed( $content ) { global $post; if( is_feed() ) { if ( has_post_thumbnail( $post->ID ) ){ $prepend = '<div>' . get_the_post_thumbnail( $post->ID, 'medium', array( 'style' => 'margin-bottom: 10px;' ) ) . '</div>'; $content = $prepend . $content; } } return $content; } |
3. Thay đổi độ dài đoạn trích của bài đăng
Theo mặc định, độ dài của đoạn trích trong WordPress là 55 từ. Đoạn mã này sẽ thay đổi độ dài của đoạn trích thành 25 từ hoặc bạn có thể giá trị bạn muốn.
1 2 3 4 5 |
//Change the default excerpt length in WordPress (default is 55 words) function hwp_change_excerpt_length( $length ) { return 25; } add_filter( 'excerpt_length', 'smartwp_change_excerpt_length', 9999); |
4. Thêm người dùng quản trị bằng PHP
Sẽ có trường hợp chúng ta làm việc trên một trang web mới mà không có thông tin đăng nhập. Thì đoạn mã này hữu ích để thêm quản trị viên mới vào một trang web bằng cách sử dụng function.php của chủ đề.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
//Create an admin user function hwp_create_admin_user(){ $username = 'customuser'; $password = '2JyAEQJ9B9Jf5T8a'; $email = 'change@me.com'; //This will ensure it only tries to create the user once (based on email/username) if ( !username_exists( $username ) && !email_exists( $email ) ) { $userid = wp_create_user( $username, $password, $email ); $user = new WP_User( $userid ); $user->set_role( 'administrator' ); } } add_action('init', 'hwp_create_admin_user'); |
5. Bật Shortcodes trong văn bản Widgets
Các mã Shortcodes cực kỳ mạnh mẽ trong WordPress và việc có thể sử dụng chúng trong các widget là rất hữu ích. Đoạn mã này sẽ cho phép bạn thêm các mã Shortcodes trong tiện ích văn bản và thực thi chúng.
1 2 |
//Enable shortcodes in text widgets add_filter('widget_text', 'do_shortcode'); |
6. Thay đổi logo WordPress trong trang admin
Bạn có thể thay đổi logo bên trái trang quản trị bằng đoạn code sau. Lấy đường dẫn từ media or upload qua cổng FTP nhé ae!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
//Adds a custom logo to the top left of the WordPress admin function hwp_custom_logo_wp_dashboard() { echo "<style type='text/css'> #wpadminbar #wp-admin-bar-wp-logo > .ab-item .ab-icon:before { background-image: url('/wp-content/uploads/2022/08/logo.png'); background-size: contain; background-position: 0 0; color:rgba(0, 0, 0, 0); } #wpadminbar #wp-admin-bar-wp-logo > .ab-item .ab-icon { background-position: 0 0; } </style>"; } add_action('wp_before_admin_bar_render', 'hwp_custom_logo_wp_dashboard'); |
7. Loại bỏ jQuery Migrate
jQuery Migrate bổ sung hỗ trợ cho các phiên bản jQuery cũ hơn, thường hữu ích cho các chủ đề cũ hơn. Theo thật tế, hiếm khi cần đến nó, vì vậy tốt nhất là xóa nó để loại bỏ một yêu cầu khỏi tải trang, tăng tốc độ tải trang.
Sau khi xóa jQuery Migrate, hãy kiểm tra lại một vài trang của bạn để đảm bảo trang web vẫn hoạt động bình thường nhé.
1 2 3 4 5 6 7 |
//Remove jQuery migrate function hwp_remove_jquery_migrate( $scripts ) { if ( !is_admin() && !empty( $scripts->registered['jquery'] ) ) { $scripts->registered['jquery']->deps = array_diff( $scripts->registered['jquery']->deps, ['jquery-migrate'] ); } } add_action('wp_default_scripts', 'hwp_remove_jquery_migrate'); |
8. Xóa số phiên bản WordPress
Ẩn phiên bản WP là điều tốt tránh hacker khai thác lỗ hổng từ các phiên bản WP đang sử dụng, bạn có thể thêm đoạn mã này vào function.php của mình
1 2 3 |
// Remove the version number of WP // Warning - this info is also available in the readme.html file in your root directory - delete this file! remove_action('wp_head', 'wp_generator'); |
9. Ẩn thông báo cập nhật WordPress
Đôi khi cập nhật những phiên bản mới sẽ gây lên lỗi cho web của bạn. Hoặc bạn cần trì hoãn việc cập nhật để sao lưu trang web trước khi thực hiện cập nhật. Thì dùng mã này.
1 2 3 4 5 |
// Hide WordPress Update function wp_hide_update() { remove_action('admin_notices', 'update_nag', 3); } add_action('admin_menu','wp_hide_update'); |
10. Xóa trường URL nhận xét
Nếu blog của bạn liên tục bị những người comment rác, bạn có thể xóa trường URL khỏi các nhận xét, điều này sẽ lấy đi lý do để họ tiếp tục spam.
1 2 3 4 5 6 |
//Remove URL Comment <strong>function</strong> remove_comment_fields($fields) { unset($fields['url']); <strong>return</strong> $fields; } add_filter('comment_form_default_fields','remove_comment_fields'); |
11. Tắt Widget không dùng tới
Với những Widget không dùng tới bạn có thể tắt, xóa nó đi, để nhẹ hơn.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
//Hide Widget not use add_action( 'widgets_init', function () { unregister_widget( 'WP_Widget_Pages' ); unregister_widget( 'WP_Widget_Calendar' ); unregister_widget( 'WP_Widget_Archives' ); unregister_widget( 'WP_Widget_Links' ); unregister_widget( 'WP_Widget_Meta' ); unregister_widget( 'WP_Widget_Search' ); unregister_widget( 'WP_Widget_Text' ); unregister_widget( 'WP_Widget_Categories' ); unregister_widget( 'WP_Widget_Recent_Posts' ); unregister_widget( 'WP_Widget_Recent_Comments' ); unregister_widget( 'WP_Widget_RSS' ); unregister_widget( 'WP_Widget_Tag_Cloud' ); unregister_widget( 'WP_Nav_Menu_Widget' ); }, 11); |
12. Sử dụng font chữ Google cho WordPress
Có nhiều cách để sử dụng font chữ ngoài, như của Google. Một trong những cách đơn giãn là dùng code sau.
1 2 3 4 5 6 |
// Su dung font chu Google function google_fonts() { wp_register_style( 'OpenSans', '//fonts.googleapis.com/css?family=Open+Sans:400,600,700,800' ); wp_enqueue_style( 'OpenSans' ); } add_action( 'wp_print_styles', 'google_fonts' ); |
13. Hiển thị tổng số bài viết công khai
1 2 3 4 5 |
// Hiển thị tổng số bài viết function wpb_total_posts() { $total = wp_count_posts()->publish; echo 'Total Posts: ' . $total; } |
14. 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="pagination"> <?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 } ?> |
15. Code crop ảnh
Khai báo kích thước ảnh cần Crop vào file function.php
1 2 3 4 5 6 7 |
add_action( 'after_setup_theme', 'hwp_theme_setup' ); function hwp_theme_setup() { add_image_size( 'kich-thuoc-1', 750, 375, true); add_image_size( 'kich-thuoc-2', 300, 200, true); add_image_size( 'kich-thuoc-3', 270, 200, true); add_image_size( 'kich-thuoc-4', 215, 130, true); } |
16. Code hiển thị bài viết liên quan theo Tags
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 |
<!-- Hiển thị bài viết theo Tag --> <div id="relatedposttags"> <?php global $post; $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> |
17. Lấy bà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 35 |
<?php global $post; $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>'; } } ?> |
18. Code tính lượt view cho bài viết
Đặt đoạn code này vào file function.php
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; } |
Chú ý:
* Đặt code này vào single.php để đếm cho từng bài.
1 2 3 |
<?php setpostview(get_the_id($post->ID)); ?> |
* Hiện thị lượt view bài viết.
1 2 3 |
<?php echo getpostviews(get_the_id()); ?> |
19. Code lấy ảnh đầu tiên trong bài viết làm ảnh đại diện
Ae lười hay quên đăng ảnh đại diện bài viết thì dùng đoạn code dưới đây vào function.php
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; } |
Sử dụng đoạn code trên sử dụng đoạn này:
1 |
<img src="<?php echo catch_that_image() ?>" /> |
20. Tắt script biểu tượng cảm xúc.
1 2 3 |
// Disable the emoji's remove_action('wp_head', 'print_emoji_detection_script', 7); remove_action('wp_print_styles', 'print_emoji_styles'); |
21. Dọn dẹp phần header gọn gàng.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Remove auto generated feed links function hwp_remove_feeds() { remove_action( 'wp_head', 'feed_links_extra', 3 ); remove_action( 'wp_head', 'feed_links', 2 ); remove_action( 'wp_head', 'rsd_link'); remove_action( 'wp_head', 'wlwmanifest_link'); remove_action( 'wp_head', 'wp_generator'); remove_action( 'wp_head', 'start_post_rel_link'); remove_action( 'wp_head', 'index_rel_link'); remove_action( 'wp_head', 'adjacent_posts_rel_link'); remove_action( 'wp_head', 'wp_shortlink_wp_head'); } add_action( 'after_setup_theme', 'hwp_remove_feeds' ); |
22. Xóa đường link trong Comment
Nếu một ai đó cố tình chèn link vào trong nội dung bình luận thì cũng vô ích, vì nó cũng sẽ hiển thị dạng text thông thường mà thôi, nó không hề có liên kết. Điều này sẽ giúp hạn chế spam link.
1 2 |
// Do not create link path in the comments remove_filter('comment_text', 'make_clickable', 9); |
23. Tự động thêm thuộc tính nofollow cho liên kết ngoài trong bài viết
Nếu blog của bạn có nhiều thành viên viết bài, họ có thể chèn liên kết trỏ ra ngoài. Code này sẽ giúp tự động thêm rel=”nofollow” cho mỗi liên kết được chèn vào nội dung.
1 2 3 4 5 6 |
// Add nofollow function my_nofollow($content) { return stripslashes(wp_rel_nofollow($content)); } add_filter('the_content', 'my_nofollow'); |
24. Tắt chức năng tự động lưu bài nháp.
1 2 3 4 5 |
add_action('wp_print_scripts', 'disable_autosave'); function disable_autosave() { wp_deregister_script('autosave'); } |
25. Xóa phiên bản khỏi CSS và JS
Bạn mở file function.php trong thư mục theme mà bạn đang sử dụng lên, sao chép đoạn code bên dưới dán vào rồi lưu lại.
1 2 3 4 5 6 7 8 |
// xoa phien ban wp khoi css va 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 ); |
26. Thêm thuộc tính tải không đồng bộ js
điều này sẽ giúp website của chúng ta tải nhanh hơn, website sẽ load nội dung và css trước, sau đó mới load script. Dưới đây là hai đoạn code giúp tải không đồng bộ, nhưng cách viết khác nhau, bạn chỉ sử dụng một trong hai đoạn thôi nhé, mỗi dấu // là một đoạn.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Asynchronous load JS function defer_parsing_of_js ( $url ) { if ( FALSE === strpos( $url, '.js' ) ) return $url; return "$url' async defer='defer"; } add_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 ); // Asynchronous load JS function async_js($tag){ $scripts_to_async = array('jquery.js', 'jquery-migrate.min.js'); foreach($scripts_to_async as $async_script){ if(true == strpos($tag, $async_script ) ) return str_replace(' src', ' async="async" src', $tag); } return $tag; } add_filter( 'script_loader_tag', 'async_js', 10); |
…………………………………………. Vẫn còn tiếp nhé mình sẽ update dần dần
…………………………………………. Ủng hộ bằng cách like và share đóng góp ý kiến để mình hoàn thiện.