Mastering WordPress: 20 Essential Codes for WordPress Developers

WordPress, renowned for its flexibility and extensibility, offers a plethora of predefined functions that simplify the development process. In this comprehensive guide, we’ve compiled 20 essential WordPress codes to empower developers in various scenarios. This curated collection serves as a quick reference, ensuring that you can easily access and utilize these codes whenever needed during your WordPress development projects.

1. Get all users with the role ‘Administrator’

<?php
$user_query = new WP_User_Query( array( 'role' => 'Administrator' ) );
if ( ! empty( $user_query->results ) ) {
    foreach ( $user_query->results as $user ) {
        echo '<p>' . $user->display_name . '</p>'; // Display the name of users with the 'Administrator' role
    }
} else {
    echo 'No users found.';
}
?>

Explanation:

This code snippet uses WP_User_Query to fetch and display all users with the ‘Administrator’ role. It’s handy for scenarios where you need to list administrators on your WordPress site.

2. Display only authors

$user_query = new WP_User_Query( array( 'who' => 'authors' ) );
if ( ! empty( $user_query->results ) ) {
    foreach ( $user_query->results as $user ) {
        echo '<p>' . $user->display_name . '</p>'; // Display the name of users with the 'Author' role
    }
} else {
    echo 'No users found.';
}

Explanation: This code snippet fetches and displays users with the ‘Author’ role. It’s useful when you want to showcase authors specifically on your WordPress site.

3. Disable plugin updates for a specific plugin only

Way 1: Add this code in your plugin root file

add_filter('site_transient_update_plugins', 'remove_update_notification');
function remove_update_notification($value) {
    unset($value->response[ plugin_basename(__FILE__) ]);
    return $value;
}

Way 2: Adding code to theme’s functions.php

function my_filter_plugin_updates( $value ) {
    if( isset( $value->response['wp-faker/wp-faker.php'] ) ) {        
        unset( $value->response['wp-faker/wp-faker.php'] );
    }
    return $value;
}
add_filter( 'site_transient_update_plugins', 'my_filter_plugin_updates' );

Explanation: These snippets prevent updates for a specific plugin. Choose the method that suits your project, either by modifying the plugin’s root file or using the theme’s functions.php.

4. Show errors

Scenario 1: Show errors on a specific page

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Scenario 2: Show errors globally on all WordPress pages

define( 'WP_DEBUG', true );

Explanation: Enable error display for debugging. Use the first snippet on specific pages or the second to show errors globally across your WordPress site.

5. Retrieve posts with a specific category

$args = array(
    'category_name' => 'your-category-slug',
    'posts_per_page' => 5,
);

$posts = new WP_Query( $args );

if ( $posts->have_posts() ) {
    while ( $posts->have_posts() ) {
        $posts->the_post();
        the_title();
        // Additional post content can be displayed here
    }
} else {
    echo 'No posts found.';
}

wp_reset_postdata(); // Reset post data after the loop

Explanation: Fetch and display posts from a specific category using WP_Query. Modify the category slug and adjust the loop content as needed.

6. Customise excerpt length

function custom_excerpt_length( $length ) {
    return 20; // Adjust the number of words in the excerpt
}
add_filter( 'excerpt_length', 'custom_excerpt_length' );

Explanation: Modify the length of post excerpts by adjusting the number of words returned in the custom_excerpt_length function.

7. Redirect users after login

function custom_login_redirect( $redirect_to, $request, $user ) {
    if ( isset( $user->roles ) && is_array( $user->roles ) ) {
        if ( in_array( 'administrator', $user->roles ) ) {
            return home_url( '/admin-dashboard' ); // Adjust the redirect URL for administrators
        } else {
            return home_url(); // Default redirect URL for other user roles
        }
    } else {
        return $redirect_to; // Default redirect if roles are not available
    }
}
add_filter( 'login_redirect', 'custom_login_redirect', 10, 3 );

Explanation: Customize user redirection after login based on their roles. Redirect administrators to ‘/admin-dashboard’ and others to the default home URL.

8. Remove WordPress version number

remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'rsd_link');

Explanation: Improve security by removing WordPress version information from the site’s head. This makes it less predictable for potential attackers.

9. Display the current post’s categories

