Ready-Made WordPress Code: Instantly Solve Common Issues

|
13 mins reading time

This article compiles ready-made code snippets commonly used in WordPress, which can help solve problems for many people. Even those without coding knowledge can use them immediately by simply placing them in the functions.php file of their theme. However, don’t forget to use the code safely by testing it locally first. If you apply it directly on the production site and it causes issues, consider this a warning.

ซ่อน Admin Bar

Hide Admin Bar

add_filter('show_admin_bar', '__return_false');

Hide Admin bar for non-Admins

function hide_admin_bar_for_non_admins() {
    // ตรวจสอบว่าผู้ใช้ปัจจุบันไม่ใช่ผู้ดูแลระบบ และไม่ได้อยู่ในหน้าแอดมิน
    if (!current_user_can('administrator') && !is_admin()) {
        // ซ่อนแถบผู้ดูแลระบบ
        show_admin_bar(false);
    }
}
add_action('after_setup_theme', 'hide_admin_bar_for_non_admins');
เปลี่ยนโลโก้ที่หน้า Login page

Change the logo on the Login page

function custom_login_logo() {
    ?>
    <style type="text/css">
        #login h1 a {
            background-image: url('<?php echo get_stylesheet_directory_uri(); ?>/path/to/your/logo.png');
            height: 80px; /* ปรับความสูงตามขนาดโลโก้ */
            width: 320px; /* ปรับความกว้างตามขนาดโลโก้ */
            background-size: contain; /* ปรับขนาดโลโก้ให้อยู่ในกรอบ */
            background-repeat: no-repeat;
            padding-bottom: 30px;
        }
    </style>
    <?php
}
add_action('login_enqueue_scripts', 'custom_login_logo');

Set the length of the Excerpt

// ฟังก์ชันกำหนดความยาวของ excerpt แบบนับตัวอักษรภาษาไทย
function custom_excerpt_length_in_chars($text, $length = 100) {
    if (mb_strlen($text) > $length) {
        $text = mb_substr($text, 0, $length) . '...';
    }
    return $text;
}

// ฟิลเตอร์สำหรับใช้ฟังก์ชันกำหนดความยาวของ excerpt แบบนับตัวอักษร
function apply_custom_excerpt_length($excerpt) {
    return custom_excerpt_length_in_chars($excerpt, 100); // เปลี่ยนตัวเลข 100 เป็นจำนวนตัวอักษรที่ต้องการ
}
add_filter('the_excerpt', 'apply_custom_excerpt_length');
ตัดคำ Tag: Category: Archive: Author: นำหน้าออกในหน้า Taxonomy

Remove the prefix Tag:, Category:, Archive:, Author: from the Taxonomy pages

// ฟังก์ชันเพื่อตัดคำนำหน้าพวก "Tag:", "Archive:", "Category:" ออกจากหัวเรื่อง
function custom_archive_title($title) {
    if (is_category()) {
        $title = single_cat_title('', false);
    } elseif (is_tag()) {
        $title = single_tag_title('', false);
    } elseif (is_post_type_archive()) {
        $title = post_type_archive_title('', false);
    } elseif (is_tax()) {
        $title = single_term_title('', false);
    }

    return $title;
}
add_filter('get_the_archive_title', 'custom_archive_title');

Disable Gutenberg

add_filter('use_block_editor_for_post', '__return_false', 10);

Set the desired page to redirect to after login

// เปลี่ยน URL ของโลโก้ในหน้าเข้าสู่ระบบ
function custom_login_logo_url() {
    return home_url(); // เปลี่ยนเป็น URL ของเว็บไซต์คุณ
}
add_filter('login_headerurl', 'custom_login_logo_url');

Set the desired page to redirect to after logout

function custom_logout_redirect() {
    return home_url();
}
add_filter('logout_redirect', 'custom_logout_redirect');

Add inline CSS to the admin area

// เพิ่ม CSS แบบกำหนดเองในแผงควบคุม Admin
function custom_admin_css() {
    echo '<style>
        /* Custom CSS ที่ต้องการ */
        #wpadminbar { background-color: #23282d; }
        .wp-admin #wpwrap { background-color: #f1f1f1; }
    </style>';
}
add_action('admin_head', 'custom_admin_css');

Disable REST API for non-logged-in users

add_filter('rest_authentication_errors', function($result) {
    if (!empty($result)) {
        return $result;
    }
    if (!is_user_logged_in()) {
        return new WP_Error('rest_not_logged_in', 'You are not currently logged in.', array('status' => 401));
    }
    return $result;
});

Disable all feeds

function disable_feeds() {
    wp_die(__('No feed available, please visit our <a href="'. esc_url(home_url('/')) .'">homepage</a>!'));
}
add_action('do_feed', 'disable_feeds', 1);
add_action('do_feed_rdf', 'disable_feeds', 1);
add_action('do_feed_rss', 'disable_feeds', 1);
add_action('do_feed_rss2', 'disable_feeds', 1);
add_action('do_feed_atom', 'disable_feeds', 1);
add_action('do_feed_rss2_comments', 'disable_feeds', 1);
add_action('do_feed_atom_comments', 'disable_feeds', 1);
เพิ่มปุ่มกลับไปด้านบน

