Archives: Snippets | Page 16

Add Custom User Profile Fields in WordPress

Add the following code to your functions.php file to add your own fields to the user profile page in the WordPress admin.


// CUSTOM USER PROFILE FIELDS
function my_custom_userfields( $contactMethods ) {

    // ADD CONTACT CUSTOM FIELDS
    $contactMethods['contact_phone_office']     = 'Office Phone';
    $contactMethods['contact_phone_mobile']     = 'Mobile Phone';
    $contactMethods['contact_office_fax']       = 'Office Fax';

    // ADD ADDRESS CUSTOM FIELDS
    $contactMethods['address_line_1']       = 'Address Line 1';
    $contactMethods['address_line_2']       = 'Address Line 2 (optional)';
    $contactMethods['address_city']         = 'City';
    $contactMethods['address_state']        = 'State';
    $contactMethods['address_zipcode']      = 'Zipcode';
}
add_filter('user_contactmethods','my_custom_userfields',10,1);

To display these fields you can use one of the following methods:

the_author_meta('facebook', $current_author->ID)
<?php $current_author = get_userdata(get_query_var('author')); ?>
<p><a href="<?php echo esc_url($current_author->contact_phone_office);?>" title="office_phone"> Office Phone</a></p>

For a more robust approach to custom fields, see Beginner’s Guide to Advanced Custom Fields.

Add a Custom Dashboard Widget in WordPress

The following code adds a new widget to the WordPress Dashboard. You can of course set what content appears in this widget. Add this code to your theme’s functions.php file:


add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');

function my_custom_dashboard_widgets() {
    wp_add_dashboard_widget('custom_help_widget', 'Help and Support', 'custom_dashboard_help');
}

function custom_dashboard_help() {
    echo '&lt;p&gt;Lorum ipsum delor sit amet et nunc&lt;/p&gt;';
}

It looks like this:

Adding a new widget to the WordPress Dashboard

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

Delay RSS Feed Publishing in WordPress

I want to delay publishing to the RSS feed by 10-15 minutes because I always find a few errors after publishing. Another scenario is when you want your site content to be exclusive for a while and not appear in the RSS feed.

// Delay feed update
function publish_later_on_feed($where) {
    global $wpdb;

    if (is_feed()) {
        // Timestamp in WordPress format
        $now = gmdate('Y-m-d H:i:s');

        // Value for wait; + device
        $wait = '10'; // integer

        // http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_timestampdiff
        $device = 'MINUTE'; // MINUTE, HOUR, DAY, WEEK, MONTH, YEAR

        // Add SQL syntax to default $where
        $where .= " AND TIMESTAMPDIFF($device, $wpdb->posts.post_date_gmt, '$now') > $wait ";
    }
    return $where;
}
add_filter('posts_where', 'publish_later_on_feed');

For more RSS management, see Disable RSS Feeds in WordPress.

Add Custom Post Types to the Main RSS Feed

To add Custom Post Types to the site’s main RSS feed by default, add the following code to your theme’s functions.php file:

// ADD CUSTOM POST TYPES TO THE DEFAULT RSS FEED
function custom_feed_request( $vars ) {
 if (isset($vars['feed']) && !isset($vars['post_type']))
  $vars['post_type'] = array( 'post', 'site', 'plugin', 'theme', 'person' );
 return $vars;
}
add_filter( 'request', 'custom_feed_request' );

Remove Width and Height Attributes from Images

When you upload an image using WordPress media and then insert it into the content editor, the image is attached with width and height attributes. These attributes are generally desirable because they help the browser reserve the right space for the image during layout.

But if you want to prevent WordPress from adding these width and height attributes, add the following code to your theme’s functions.php file:

add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );

function remove_width_attribute( $html ) {
   $html = preg_replace( '/(width|height)="d*"s/', "", $html );
   return $html;
}

Redirect to Specific URL on Coupon Removal in WooCommerce

Here is a simple way to redirect a user to a specific page when they remove a WooCommerce coupon from the cart page. Useful for example if you want to show content to users who remove a coupon that was automatically added to the cart. Here is how:

/*
 * Redirects user to a specific page upon coupon removal.
 */
function action_woocommerce_removed_coupon( $coupon_code ) { 
    // Redirection...
    wp_redirect( $url ); // Replace $url by your page URL.
    exit; 
}; 

// add the action 
add_action( 'woocommerce_removed_coupon', 'action_woocommerce_removed_coupon', 10, 1 );

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.

Hide Scrollbars While Allowing Scrolling with CSS

To hide a scrollbar with CSS while keeping the element scrollable, use scrollbar-width: none plus a ::-webkit-scrollbar fallback. Users can still scroll with a mouse wheel, trackpad, touch or keyboard, but no scrollbar is drawn.

