Archives: Snippets | Page 16

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.

Allow Contributors to Upload Images in WordPress

By default, WordPress does not allow users with the Contributor role to upload images to the media library. Of course you could give that user higher-level permissions, but that would allow them to perform additional actions on the site that you may not want them to be able to perform.

The following code lets Contributor users upload images to posts they wrote without any additional permissions:


function sv_allow_contributor_uploads() {
    $contributor = get_role('contributor');
    $contributor->add_cap('upload_files');
}

if (current_user_can('contributor') && !current_user_can('upload_files'))
    add_action('admin_init', 'sv_allow_contributor_uploads');

For more on file uploads in WordPress, see Enable Additional File Type Uploads.

Display Database Queries, Time, and Memory Usage

The following code displays in the footer the number of database queries the page executed, the time it took to run those queries, and the memory usage of the page.

function sv_performance( $visible = false ) {

    $stat = sprintf( '%d queries in %.3f seconds, using %.2fMB memory',
        get_num_queries(),
        timer_stop( 0, 3 ),
        memory_get_peak_usage() / 1024 / 1024
    );

    echo $visible ? $stat : "<!-- {$stat} -->" ;
}

add_action( 'wp_footer', 'sv_performance', 20 );

The result appears as a comment in the footer. Check the page source to see it:

<!-- 33 queries in 1.532 seconds, using 48.75MB memory -->

For more performance optimization, see Improve WordPress Loading Time.

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.