<?php
$categories = get_the_category();
foreach ( $categories as $category ) {
    echo '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '">' . esc_html( $category->name ) . '</a> ';
}
?>

Explanation: Display the categories of the current post. Useful when you want to showcase the post’s categories within its content.

10. Exclude specific categories from the main loop

<?php
$args = array(
    'category__not_in' => array( 1, 2, 3 ), // Adjust category IDs to exclude
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        // Display post content here
    }
}
wp_reset_postdata(); // Reset post data after the loop
?>

Explanation: Exclude specific categories from the main loop using WP_Query. Customize by adjusting the category IDs in the array.

11. Add a custom logo to the WordPress login page

function custom_login_logo() {
    echo '<style type="text/css">
        h1 a { background-image: url(' . get_template_directory_uri() . '/images/custom-login-logo.png) !important; }
    </style>';
}
add_action('login_head', 'custom_login_logo');

Explanation: Enhance branding by adding a custom logo to the WordPress login page. Replace ‘custom-login-logo.png’ with your image file.

12. Enable shortcodes in widgets

add_filter('widget_text','do_shortcode');

Explanation: Enable the execution of shortcodes within widgets, providing more flexibility in widget content.

13. Disable WordPress emoji script

remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');

Explanation: Improve site performance by disabling the unnecessary emoji script in the site’s head.

14. Set a custom excerpt for a post

function custom_excerpt($length) {
    return get_the_excerpt();
}
add_filter('excerpt_length', 'custom_excerpt');

Explanation: Override the default excerpt with the full post content. Useful when you want to display the entire post content in excerpts.

15. Add custom fields to user profile

function custom_user_profile_fields($user) {
    ?>
    <h3><?php _e('Custom User Fields', 'your_text_domain'); ?></h3>
    <table class="form-table">
        <tr>
            <th><label for="custom_field"><?php _e('Custom Field', 'your_text_domain'); ?></label></th>
            <td>
                <input type="text" name="custom_field" id="custom_field" value="<?php echo esc_attr(get_the_author_meta('custom_field', $user->ID)); ?>" class="regular-text" />
            </td>
        </tr>
    </table>
    <?php
}
add_action('show_user_profile', 'custom_user_profile_fields');
add_action('edit_user_profile', 'custom_user_profile_fields');

function save_custom_user_profile_fields($user_id) {
    if (current_user_can('edit_user', $user_id)) {
        update_user_meta($user_id, 'custom_field', $_POST['custom_field']);
    }
}
add_action('personal_options_update', 'save_custom_user_profile_fields');
add_action('edit_user_profile_update', 'save_custom_user_profile_fields');

Explanation: This code adds a custom field to the user profile page, allowing the storage of additional information for each user.

16. Disable the WordPress admin bar for non-admins

if (!current_user_can('administrator')) {
    add_filter('show_admin_bar', '__return_false');
}

Explanation: Hide the WordPress admin bar for non-administrative users, providing a cleaner interface for non-admins.

17. Change the default sender name and email address for emails

function custom_wp_mail_from($original_email_address) {
    return 'your_email@example.com';
}
function custom_wp_mail_from_name($original_email_from) {
    return 'Your Name';
}
add_filter('wp_mail_from', 'custom_wp_mail_from');
add_filter('wp_mail_from_name', 'custom_wp_mail_from_name');

Explanation: Customize the sender name and email address for outgoing WordPress emails, ensuring a professional and branded appearance.

18. Disable the WordPress REST API

add_filter('rest_enabled', '__return_false');
add_filter('rest_jsonp_enabled', '__return_false');

Explanation: If you don’t need the WordPress REST API, these filters can be used to disable it and improve security.

19. Customize the login page URL

function custom_login_url() {
    return home_url('/custom-login-url');
}
add_filter('login_url', 'custom_login_url');

Explanation: Change the default WordPress login page URL to enhance security by making it less predictable.

20. Limit post revisions

define('WP_POST_REVISIONS', 5); // Change the number to limit revisions

Explanation: Limit the number of post revisions stored in the database, optimising performance and database size.

These 20 WordPress code snippets form a valuable toolkit for developers, addressing common tasks efficiently. Feel free to integrate, modify, and explore these codes in your projects, enhancing your WordPress development journey.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *