Archives: Snippets | Page 18

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.

Style the ACF Admin Interface

Here is how to add CSS to the ACF admin interface. In this case, we made Repeater Fields have clearer separation. Several other changes were made to improve the interface readability:

function my_acf_admin_head() {	?>
    <style type="text/css">

        .acf-flexible-content .layout .acf-fc-layout-handle {
            background-color: #202428;
            color: #eee;
        }

        .acf-repeater.-row > table > tbody > tr > td,
        .acf-repeater.-block > table > tbody > tr > td {
            border-top: 2px solid #202428;
        }

        .acf-repeater .acf-row-handle {
            vertical-align: top !important;
            padding-top: 16px;
        }

        .acf-repeater .acf-row-handle span {
            font-size: 20px;
            font-weight: bold;
            color: #202428;
        }

        .imageUpload img {
            width: 75px;
        }

        .acf-repeater .acf-row-handle .acf-icon.-minus {
            top: 30px;
        }

    </style>
t<?php
}

add_action( 'acf/input/admin_head', 'my_acf_admin_head' );

And here is the result for the Repeater. Notice the separator line?

Making the Repeater have clearer styling

Add CSS to WooCommerce Emails

To change the styling of emails that WooCommerce sends, you can add inline CSS using the woocommerce_email_header hook. Add the following code to your functions.php file:

<?php
/**
 * WooCommerce
 * Add inline CSS to emails sent out
 */
function sv_add_css_to_woo_email() {
    echo '<style type="text/css">
             h1 {
                 text-align: center !important;
                 color: #DDD;
             }
         </style></pre>'; 
}
add_action( 'woocommerce_email_header', 'sv_add_css_to_woo_email' );

For more WooCommerce email customization, see Mastering WooCommerce Hooks.

Change the Breadcrumb Delimiter in WooCommerce

To change the breadcrumb delimiter in WooCommerce, filter the delimiter key of woocommerce_breadcrumb_defaults. By default WooCommerce prints a slash with a non-breaking space on each side.

For every other argument (wrap_before, wrap_after, before, after and home) with real examples, see Customize WooCommerce Breadcrumbs.

Replace the Breadcrumb Delimiter

Add this to your child theme’s functions.php file or to a small custom plugin:

/**
 * Replace the WooCommerce breadcrumb delimiter with a vertical bar.
 */
function savvy_wc_breadcrumb_delimiter( $defaults ) {
    $defaults['delimiter'] = '&nbsp;&#124;&nbsp;';
    return $defaults;
}
add_filter( 'woocommerce_breadcrumb_defaults', 'savvy_wc_breadcrumb_delimiter', 20 );

A product breadcrumb now reads Home | Clothing | T-Shirt instead of Home / Clothing / T-Shirt.

How It Works

The function woocommerce_breadcrumb() builds an array of defaults and passes it through the woocommerce_breadcrumb_defaults filter. The template global/breadcrumb.php then echoes the delimiter between crumbs, but not after the last one.

These are the defaults in current WooCommerce source (includes/wc-template-functions.php):

array(
    'delimiter'   => '&nbsp;&#47;&nbsp;',
    'wrap_before' => '<nav class="woocommerce-breadcrumb" aria-label="Breadcrumb">',
    'wrap_after'  => '</nav>',
    'before'      => '',
    'after'       => '',
    'home'        => _x( 'Home', 'breadcrumb', 'woocommerce' ),
)

Only change the delimiter key and return the rest untouched. Returning a brand new array wipes out defaults you did not mean to change, such as the aria-label WooCommerce added to wrap_before in version 8.3.

Delimiter Variations

The delimiter is printed as raw HTML, not escaped, so you can use entities, a styled element or an inline SVG. A few common choices:

// Right-pointing angle: Home › Shop › Product
$defaults['delimiter'] = ' &rsaquo; ';

// Arrow: Home → Shop → Product
$defaults['delimiter'] = ' &rarr; ';

// A span you can style with CSS
$defaults['delimiter'] = '<span class="breadcrumb-sep" aria-hidden="true">/</span>';

The span version is the most flexible. Add aria-hidden="true" so screen readers skip the decorative character, then style .breadcrumb-sep in your theme CSS.

Why the Delimiter Does Not Change

