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 Functions hay trong lập trình theme WordPress

NỘI DUNG (HIGHLIGHTS)

Functions hay trong lập trình theme WordPress: Tất cả các chủ đề giao diện WordPress đều đi kèm với tệp functions.php. Tệp này hoạt động như một plugin, cho phép các nhà phát triển giao diện và người dùng phổ thông thêm mã tùy chỉnh vào WordPress một cách dễ dàng. Trong bài viết này, chúng tôi sẽ chỉ cho bạn một số thủ thuật hữu ích cho tệp functions WordPress.

File Functions trong WordPress là gì?

Functions hoạt động như một plugin và cho phép các nhà phát triển chủ đề xác định các tính năng của chủ đề. Người dùng cũng có thể sử dụng nó để thêm đoạn mã tùy chỉnh của họ vào WordPress.

Có thể bạn quan tâm: những đoạn code hay dùng trong lập trình theme Worpdress

Tổng hợp những Functions hay trong lập trình theme WordPress

1] Xóa số phiên bản WordPress

function wpb_remove_version() {
return '';
}
add_filter('the_generator', 'wpb_remove_version');

2] Thêm Logo bảng điều khiển tùy chỉnh

function wpb_custom_logo() {
echo '
<style type="text/css">
#wpadminbar #wp-admin-bar-wp-logo > .ab-item .ab-icon:before {
background-image: url(' . get_bloginfo('stylesheet_directory') . '/images/custom-logo.png) !important; background-position: 0 0; color:rgba(0, 0, 0, 0);
}
#wpadminbar #wp-admin-bar-wp-logo.hover > .ab-item .ab-icon {background-position: 0 0;}
</style>
';
}
//hook into the administrative header output
add_action('wp_before_admin_bar_render', 'wpb_custom_logo');

3] Thay đổi Footer trong Bảng quản trị

function remove_footer_admin () {
echo 'Design by <a href="http://www.wordpress.org" target="_blank">WordPress</a> | WordPress Tutorials: <a href="https://f4vnn.com" target="_blank">Blog tips f4vnn</a></p>';
}
add_filter('admin_footer_text', 'remove_footer_admin');

4] Thêm thông tin liên hệ bảng điều khiển tùy chỉnh

add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');
 
function my_custom_dashboard_widgets() {
global $wp_meta_boxes;
 
wp_add_dashboard_widget('custom_help_widget', 'Theme Support', 'custom_dashboard_help');
}
 
function custom_dashboard_help() {
echo '<p>Welcome to Custom Blog Theme! Need help? Contact the developer <a href="mailto:yourusername@gmail.com">here</a>. For WordPress Tutorials visit: <a href="https://f4vnn.com" target="_blank">Blog tips f4vnn</a></p>';
}

5] Thay đổi Gravatar mặc định

function wpb_custom_default_gravatar( $avatar_defaults ) {
    $myavatar = 'https://example.com/wp-content/uploads/2022/10/dummygravatar.png';
    $avatar_defaults[$myavatar] = 'Default Gravatar';
    return $avatar_defaults;
}
add_filter( 'avatar_defaults', 'wpb_custom_default_gravatar' );

6] Ngày bản quyền động trong Footer

function wpb_copyright() {
global $wpdb;
$copyright_dates = $wpdb->get_results("
SELECT
YEAR(min(post_date_gmt)) AS firstdate,
YEAR(max(post_date_gmt)) AS lastdate
FROM
$wpdb->posts
WHERE
post_status = 'publish'
");
$output = '';
if($copyright_dates) {
$copyright = "© " . $copyright_dates[0]->firstdate;
if($copyright_dates[0]->firstdate != $copyright_dates[0]->lastdate) {
$copyright .= '-' . $copyright_dates[0]->lastdate;
}
$output = $copyright;
}
return $output;
}

Sau khi thêm chức năng này, bạn sẽ cần mở tệp footer.php và thêm đoạn mã sau vào nơi bạn muốn hiển thị ngày bản quyền động:

<?php echo wpb_copyright(); ?>

7] Thêm trường hồ sơ tác giả

function wpb_new_contactmethods( $contactmethods ) {
// Add Twitter
$contactmethods['twitter'] = 'Twitter';
//add Facebook
$contactmethods['facebook'] = 'Facebook';
 
return $contactmethods;
}
add_filter('user_contactmethods','wpb_new_contactmethods',10,1);

