Archives: Snippets | Page 17

Disable the Default Lightbox in WooCommerce 3.0+

Here is a quick way to disable the Lightbox in WooCommerce 3.0 and above. Add the following code to your functions.php file:

add_action( 'after_setup_theme', 'remove_wc_gallery_lightbox', 100 );

function remove_wc_gallery_lightbox() { 
  remove_theme_support( 'wc-product-gallery-lightbox' );
}

For more WooCommerce customization, see Mastering WooCommerce Hooks.

Replace PayPal Logo in WooCommerce

If you use PayPal as a payment option on the WooCommerce checkout page, you can replace the PayPal logo displayed there. Add the following code to your theme’s functions.php file:

/**
 * Add custom gateway icons
 *
 * @param string $icon Image HTML.
 * @param string $gateway_id Gateway ID.
 *
 * @return string
 */
function sv_custom_wc_gateway_icons($icon, $gateway_id)
{
    // Example for PayPal:
    if ('paypal' == $gateway_id) {
        $icon = '<img src="' . get_stylesheet_directory_uri() . '/images/paypal.svg" alt="' . __('PayPal') . '" />';
    }
    return $icon;
}

add_filter('woocommerce_gateway_icon', 'sv_custom_wc_gateway_icons', 10, 2);

Change the path and filename to your new image and you are set!

Extend WordPress Auto Logout Period

The following code lets you extend how long it takes before WordPress automatically logs you out of the admin area. Add this code to your theme’s functions.php file:

function keep_me_logged_in_for_1_year( $expirein ) {
   return 31556926; // 1 year in seconds
}
add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for_1_year' );

For more security tips, see Hardening WordPress Security.

Restrict Admin Menu Items by Username in WordPress

You can hide specific admin menu items from a specific user in the WordPress dashboard. Replace username with the login of the user you want to hide those menu items from:

function remove_menus()
{
    global $menu;
    global $current_user;
    get_currentuserinfo();

    if($current_user->user_login == 'username')
    {
        $restricted = array(__('Posts'),
                            __('Media'),
                            __('Links'),
                            __('Pages'),
                            __('Comments'),
                            __('Appearance'),
                            __('Plugins'),
                            __('Users'),
                            __('Tools'),
                            __('Settings')
        );
        end ($menu);
        while (prev($menu)) {
            $value = explode(' ',$menu[key($menu)][0]);
            if(in_array($value[0] != NULL ? $value[0] : "" , $restricted)) {
                unset($menu[key($menu)]);
            }
        } // end while

    } // end if
}
add_action('admin_menu', 'remove_menus');

This uses a WordPress hook. Learn more in WordPress Hooks Explained.

Remove Dashboard Meta Boxes in WordPress

The following snippet lets you remove specific meta boxes from the main Dashboard page in WordPress. These are the default meta boxes shown on the main admin screen.

To remove or change which boxes are displayed, add this snippet to your theme’s functions.php file and choose which boxes to remove:

function my_custom_dashboard_widgets()
{
    global $wp_meta_boxes;

    // Main column (left):
    // Browser Update Required
    unset($wp_meta_boxes['dashboard']['normal']['high']['dashboard_browser_nag']);
    // PHP Update Required
    unset($wp_meta_boxes['dashboard']['normal']['high']['dashboard_php_nag']);
    // Right Now - Comments, Posts, Pages at a glance
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);
    // Right Now
    unset($wp_meta_boxes['dashboard']['normal']['core']['network_dashboard_right_now']);
    // Activity
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_activity']);
    // Site Health Status
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_site_health']);

    // Side Column (right):
    // WordPress Events and News
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
    // Quick Draft, Your Recent Drafts
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']);

    // Recent Comments
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']);

    // Incoming Links
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);

    // Plugins - Popular, New and Recently updated WordPress Plugins
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);

    // Other WordPress News Feed
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);


    // Recent Drafts List
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_recent_drafts']);
}

add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');

This is the page we are talking about:

Removing default meta boxes from the main Dashboard page

For safe admin customizations, see What Are Child Themes and How to Use Them.

Display All Post Types in Category Archives

If you want WordPress category archive pages to display all posts regardless of post type, add the following code to your functions.php file:

function any_ptype_on_cat($request) {

    if ( isset($request['category_name']) )
        $request['post_type'] = 'any';

    return $request;
}
add_filter('request', 'any_ptype_on_cat');