If the separator stays the same after adding the filter, the cause is usually one of these:

  • Storefront or another theme sets its own delimiter. Storefront hooks woocommerce_breadcrumb_defaults at the default priority 10 from the parent theme, which loads after your child theme. That is why the snippet above uses priority 20.
  • The breadcrumb is not WooCommerce’s. Yoast SEO, Rank Math and many themes print their own trail, which this filter does not touch.
  • A page cache is serving old HTML. Purge the cache and reload.

In block themes the Store Breadcrumbs block calls woocommerce_breadcrumb() internally, so the same filter applies there. To hide the trail on some pages instead, see Remove WooCommerce Breadcrumbs on Specific Pages.

FAQs

Common questions about the WooCommerce breadcrumb delimiter:

What is the default WooCommerce breadcrumb delimiter?
It is &nbsp;&#47;&nbsp;, a forward slash with a non-breaking space on each side. It is set in woocommerce_breadcrumb() and can be changed through the woocommerce_breadcrumb_defaults filter.
Can I use HTML or an icon as the delimiter?
Yes. The breadcrumb template echoes the delimiter without escaping, so a <span>, an icon font element or an inline SVG all work. Mark decorative separators with aria-hidden="true".
Why does my delimiter change not work in Storefront?
Storefront sets its own delimiter on the same filter at priority 10, and the parent theme loads after the child theme. Register your filter with a higher priority, such as 20, so it runs last.
Does changing the delimiter affect breadcrumb schema?
No. WooCommerce builds its BreadcrumbList structured data from the crumbs array, not from the rendered HTML, so the separator has no effect on schema.

Enable Excerpt Support for Pages in WordPress

WordPress lets you create an excerpt for posts by entering text in the excerpt box on the post edit screen. But excerpts are not available for pages, and there is no way to enable this through the WordPress admin.

If you want to add the excerpt box for pages too, add the following code to your theme’s functions.php file:

<?php

// START COPY FROM HERE
function add_excerpt_pages() {
    add_post_type_support('page', 'excerpt');
}
add_action('init', 'add_excerpt_pages');

 

After adding the code, edit a page and click “Screen options” in the top-left corner of the screen.

How to enable excerpt for pages in WordPress

How to enable excerpt for pages in WordPress

Check the Excerpt box and you are done. You will now see an excerpt box for all pages on your site…

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

Change Number of Products Per Page in WooCommerce

Use the following code to change the number of products WooCommerce displays per page. For this to work, make sure the “Products per page” option is selected in Customizer.

Changing the number of products displayed per page

Add this code to your theme’s functions.php file:

/**
 * Change number of products that are displayed per page (shop page)
 */
add_filter( 'loop_shop_per_page', 'new_loop_shop_per_page', 20 );

function new_loop_shop_per_page( $cols ) {
  // $cols contains the current number of products per page based on the value stored on Options –> Reading
  // Return the number of products you wanna show per page.
  $cols = 9;
  return $cols;
}

For more WooCommerce customization, see Mastering WooCommerce Hooks.

Completely Disable Search in WordPress

To completely disable WordPress search, add the following code to your theme’s functions.php file:

<?php function sv_filter_query($query, $error = true) {
    if (is_search()) {
        $query->is_search = false;
        $query->query_vars[s] = false;
        $query->query[s] = false;
        if ($error == true)
            $query->is_404 = true;
    }
}

add_action('parse_query', 'sv_filter_query');
add_filter('get_search_form', create_function('$a', "return null;"));
    
function remove_search_widget() {
    unregister_widget('WP_Widget_Search');
}

add_action('widgets_init', 'remove_search_widget');

Limit WordPress Search to Specific Post Types

Ever wondered how to limit search results to a specific Custom Post Type? It is simple. We have already seen how to completely disable WordPress search by modifying functions.php. Now we will do something similar to filter our search results.

Add the following code to your functions.php file:

function sv_search_filter($query) {
 
    if ($query->is_search && !is_admin() ) {
        $query->set('post_type',array('post','page'));
    }
 
return $query;
}
 
add_filter('pre_get_posts','sv_search_filter');

Note this line:

$query->set('post_type',array('post','page'));

You can filter search results by changing the values in that array. Search results will now show only pages and posts, but you can change this array to include any post type you want.