Bây giờ bạn có thể hiển thị các trường này trong mẫu tác giả của mình như thế này:

<?php echo get_the_author_meta('twitter') ?>

8] Đăng ký Sidebars

function custom_sidebars() {
 
    $args = array(
        'id'            => 'custom_sidebar',
        'name'          => __( 'Custom Widget Area', 'text_domain' ),
        'description'   => __( 'A custom widget area', 'text_domain' ),
        'before_title'  => '<h3 class="widget-title">',
        'after_title'   => '</h3>',
        'before_widget' => '<aside id="%1$s" class="widget %2$s">',
        'after_widget'  => '</aside>',
    );
    register_sidebar( $args );
 
}
add_action( 'widgets_init', 'custom_sidebars' );

Để hiển thị Sidebars hoặc khu vực sẵn sàng cho tiện ích này trên trang web của bạn, bạn sẽ cần thêm mã sau vào mẫu mà bạn muốn hiển thị:

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('custom_sidebar') ) : ?>
<!–Default sidebar info goes here–>
<?php endif; ?>

9] Ẩn lỗi đăng nhập

function no_wordpress_errors(){
  return 'Something is wrong!';
}
add_filter( 'login_errors', 'no_wordpress_errors' );

10] Thay đổi độ dài đoạn trích

function new_excerpt_length($length) {
return 100;
}
add_filter('excerpt_length', 'new_excerpt_length');

11] Thêm người dùng quản trị

function wpb_admin_account(){
$user = 'Username';
$pass = 'Password';
$email = 'email@domain.com';
if ( !username_exists( $user )  && !email_exists( $email ) ) {
$user_id = wp_create_user( $user, $pass, $email );
$user = new WP_User( $user_id );
$user->set_role( 'administrator' );
} }
add_action('init','wpb_admin_account');

12] Hiển thị tổng số người dùng đã đăng ký

function wpb_user_count() {
$usercount = count_users();
$result = $usercount['total_users'];
return $result;
}
// Creating a shortcode to display user count
add_shortcode('user_count', 'wpb_user_count');

Bây giờ bạn chỉ cần thêm shortcode [user_count] vào bài đăng hoặc trang nơi bạn muốn hiển thị tổng số người dùng.

13] Thêm các loại file bổ sung sẽ được tải lên

function my_myme_types($mime_types){
    $mime_types['svg'] = 'image/svg+xml'; //Adding svg extension
    $mime_types['psd'] = 'image/vnd.adobe.photoshop'; //Adding photoshop files
    return $mime_types;
}
add_filter('upload_mimes', 'my_myme_types', 1, 1);

14] Thêm hộp thông tin tác giả trong bài viết

function wpb_author_info_box( $content ) {
 
global $post;
 
// Detect if it is a single post with a post author
if ( is_single() && isset( $post->post_author ) ) {
 
// Get author's display name
$display_name = get_the_author_meta( 'display_name', $post->post_author );
 
// If display name is not available then use nickname as display name
if ( empty( $display_name ) )
$display_name = get_the_author_meta( 'nickname', $post->post_author );
 
// Get author's biographical information or description
$user_description = get_the_author_meta( 'user_description', $post->post_author );
 
// Get author's website URL
$user_website = get_the_author_meta('url', $post->post_author);
 
// Get link to the author archive page
$user_posts = get_author_posts_url( get_the_author_meta( 'ID' , $post->post_author));
     
// Get User Gravatar
$user_gravatar =  get_avatar( get_the_author_meta( 'ID' , $post->post_author) , 90 );
 
if ( ! empty( $display_name ) )
 
$author_details = '<p class="author_name">About ' . $display_name . '</p>';
 
if ( ! empty( $user_description ) )
// Author avatar and bio will be displayed if author has filled in description. 
 
$author_details .= '<p class="author_details">' . $user_gravatar . nl2br( $user_description ). '</p>';
 
$author_details .= '<p class="author_links"><a href="'. $user_posts .'">View all posts by ' . $display_name . '</a>';  
 
// Check if author has a website in their profile
if ( ! empty( $user_website ) ) {
 
// Display author website link
$author_details .= ' | <a href="' . $user_website .'" target="_blank" rel="nofollow noopener">Website</a></p>';
 
} else {
// if there is no author website then just close the paragraph
$author_details .= '</p>';
}
 
// Pass all this info to post content
$content = $content . '<footer class="author_bio_section" >' . $author_details . '</footer>';
}
return $content;
}
 
// Add our function to the post content filter
add_action( 'the_content', 'wpb_author_info_box' );
 
// Allow HTML in author bio section
remove_filter('pre_user_description', 'wp_filter_kses');

Bạn có thể sử dụng CSS mẫu này làm điểm bắt đầu:

.author_bio_section{
background: none repeat scroll 0 0 #F5F5F5;
padding: 15px;
border: 1px solid #ccc;
}
 
.author_name{
font-size:16px;
font-weight: bold;
}
 
.author_details img {
border: 1px solid #D8D8D8;
border-radius: 50%;
float: left;
margin: 0 10px 10px 0;
}

Hoặc dùng đoạn code này

function wpb_author_info_box( $content ) {
global $post;
if ( is_single() && isset( $post->post_author ) ) {
$display_name = get_the_author_meta( 'display_name', $post->post_author );
if ( empty( $display_name ) )
$display_name = get_the_author_meta( 'nickname', $post->post_author );
$user_description = get_the_author_meta( 'user_description', $post->post_author );
$user_website = get_the_author_meta('url', $post->post_author);
$user_posts = get_author_posts_url( get_the_author_meta( 'ID' , $post->post_author));
$user_gravatar =  get_avatar( get_the_author_meta( 'ID' , $post->post_author) , 90 );
if ( ! empty( $display_name ) ) 
$author_details = '<p class="author_name">Giới thiệu ' . $display_name . '</p>';
if ( ! empty( $user_description ) )
$author_details .= '<p class="author_details">' . $user_gravatar . nl2br( $user_description ). '</p>';
$content = $content . '<footer class="author_bio_section" >' . $author_details . '</footer>';
}
return $content;
}
add_action( 'the_content', 'wpb_author_info_box' );
remove_filter('pre_user_description', 'wp_filter_kses');

14] Hiển thị ngày cập nhật cuối cùng

$u_time          = get_the_time( 'U' );
$u_modified_time = get_the_modified_time( 'U' );
// Only display modified date if 24hrs have passed since the post was published.
if ( $u_modified_time >= $u_time + 86400 ) {
 
    $updated_date = get_the_modified_time( 'F jS, Y' );
    $updated_time = get_the_modified_time( 'h:i a' );
 
    $updated = '<p class="last-updated">';
 
    $updated .= sprintf(
    // Translators: Placeholders get replaced with the date and time when the post was modified.
        esc_html__( 'Last updated on %1$s at %2$s' ),
        $updated_date,
        $updated_time
    );
    $updated .= '</p>';
 
    echo wp_kses_post( $updated );
}

15] Vô hiệu hóa thanh quản trị WordPress trên Frontend

add_filter( 'show_admin_bar', '__return_false' );

16] Vô hiệu hóa chỉnh sửa tệp Plugin / Theme

if ( ! defined( 'DISALLOW_FILE_EDIT' ) ) {
    define( 'DISALLOW_FILE_EDIT', true );
}

17] Thêm nút sao chép bài đăng

add_filter( 'post_row_actions', 'wpcode_snippet_duplicate_post_link', 10, 2 );
add_filter( 'page_row_actions', 'wpcode_snippet_duplicate_post_link', 10, 2 );
 
// Let's make sure the function doesn't already exist.
if ( ! function_exists( 'wpcode_snippet_duplicate_post_link' ) ) {
    /**
     * @param array   $actions The actions added as links to the admin.
     * @param WP_Post $post The post object.
     *
     * @return array
     */
    function wpcode_snippet_duplicate_post_link( $actions, $post ) {
 
        // Don't add action if the current user can't create posts of this post type.
        $post_type_object = get_post_type_object( $post->post_type );
 
        if ( null === $post_type_object || ! current_user_can( $post_type_object->cap->create_posts ) ) {
            return $actions;
        }
 
 
        $url = wp_nonce_url(
            add_query_arg(
                array(
                    'action'  => 'wpcode_snippet_duplicate_post',
                    'post_id' => $post->ID,
                ),
                'admin.php'
            ),
            'wpcode_duplicate_post_' . $post->ID,
            'wpcode_duplicate_nonce'
        );
 
        $actions['wpcode_duplicate'] = '<a href="' . $url . '" title="Duplicate item" rel="permalink">Duplicate</a>';
 
        return $actions;
    }
}
 