This is common for horizontal carousels, tab bars and chat panels where the scrollbar looks out of place. If you want to restyle the scrollbar rather than remove it, see Style Scrollbars Using CSS.

CSS to Hide the Scrollbar but Allow Scrolling

Add this to your stylesheet and replace .element with the class of the scrolling container:

.element {
    overflow: auto;
    scrollbar-width: none;     /* Firefox, Chrome and Edge 121+, Safari 18.2+ */
    -ms-overflow-style: none;  /* Internet Explorer and legacy Edge */
}

.element::-webkit-scrollbar {
    display: none;             /* Older Chrome, Edge and Safari */
}

To hide the scrollbar of the whole page, target the html element:

html {
    scrollbar-width: none;
    -ms-overflow-style: none;
}

html::-webkit-scrollbar {
    display: none;
}

How It Works

The scrollbar is hidden, but the element is still a scroll container, so scrolling keeps working. Each rule covers a different set of browsers:

  • scrollbar-width: none is the standard property. It is supported in Firefox 64+, Chrome and Edge 121+, and Safari 18.2+, and has been Baseline since December 2024.
  • ::-webkit-scrollbar is a non-standard pseudo-element for Chromium and WebKit browsers. It covers older Chrome and Safari versions that don’t support scrollbar-width.
  • -ms-overflow-style: none only matters for Internet Explorer 10 and 11 and the old EdgeHTML-based Edge. You can drop it if you don’t support those.

overflow: auto is there to make the element scrollable in the first place. Use overflow-x or overflow-y if you only want one direction.

Why display: none Instead of width: 0

Many snippets set width: 0; height: 0 on ::-webkit-scrollbar. On iOS, Safari 13 and later ignores every style on that pseudo-element except display: none, so display: none is the safer choice.

Chrome and Edge 121+ also ignore ::-webkit-scrollbar on any element where scrollbar-width or scrollbar-color is set to something other than auto. That is fine here, since both rules hide the scrollbar.

It matters if you use scrollbar-width: thin and expect your ::-webkit-scrollbar styles to apply as well.

Avoid an unscoped ::-webkit-scrollbar { display: none; } rule without a selector. It hides scrollbars on every element on the site, including textareas and code blocks.

Accessibility: Give Users Another Cue

A hidden scrollbar is also a hidden hint that there is more content, and users without a wheel or touchpad can get stuck.

MDN recommends avoiding scrollbar-width: none, because content can become hard to scroll without another scrolling mechanism.

If you hide it anyway:

  • Show that content continues, for example with a partly visible next item, a fade at the edge, or arrow buttons.
  • Make the container reachable by keyboard. If it has no focusable content inside, add tabindex="0" and an aria-label so arrow keys can scroll it.
  • Don’t hide the main page scrollbar on long pages. It is the main indicator of page length and position.

For horizontal carousels, CSS scroll snapping makes swiping between items feel controlled once the scrollbar is gone.

FAQs

Common questions about hiding scrollbars with CSS:

How do I hide the scrollbar in CSS without disabling scrolling?
Keep overflow: auto on the element and add scrollbar-width: none, with ::-webkit-scrollbar { display: none; } as a fallback for older browsers. Don't use overflow: hidden, which removes scrolling as well as the scrollbar.
Does scrollbar-width: none work in Safari?
Yes, from Safari 18.2 on macOS and iOS. Older Safari versions need ::-webkit-scrollbar { display: none; }, which is why the snippet includes both.
What is the difference between overflow: hidden and hiding the scrollbar?
overflow: hidden clips the content and stops users from scrolling it. scrollbar-width: none only removes the visible scrollbar, and the content can still be scrolled.
Is hiding scrollbars bad for accessibility?
It can be. Without a scrollbar, some users don't know the area scrolls or can't scroll it at all. Add a visual cue and make sure the container can be scrolled with the keyboard.

Remove WordPress Version from Header

You may want to prevent the display of the WordPress version you are using that appears automatically in the site header. One reason to do this is securing your WordPress site.

If those trying to breach your site know the version you use by looking at the site source, it can guide them and make their job easier because they can easily check for security vulnerabilities in that version.

// remove version info from head and feeds
function sv_complete_version_removal() {
    return '';
}
add_filter('the_generator', 'sv_complete_version_removal');

Redirect New Registered Users to a Specific Page

If your site allows registration to your WordPress site, you may want to redirect new registrants to a specific page after successful registration. For example, a page where they can download a file, or one that shows important information you want that user to see after registration:

function sv_registration_redirect(){
    return home_url( '/finished/' );
}
add_filter( 'registration_redirect', 'sv_registration_redirect' );

Information about redirects related to this topic can be found in the post 301 redirects and their importance for SEO.