search

Archives: Snippets | Page 5

Create a Custom Page Template as Homepage

To create a custom page template as the homepage in WordPress, duplicate page.php from your theme’s main directory or create a new PHP file and add the following code at the top:

<?php /* Template Name: xxxxxx */ ?>

Replace xxxxxx with the name that will appear under “Page Attributes” when you create a new page.

Go to your WordPress admin panel, create a new page and select this template.

Custom homepage - WordPress

After publishing the page, go to Settings > Reading in the WordPress admin.

Custom homepage - WordPress

Select your page as the homepage. That is it – you now have a custom homepage. See the post on WordPress page templates.

Change Add to Cart Button Text in WooCommerce

A few weeks ago I ran into a situation where a client wanted different text instead of the standard “Add to Cart” or “Add to Bag” in WooCommerce. Here is the code to add to functions.php to change the text:

add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text' );
 
function woo_custom_cart_button_text() {
         return __( 'My Button Text', 'woocommerce' );
 }

Allow SVG File Uploads in WordPress Media Library

To allow SVG file uploads through the media library, add the following code to your functions.php file:

function cc_mime_types($mimes) {
  $mimes['svg'] = 'image/svg+xml';
  return $mimes;
}
add_filter('upload_mimes', 'cc_mime_types');

A more detailed explanation can be found in this post.

Auto Set First Image as Featured Image in WordPress

The following snippet takes the first image it finds in the post and sets it as the featured image. If you choose a featured image manually, it will of course display that one.

function autoset_featured() {
          global $post;
          $already_has_thumb = has_post_thumbnail($post->ID);
              if (!$already_has_thumb)  {
              $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
                          if ($attached_image) {
                                foreach ($attached_image as $attachment_id => $attachment) {
                                set_post_thumbnail($post->ID, $attachment_id);
                                }
                           }
                        }
      }
add_action('the_post', 'autoset_featured');
add_action('save_post', 'autoset_featured');
add_action('draft_to_publish', 'autoset_featured');
add_action('new_to_publish', 'autoset_featured');
add_action('pending_to_publish', 'autoset_featured');
add_action('future_to_publish', 'autoset_featured');

For more on WordPress image handling, see Image Sizes in WordPress.

Disable Login Error Messages in WordPress

When users enter an incorrect username or password, an error message appears telling them which one is wrong. If someone is trying to break into your site by guessing one of these, that error message can help them understand what they got wrong. Block this by adding the following line to your functions.php file. For more security tips, see hardening your WordPress site:

add_filter('login_errors',create_function('$a', "return null;"));

Set Default Post Editor Mode in WordPress

Some prefer to work with the visual editor when writing posts and others prefer the text editor. Change the default post editor by adding the following lines to your functions.php file:

# Visual Editor as default
add_filter( 'wp_default_editor', create_function('', 'return "tinymce";') );

# HTML Editor as default
add_filter( 'wp_default_editor', create_function('', 'return "html";') );

For more editor configuration, see Enable Gutenberg for Custom Post Types.

Redirect Users After Login by Role in WordPress

You can redirect users who log into your WordPress site to different URLs based on their role.


function redirect_user_on_role()
{
	global $current_user;
   	get_currentuserinfo();
 	if ($current_user->user_level == 0)
 	{
       	wp_redirect( home_url() ); exit;
 	}
 	else if ($current_user->user_level > 1)
 	{
       	 wp_redirect( home_url() ); exit;
 	}
  	else if ($current_user->user_level >8)
 	{
		wp_redirect( home_url() ); exit;
 	}
 	else
 	{
     		$redirect_to = 'http://google.com/';
       	return $redirect_to;
 	}
}
add_action('admin_init','redirect_user_on_role');

For more security best practices, see Hardening WordPress Security.

Enable Comments on Custom Post Types in WordPress

By default WordPress blocks comments on Custom Post Types. To enable comments on a custom post type, add comments under supports where you register it (line 32):

function snippet_custom_init() {
      $labels = array(
          'name' => 'Snippet',
          'singular_name' => 'Snippet',
          'add_new' => 'Add New Snippet',
          'add_new_item' => 'Add New Snippet',
          'edit_item' => 'Edit Snippet',
          'new_item' => 'New Snippet',
          'all_items' => 'All Snippets',
          'view_item' => 'View Snippet',
          'search_items' => 'Search Snippets',
          'not_found' =>  'No snippets found',
          'not_found_in_trash' => 'No snippets found in trash',
          'parent_item_colon' => '',
          'menu_name' => 'Snippets',
          );

      $args = array(
          'labels' => $labels,
          'exclude_from_search' => false,
          'public' => true,
          'publicly_queryable' => true,
          'show_ui' => true,
          'show_in_menu' => true,
          'query_var' => true,
          'rewrite' => array( 'slug' => 'snippet' ),
          'capability_type' => 'post',
          'has_archive' => true,
          'hierarchical' => false,
          'taxonomies' => array('category'),
          'menu_position' => null,
          'supports' => array( 'title', 'author', 'thumbnail', 'excerpt', 'comments', 'editor' )
          );

        register_post_type( 'snippet', $args );
    }
add_action( 'init', 'snippet_custom_init', 0);

Reverse Comment Order in WordPress

A trend I have seen on many blogs is to change the order of comments in WordPress posts so the most recently written comments appear at the top. If your blog posts have many comments, this option can be preferable to prevent the latest comments from being “buried” at the bottom of the page.

Here is how to reverse comment order in WordPress.

Option 1

Go to Settings > Discussion. Under “Other comment settings” find “Older comments at the top of each page” and change the setting accordingly.

Reverse comment order in WordPress

Option 2

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

function wpb_reverse_comments($comments) {
		return array_reverse($comments);
	}	
add_filter ('comments_array', 'wpb_reverse_comments');

Here we use the comments_array filter to reverse the comment order.

That is it – hope this tip helps when you want to reverse comment order on your WordPress site.

For more comment customization, see Show the Total Number of Comments in WordPress.

Savvy WordPress Development official logo