/**
 * Handle the custom action when clicking the button we added above.
 */
add_action( 'admin_action_wpcode_snippet_duplicate_post', function () {
 
    if ( empty( $_GET['post_id'] ) ) {
        wp_die( 'No post id set for the duplicate action.' );
    }
 
    $post_id = absint( $_GET['post_id'] );
 
    // Check the nonce specific to the post we are duplicating.
    if ( ! isset( $_GET['wpcode_duplicate_nonce'] ) || ! wp_verify_nonce( $_GET['wpcode_duplicate_nonce'], 'wpcode_duplicate_post_' . $post_id ) ) {
        // Display a message if the nonce is invalid, may it expired.
        wp_die( 'The link you followed has expired, please try again.' );
    }
 
    // Load the post we want to duplicate.
    $post = get_post( $post_id );
 
    // Create a new post data array from the post loaded.
    if ( $post ) {
        $current_user = wp_get_current_user();
        $new_post     = array(
            'comment_status' => $post->comment_status,
            'menu_order'     => $post->menu_order,
            'ping_status'    => $post->ping_status,
            'post_author'    => $current_user->ID,
            'post_content'   => $post->post_content,
            'post_excerpt'   => $post->post_excerpt,
            'post_name'      => $post->post_name,
            'post_parent'    => $post->post_parent,
            'post_password'  => $post->post_password,
            'post_status'    => 'draft',
            'post_title'     => $post->post_title . ' (copy)',// Add "(copy)" to the title.
            'post_type'      => $post->post_type,
            'to_ping'        => $post->to_ping,
        );
        // Create the new post
        $duplicate_id = wp_insert_post( $new_post );
        // Copy the taxonomy terms.
        $taxonomies = get_object_taxonomies( get_post_type( $post ) );
        if ( $taxonomies ) {
            foreach ( $taxonomies as $taxonomy ) {
                $post_terms = wp_get_object_terms( $post_id, $taxonomy, array( 'fields' => 'slugs' ) );
                wp_set_object_terms( $duplicate_id, $post_terms, $taxonomy );
            }
        }
        // Copy all the custom fields.
        $post_meta = get_post_meta( $post_id );
        if ( $post_meta ) {
 
            foreach ( $post_meta as $meta_key => $meta_values ) {
                if ( '_wp_old_slug' === $meta_key ) { // skip old slug.
                    continue;
                }
                foreach ( $meta_values as $meta_value ) {
                    add_post_meta( $duplicate_id, $meta_key, $meta_value );
                }
            }
        }
 
        // Redirect to edit the new post.
        wp_safe_redirect(
            add_query_arg(
                array(
                    'action' => 'edit',
                    'post'   => $duplicate_id
                ),
                admin_url( 'post.php' )
            )
        );
        exit;
    } else {
        wp_die( 'Error loading post for duplication, please try again.' );
    }
} );

18] Xóa bảng chào mừng khỏi bảng điều khiển quản trị viên

add_action(
    'admin_init',
    function () {
        remove_action( 'welcome_panel', 'wp_welcome_panel' );
    }
);

19] Thêm cột hình ảnh nổi bật cho bài viết trong quản trị viên

add_filter( 'manage_posts_columns', function ( $columns ) {
    // You can change this to any other position by changing 'title' to the name of the column you want to put it after.
    $move_after     = 'title';
    $move_after_key = array_search( $move_after, array_keys( $columns ), true );
 
    $first_columns = array_slice( $columns, 0, $move_after_key + 1 );
    $last_columns  = array_slice( $columns, $move_after_key + 1 );
 
    return array_merge(
        $first_columns,
        array(
            'featured_image' => __( 'Featured Image' ),
        ),
        $last_columns
    );
} );
 
add_action( 'manage_posts_custom_column', function ( $column ) {
    if ( 'featured_image' === $column ) {
        the_post_thumbnail( array( 300, 80 ) );
    }
} );

20] Chặn khu vực quản trị cho mọi người trừ quản trị viên