Add a "Back to Top" button

function add_back_to_top_button() { ?>
    <!-- Back to Top button element -->
    <a id="back-to-top" href="#" style="display: none; position: fixed; bottom: 20px; right: 20px; z-index: 100;">⇧</a>
    <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', function() {
            // Function to show/hide the Back to Top button
            window.addEventListener('scroll', function() {
                if (window.scrollY > 100) {
                    document.getElementById('back-to-top').style.display = 'block';
                } else {
                    document.getElementById('back-to-top').style.display = 'none';
                }
            });
            
            // Function to scroll to the top when the button is clicked
            document.getElementById('back-to-top').addEventListener('click', function(event) {
                event.preventDefault();
                window.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            });
        });
    </script>
<?php }
add_action('wp_footer', 'add_back_to_top_button');

Disable comments

Some theme have to delete file in template too.

// ปิดการใช้งานฟังก์ชันความคิดเห็นสำหรับโพสต์ทั้งหมด
function disable_comments_post_types_support() {
    $post_types = get_post_types();
    foreach ($post_types as $post_type) {
        if (post_type_supports($post_type, 'comments')) {
            remove_post_type_support($post_type, 'comments');
            remove_post_type_support($post_type, 'trackbacks');
        }
    }
}
add_action('admin_init', 'disable_comments_post_types_support');

// ปิดการใช้งานเมนูความคิดเห็นในแผงควบคุม
function disable_comments_admin_menu() {
    remove_menu_page('edit-comments.php');
}
add_action('admin_menu', 'disable_comments_admin_menu');

// ปิดการใช้งาน Widget ความคิดเห็นในแผงควบคุม
function disable_comments_dashboard() {
    remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');
}
add_action('admin_init', 'disable_comments_dashboard');

// ปิดการใช้งาน Meta Box ความคิดเห็นในหน้าโพสต์
function disable_comments_post_meta_box() {
    remove_meta_box('commentstatusdiv', 'post', 'normal');
    remove_meta_box('commentsdiv', 'post', 'normal');
}
add_action('admin_menu', 'disable_comments_post_meta_box');

// ปิดการใช้งานฟังก์ชันความคิดเห็นในหน้า
function disable_comments_status() {
    return false;
}
add_filter('comments_open', 'disable_comments_status', 20, 2);
add_filter('pings_open', 'disable_comments_status', 20, 2);

// ซ่อนฟิลด์ความคิดเห็นในหน้า
function disable_comments_hide_existing_comments($comments) {
    $comments = array();
    return $comments;
}
add_filter('comments_array', 'disable_comments_hide_existing_comments', 10, 2);

// ปิดการใช้งาน RSS Feed ของความคิดเห็น
function disable_comments_feed() {
    wp_die(__('No feed available, please visit our <a href="'. esc_url(home_url('/')) .'">homepage</a>!'));
}
add_action('do_feed_rss2_comments', 'disable_comments_feed', 1);
add_action('do_feed_atom_comments', 'disable_comments_feed', 1);

// ลบฟังก์ชันความคิดเห็นออกจากแถบ Admin Bar
function disable_comments_admin_bar() {
    if (is_admin_bar_showing()) {
        remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
    }
}
add_action('init', 'disable_comments_admin_bar');

Disable XML-RPC

add_filter('xmlrpc_enabled', '__return_false');

Disable self pingbacks

function disable_self_pingbacks(&$links) {
    foreach ($links as $l => $link) {
        if (0 === strpos($link, home_url())) {
            unset($links[$l]);
        }
    }
}
add_action('pre_ping', 'disable_self_pingbacks');

Install Google Analytic

function add_google_analytics() { ?>
    <script async src="https://www.googletagmanager.com/gtag/js?id=YOUR_TRACKING_ID"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'YOUR_TRACKING_ID');
    </script>
<?php }
add_action('wp_head', 'add_google_analytics');

Limit search results to display only Post and Page types

function custom_search_results($query) {
    if ($query->is_search && !is_admin()) {
        $query->set('post_type', array('post', 'page')); // จำกัดการค้นหาเฉพาะโพสต์และเพจ
    }
    return $query;
}
add_filter('pre_get_posts', 'custom_search_results');

Restrict access to the Dashboard for non-Admin users

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

Remove specific items from the Admin Bar: WordPress logo, Updates, and Add New content

function remove_admin_bar_items() {
    global $wp_admin_bar;
    $wp_admin_bar->remove_node('wp-logo'); // ลบโลโก้ WordPress
    $wp_admin_bar->remove_node('updates'); // ลบการอัปเดต
    $wp_admin_bar->remove_node('new-content'); // ลบเมนูเนื้อหาใหม่
}
add_action('wp_before_admin_bar_render', 'remove_admin_bar_items');
เพิ่มลิงก์ในแถบ Admin Bar ( ใช้เพื่อเป็นเมนูลัด )