For more on custom post types, see How to Create Custom Post Types.

Unregister Default WordPress Widgets

To remove the widgets that come by default with WordPress, add the following code to your theme’s functions.php file:

// Unregister all default WordPress Widgets
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);

This uses the widgets_init action. Learn more in WordPress Hooks Explained.

Add Featured Image Column to Posts List in WordPress Admin

Want to know how to display the featured image next to each post and page when viewing the posts or pages list in the WordPress admin?

You can use a plugin for this, but it is unnecessary. Simply add the following code to your theme’s functions.php file.

function posts_columns($defaults){
    $defaults['sv_post_thumbs'] = __('Image');
    return $defaults;
}

function posts_custom_columns($column_name, $id){
    if($column_name === 'sv_post_thumbs'){
        the_post_thumbnail( 'thumbnail' );
    }
}

add_filter('manage_posts_columns', 'posts_columns', 5);
add_action('manage_posts_custom_column', 'posts_custom_columns', 5, 2);

The result will look something like this:

Adding featured image to posts column in WordPress admin

This uses WordPress hooks to add admin columns. Learn more in WordPress Hooks Explained.

Upgrade and Downgrade WordPress with WP-CLI

With WP-CLI, wp core update updates WordPress from the command line, and the --version flag lets you move to a specific version, newer or older. Use it to upgrade, pin a known release, or roll back after a bad update.

For other ways to roll back, including without shell access, see how to downgrade WordPress to a previous version.

WP-CLI Commands to Update or Downgrade WordPress

Run these from the WordPress root directory over SSH (or add --path=/path/to/wordpress). Start by checking what is installed and what is available:

# Show the installed version
wp core version

# Version plus database revision, TinyMCE version and package language
wp core version --extra

# List available updates
wp core check-update

Update to the latest version, or only to the latest minor release of your current branch:

wp core update
wp core update --minor

Update to a specific version:

wp core update --version=7.0.4

Downgrade to a specific version, or reinstall the version you already have:

wp core update --version=6.9.7 --force

Then run the database update routine:

wp core update-db

How the Flags Work

wp core update downloads the release from WordPress.org and replaces the core files. Your themes, plugins and uploads in wp-content, and wp-config.php, are not replaced.

  • --version=<version> picks the exact release instead of the latest. It also accepts nightly.
  • --force updates even when the installed version is newer than the requested one. Without it, a request for an older version changes nothing and WP-CLI only reports “WordPress is up to date.”
  • --minor stays within your current branch, for example from 7.0.2 to 7.0.4 without jumping to 7.1.
  • --locale=<locale> downloads a specific language package, such as he_IL.

After the files are replaced, WP-CLI removes core files that don’t exist in the target version when checksums for both versions are available.

wp core update-db runs the same database upgrade you would otherwise confirm in the dashboard. On multisite, use wp core update-db --network.

Downgrade WordPress Safely

A downgrade replaces the files, but it does not undo database changes a newer version has already made. Take a backup first so you can restore the exact previous state:

# Back up the database
wp db export before-downgrade.sql

# Downgrade, then verify the core files
wp core update --version=6.9.7 --force
wp core verify-checksums

wp core verify-checksums compares the installed core files with the official checksums from WordPress.org. It reports missing, modified and extra core files, so it catches an incomplete download and also flags altered core files on a hacked site.

Keep a file backup of wp-content as well, because plugins and themes that were updated for the newer version may not work on the older one.

Automatic background updates can move a downgraded site forward again.

Disable automatic WordPress updates until you are ready to upgrade, and plan to return to the latest release soon. Only the latest version of WordPress is officially supported.

FAQs

Common questions about updating WordPress with WP-CLI:

How do I update WordPress to a specific version with WP-CLI?
Run wp core update --version=7.0.4 with the version you want. If that version is older than the one installed, add --force.
Why does wp core update --version not downgrade WordPress?
WP-CLI refuses to install an older version unless you pass --force. Without it, the command changes nothing and only reports "WordPress is up to date."
Do I need to run wp core update-db after updating?
Run it after any core update. If no database changes are needed it does nothing, and if they are, it applies them without waiting for someone to open the dashboard. Use wp core update-db --network on multisite.
How do I upgrade WP-CLI itself?
Run wp cli update. It only works when WP-CLI was installed as a Phar file. If you installed it with Homebrew or another package manager, update it through that package manager.