add_action( 'admin_init', function() {
    if ( ! current_user_can( 'administrator' ) ) {
       wp_redirect( home_url() );
       exit;
    }
} );

21] Thêm shortcode vào tiêu đề bài viết

add_filter( 'the_title', 'do_shortcode' );

Ví dụ: khi kết hợp với đoạn mã trước đó, điều này sẽ cho phép bạn tự động đưa năm hiện tại vào tiêu đề bài đăng bằng cách thêm mã ngắn [currentyear].

22] Thay đổi số lượng kết quả tìm kiếm

function f4vnn_search_results_list() {
if ( is_search() )
set_query_var('posts_per_archive_page', 12);
}

add_filter('pre_get_posts', 'f4vnn_search_results_list');

23] Thay đổi chất lượng tối ưu hóa JPEG tự động

add_filter( 'jpeg_quality', create_function( '', 'return 90;' ) );

Thay đổi số 90 thành mức chất lượng thực tế mà bạn muốn sử dụng

23] Đăng ký menu

function register_my_menus() {
  register_nav_menus(
    array(
      'header-menu' => __( 'Header Menu' ),
      'footer-menu' => __( 'Footer Menu' ),
      'sidebar-menu' => __( 'Sidebar Menu' )
     )
   );
 }
 add_action( 'init', 'register_my_menus' );

Thêm vào chỗ hiển thị

<?php
if ( has_nav_menu( 'header-menu' ) ) {
    wp_nav_menu( array( 
        'theme_location' => 'header-menu' 
    ) ); 
}
?>

24] Hủy đăng ký Widget mặc định

function unregister_default_wp_widgets() {
    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');
}
add_action('widgets_init', 'unregister_default_wp_widgets', 1);

25] Xóa thông tin thừa và HTML trong thẻ <head>

// remove unnecessary header info
add_action( 'init', 'remove_header_info' );
function remove_header_info() {
    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' );         // for WordPress < 3.0
    remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head' ); // for WordPress >= 3.0
}

// remove extra CSS that 'Recent Comments' widget injects
add_action( 'widgets_init', 'remove_recent_comments_style' );
function remove_recent_comments_style() {
    global $wp_widget_factory;
    remove_action( 'wp_head', array(
        $wp_widget_factory->widgets['WP_Widget_Recent_Comments'],
        'recent_comments_style'
    ) );
}

26] Đếm số lượng bình luận

function count_user_comments($id) {
global $wpdb;
$users = $wpdb->get_var("
        SELECT COUNT( * ) AS total
        FROM $wpdb->comments
        WHERE comment_approved = 1 
        AND user_id = $id");
return $users;
}

27] Chỉ hiển thị nội dung cụ thể cho người dùng đã đăng nhập

add_shortcode( 'userview', 'f4vnn_check_user_login' );
function f4vnn_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!";}
}

Chèn shortcode vào nơi bạn muốn hiển thị [userview] Nội dung [/userview]

28]  Lấy danh sách Taxonomy của một Post Type

<?php
function f4vnn_taxonomylist(){
    $post_type = 'pagebai';
    $taxonomies = get_object_taxonomies( (object) array( 'post_type' => $post_type ) );
    foreach( $taxonomies as $taxonomy ){
        $terms = get_terms( $taxonomy );
        foreach( $terms as $term ){ ?>
            <a href="<?php echo get_term_link($term->term_id) ?>"><?php echo $term->name; ?></a>
        <?php }
    }
}
f4vnn_taxonomylist();
?>

29] Bỏ chức năng không cần thiết trong Theme WordPress

add_action( 'after_setup_theme', function () {
  remove_theme_support( 'post-formats' );
  remove_theme_support( 'post-thumbnails' );
  remove_theme_support( 'custom-background' );
  remove_theme_support( 'custom-header' );
  remove_theme_support( 'automatic-feed-links' );
  remove_theme_support( 'html5' );
  remove_theme_support( 'title-tag' );
  remove_theme_support( 'menus' );
}, 11 );

Kết luận

Trên đây là tổng hợp những Functions hay trong lập trình theme WordPress mà bạn có thể tham khảo. Nó vẫn đang trong quá trình cập nhật thêm những cái mới, chúc bạn thành công.

Theo dõi trên

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