Add a link to the Admin Bar (use as a shortcut menu)

function modify_admin_bar() {
    global $wp_admin_bar;
    $wp_admin_bar->add_menu(array(
        'id' => 'custom_link',
        'title' => __('Custom Link'),
        'href' => 'http://www.example.com'
    ));
}
add_action('wp_before_admin_bar_render', 'modify_admin_bar');

Disable automatic updates

add_filter('automatic_updater_disabled', '__return_true');
add_filter('auto_update_core', '__return_false');
add_filter('auto_update_plugin', '__return_false');
add_filter('auto_update_theme', '__return_false');

Set the uploaded media to be visible only to yourself, except for the administrators.

// Restrict media library
function restrict_media_library($wp_query_obj)
{
  global $current_user, $pagenow;
  if (!is_a($current_user, 'WP_User'))
    return;
  if ('admin-ajax.php' != $pagenow || $_REQUEST['action'] != 'query-attachments')
    return;
  if (!current_user_can('manage_options'))
    $wp_query_obj->set('author', $current_user->ID);
  return;
}
add_action('pre_get_posts', 'restrict_media_library');

Set the maximum upload file size to 1MB

function custom_upload_size_limit($size)
{
	// ตรวจสอบว่าเป็นแอดมินหรือไม่
	if (!current_user_can('administrator')) {
		// กำหนดขนาดไฟล์สูงสุดที่ต้องการในหน่วยไบต์ (เช่น 1MB)
		$size = 1 * 1024 * 1024; // 1MB
	}
	return $size;
}

add_filter('upload_size_limit', 'custom_upload_size_limit');
code snippet

Guide to Using the Code Snippets Plugin

If it's not convenient to edit the functions.php file, you can use the Code Snippets plugin to add the code instead. You can follow these steps to do so.

  • Add New
  • Set a name snippet
  • Insert into Code
  • Select the position where the code runs
  • Click Save Changes and Activate

Edit the functions.php File in the Theme

If you're not writing your own theme, be cautious when editing the functions.php file. If the theme gets updated, the code you modified might be overwritten. Therefore, if you want to add code, make sure to edit the Child theme instead.


The provided code snippets are only minor adjustments or fixes for WordPress. If you want to dive deeper, you can read the article “Path to Becoming a Professional WordPress Theme Developer” for more information. Or, if you're looking for WordPress experts, feel free to contact us here. If you enjoyed this article, please like and share our page do action.

Designil PDPA Banner Thai Woo AIO Banner

author - aum watcharapon
Aum Watcharapon
👨🏻‍💻 WordPress Expertiser

Subscribe to newsletter

doaction will send notifications when new articles are available on the website, and you can unsubscribe at any time.

More Articles

Navigating Your Path to Becoming an Expert WordPress Theme Developer

This article will guide you through becoming a WordPress Theme Developer and what to learn to get started. It explores an alternative for those using website builders like Elementor and dives into what it takes to write your own themes.

Read more

WordPress Best Practices: Essential Dos and Don'ts

Developing and maintaining a WordPress website involves several factors to ensure optimal performance and security. Choosing the right themes and plugins, as well as regularly updating the WordPress core and plugins, is crucial. Additionally, regular backups and selecting quality hosting can help the site run smoothly. Learning basic coding and resizing images before uploading can enhance website efficiency. Using caching systems and customizing wp-login.php are other methods to boost speed and security. Compliance with PDPA laws to protect user data is also essential. Conversely, there are actions to avoid, such as directly editing theme files, using pirated themes or plugins, and using copyrighted images without permission. Minifying and combining JavaScript files using caching plugins can sometimes cause issues. Relying too much on plugins is not ideal, and it's better to avoid letting the server handle image resizing. Also, remember to delete unused plugins or themes to reduce system load and enhance security. This article will help you understand the correct methods for customizing and maintaining your WordPress website to ensure it operates efficiently, securely, and with quality in the long term. All these topics are gathered from my personal experience with WordPress, not only to ensure web security but also to make the site lean, small, and fast-loading, and to understand the correct methods for customizing your own WordPress site. When selecting a theme for WordPress, there are several considerations. First, choose a theme that is regularly updated. [...]

Read more

If you have any questions or need advice about WordPress, feel free to ask.

Office

  • do action co., ltd.
    66 Soi Petchkasem 98/1, Petchkasem Road,
    Bangkhae Nuea, Bangkhae,
    Bangkok, Thailand
    10160
PDPA Icon

Our website uses cookies to enhance your user experience.

Privacy Preferences

คุณสามารถเลือกการตั้งค่าคุกกี้โดยเปิด/ปิด คุกกี้ในแต่ละประเภทได้ตามความต้องการ ยกเว้น คุกกี้ที่จำเป็น

Allow All
Manage Consent Preferences
  • Always Active

Save