Showing posts with label functions.php. Show all posts
Showing posts with label functions.php. Show all posts

Saturday 30 November 2013

Set WordPress Permalinks Settings From functions.php

Permalinks are the permanent URLs to your individual WordPress or blog posts, as well as pages and other lists of blog postings. It's very important to have an easy and beautiful permalinks structure for your site, as it's a part of optimizing your site for SEO.

The default WordPress permalinks structure looks something like this:

http://www.whatever.com/?p=316

And I hate this as much as you all do. However, you can change the default structure of your blog permalinks in the settings of your WordPress blog. But we can also change the default permalinks structure from our functions.php file.

It's pretty easy, just add following snippet to your functions.php file:

<?php
// set permalink
function set_permalink(){
    global $wp_rewrite;
    $wp_rewrite->set_permalink_structure('/%year%/%monthnum%/%postname%/');
}
add_action('init', 'set_permalink');
?>

Use this snippet to change the permalink settings from your functions.php file instead of in the admin area. You can replace the red area in above code with following structure codes:

%year%
    The year of the post, four digits, for example 2004

 %monthnum%
    Month of the year, for example 05

 %day%
    Day of the month, for example 28

 %hour%
    Hour of the day, for example 15

 %minute%
    Minute of the hour, for example 43

 %second%
    Second of the minute, for example 33

 %post_id%
    The unique ID # of the post, for example 423

 %postname%
    A sanitized version of the title of the post (post slug field on Edit Post/Page panel). So “This Is A Great Post!” becomes this-is-a-great-post in the URI.

 %category%
    A sanitized version of the category name (category slug field on New/Edit Category panel). Nested sub-categories appear as nested directories in the URI.

 %author%
    A sanitized version of the author name.

Sunday 17 November 2013

Using A Different Post Template For Posts Within A Specific Category

On Thursday I posted an article about using different post template for posts formats, but now it's time for doing the same thing with categories, instead of formats. You can use this trick in your WordPress to create different type of posts, such as portfolio items.

We discussed everything previously, so let's get into this trick:

Using A Different Post Template:

In this tutorial, we'll create a different post template for the cat-1 category. We'll use multiple single.php files to make it more easy and customizable.

Create a single.php file for your category. We're going to name it single-cat-1.php. You can also copy your single.php file to this template and make some changes that you want in the video template.

Upload single-cat-1.php to the root of your current theme. Same place where single.php file is located.

Okay, so now we'll tell WordPress to use single-cat-1.php template for the posts within video category. Add following to your theme's functions.php file:

add_action('template_include', 'load_single_template');
  function load_single_template($template) {
    $new_template = '';

    // single post template
    if( is_single() ) {
      global $post;

      // 'cat-1' is category slugs
      if( has_term('cat-1', 'category', $post) ) {
        // use template file single-template-cat-1.php
        $new_template = locate_template(array('single-cat-1.php' ));
      }

    }
    return ('' != $new_template) ? $new_template : $template;
  }

In above code, replace cat-1 is the slug of your category, and single-cat-1.php is your custom post template file. Save the file. That's it.

Thursday 14 November 2013

Using A Different Post Template For Posts Formats In WordPress

Post Formats is a theme feature which was introduced with the WordPress 3.1 release. It gave us a new feature to style posts based on its format. If you ever used WordPress' default themes, then you might know about their different post templates based on the post format. So it's time for you to style your posts based on its format. Here's a demo of this trick from my own WordPress site:

This is a simple post.

This is a video post with a different template.

Add Post Format Support To Your WordPress Theme:

Before starting this tutorial, it's important for you to add support for post formats in your current WordPress theme. If this section is available in your post editor then you can skip this step:


If not, then follow this tutorial.

Using A Different Post Template:

In this tutorial, we'll create a different post template for the Video format. Most of developers uses a single post template file for all different format. But we'll use multiple single.php files to make it more easy and customizable.

Create a single.php file for your post format (we're using Video). We're going to name it single-video.php. You can also copy your single.php file to this template and make some changes that you want in the video template.

Upload single-video.php to the root of your current theme. Same place where single.php file is located.

Okay, so now we'll tell WordPress to use single-video.php template for the posts with video format. Add following to your theme's functions.php file:

add_action('template_include', 'load_single_template');
  function load_single_template($template) {
    $new_template = '';

    // single post template
    if( is_single() ) {
      global $post;

      // template for post with video format
      if ( has_post_format( 'video' )) {
        // use template file single-video.php for video format
        $new_template = locate_template(array('single-video.php' ));
      }

    }
    return ('' != $new_template) ? $new_template : $template;
  }

Save the file. That's it.

Now just publish a post with video format & see the magic. You can do the same with every post format. On a related note, I'll also share the same trick with categories, instead of formats.

Add Post Formats To WordPress Theme

It's school holiday for five days in a row, so as a part of the second day of this holiday, I was doing some random stuff around the internet, such as listing to new songs, reading about upcoming Next-Gen gaming consoles, browsing troll memes, blaming Justin Bieber, and more.

So in this busy day I took some time to edit my WordPress website for new feature. I did some thing new (at least for me) with some post formats, and I'm going to share it here on BWidgets. So as a part of that tutorial, here's the basic thing to learn before I post that article, which is adding post format support to your WordPress theme.

Post Formats is a theme feature introduced with the WordPress 3.1 release. It's piece of meta info that can be used by a theme to customize its post structure. If you ever used Tumblr, then you'll love this feature.

As of now, WordPress supports following post formats:

  • aside: Typically styled without a title. Similar to a Facebook note update.
  • gallery: An image gallery. This type of post will likely contain an image gallery using shortcode and plugins.
  • link: A link to an external webpage.
  • image: A single image. Yeah, just a single image.
  • quote: A quatation. My favorite quote is: Your arms are just too short to box with the God. - CM Punk to Dwayne "The Rock" Johnson
  • status: A short status update, similar to a tweet.
  • video: A single video or several videos. You can upload or embed a video to the post.
  • audio: An audeo file, likely if you run a Podcast.
  • chat: A chat transcript.

Add following snippet to your theme's functions.php file to add post format support to your post:

add_theme_support( 'post-formats', array( 'aside', 'chat','gallery','image','link', 'quote', 'status', 'video', 'audio' ) );

You can also add post format support to Page and custom post types:

// add post-formats to post_type 'page'
add_post_type_support( 'page', 'post-formats' );

// add post-formats to post_type 'my_custom_post_type'
add_post_type_support( 'my_custom_post_type', 'post-formats' );

Monday 11 November 2013

Change WordPress Login Logo Without Plugins

Above is a screen shot of the login page of my WordPress website. As you can see in above image, I'm using my website's logo in the login page instead of WordPress logo. And it looks pretty good.

If you're running a website with public registration or a client website, then you should replace the default logo with your own. There are lots of plugins to change the custom logo in some easy steps. However, we're going to do this without any plugin.

Add this snippet to the functions.php file of your active theme:

<?php
function custom_login_logo() {
    echo '<style type="text/css">
        h1 a { background-image:url('CUSTOM-LOGO-URL.png') !important; }
    </style>';
}
add_action('login_head', 'custom_login_logo');
?>

Replace the CUSTOM-LOGO-URL.png in above code with url of your custom login logo. That's it.

Sunday 10 November 2013

How To Set Minimum Word Count For WordPress Posts

If you're running a WordPress site with some co-authors then it's really important for you to focus on your content's quality. Quality content is the ultimate key to success in blogging. Most of bloggers write like a monkey in the very beginning; I was also in that league when I started this blog.

Since recent Google updates you can no longer post an article with some couple of words and expect the post to rank highly for the keywords in the title. Now you need more content in the entire post with a lot of different keywords.

With WordPress you can create a function to make sure that you have a minimum number of words in your post.

By adding following code to your functions.php file, you can check if the post is under 500 words and if it is you can end the publishing process so the post will not be published:

function minimum_number_words($content)
{
    global $post;
    $content = $post->post_content;
    if (str_word_count($content) < 500 )
    wp_die( __('The current post is below the minimum number of words, it must be over 500 words.') );
}

Friday 8 November 2013

How To Set Minimum Comment Length In WordPress

Most of us turn on comments in our sites to start a discussion and reach out more people. But some people comment just to get a link back to their own site. Their comments will consist of things like "nice post", "thanks" and all stuff.

If you're running a big website, then moderating these crappy comments will waste a lot of time. So how about setting a minimum character count length on your comments.

Add following snippet to your functions.php file:

add_filter( 'preprocess_comment', 'minimal_comment_length' );

function minimal_comment_length( $commentdata ) {
    $minimalCommentLength = 20;

    if ( strlen( trim( $commentdata['comment_content'] ) ) < $minimalCommentLength )
        {
        wp_die( 'All comments must be at least ' . $minimalCommentLength . ' characters long.' );
        }
    return $commentdata;
}

Save your file. That's it. You can also replace 20 in the above code with your custom value.

Tuesday 5 November 2013

Bulk Remove Featured Images From WordPress Posts

By default, there's no such option in WordPress to remove featured image from all posts at once. You can only remove the featured image by editing each post and removing it manually. It can take a lot of time. For example, it's almost impossible to manually remove featured images from my WWEFansNation.com with more than 4,000 posts. But that's all right cuz we're here to solve this problem.

WPBeginner found a great way to remove (unset) featured images from all posts in bulk. It's worth nothing that this code will only remove the featured image from the posts, and the image will not be deleted from your site.

Copy & paste following code in your theme's functions.php file:

global $wpdb;

$attachments = $wpdb->get_results( "
     SELECT *
     FROM $wpdb->postmeta
     WHERE meta_key = '_thumbnail_id'
" );

foreach ( $attachments as $attachment ) {
    wp_delete_attachment( $attachment->meta_value, true );
}

$wpdb->query( "
    DELETE FROM $wpdb->postmeta
    WHERE meta_key = '_thumbnail_id'
" );

Important: Please remove this code immediately after saving your functions.php file. You only need to run this code once, there's no need to keep this code in your theme.

Monday 4 November 2013

Automatically Set The Featured Image In WordPress

Almost every WordPress theme developer is using WordPress' featured post image option in their latest themes, and it's a very great option. You can pick any image for your article before publishing

But ofter we forget to pick a featured image for out posts. Also there's no way to pick a featured image in WordPress' smartphone application. So today we're going to automatically set the featured image.

This snippet will automatically set the first image of your post as the featured image of the post. Note, you can always go and set another image as the featured image if you want to.

Add following snippet to your functions.php file:

function wpforce_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);
                                }
                           } else {
                                set_post_thumbnail($post->ID, '414');
                           }
                        }
      }  //end function
add_action('the_post', 'wpforce_featured');
add_action('save_post', 'wpforce_featured');
add_action('draft_to_publish', 'wpforce_featured');
add_action('new_to_publish', 'wpforce_featured');
add_action('pending_to_publish', 'wpforce_featured');
add_action('future_to_publish', 'wpforce_featured');

There is one more cool option in this code. If you don't have an image in the post, the above code will let you set a default featured image as well. You must edit the attachment ID according to your WordPress site. The example above uses the attachment ID "414"

Credits: WPForce

Sunday 3 November 2013

Move WordPress Admin Bar To The Bottom

Ever wanted to move your WordPress blog's Admin Bar to bottom of the page? If yes, then this is the right place for you. It sounds like a telemall commercial, lol. With just a bit CSS you can change it. So instead of editing the core CSS files, we'll add some CSS to your functions.php file.

Put this little snippet to a Plugin or in the functions.php of your theme:

 function fb_move_admin_bar() {
    echo '
    <style type="text/css">
    body {
    margin-top: -28px;
    padding-bottom: 28px;
    }
    body.admin-bar #wphead {
       padding-top: 0;
    }
    body.admin-bar #footer {
       padding-bottom: 28px;
    }
    #wpadminbar {
        top: auto !important;
        bottom: 0;
    }
    #wpadminbar .quicklinks .menupop ul {
        bottom: 28px;
    }
    </style>';
}
// on backend area
add_action( 'admin_head', 'fb_move_admin_bar' );
// on frontend area
add_action( 'wp_head', 'fb_move_admin_bar' );

Thursday 31 October 2013

Stop WordPress From Compressing JPEG Images

According to some blogs, WordPress automatically compress your JPEG images to 90% quality, but this information is false.

This only happens on the resized images WordPress creates. The original uploaded image is saved unaltered, as the "full" size.

Anyways, you can stop compressing of JPEG images by putting following code into your functions.php file:

add_filter('jpeg_quality', function($arg){return 100;});
add_filter( 'wp_editor_set_quality', function($arg){return 100;} );

Tuesday 29 October 2013

Remove Author Prefix From Slug In WordPress


Earlier this month I shared an article about changing WordPress Author URL Slug. That code will change the default yoursite.com/author/name to yoursite.com/profile/name.

Now this trick will remove the author prefix from the author slug. To clarify, this snippet will help you turn: yoursite.com/author/name/ into: yoursite.com/name/.

Just add following snippet to your functions.php file:

// The first part //
add_filter('author_rewrite_rules', 'no_author_base_rewrite_rules');
function no_author_base_rewrite_rules($author_rewrite) {
    global $wpdb;
    $author_rewrite = array();
    $authors = $wpdb->get_results("SELECT user_nicename AS nicename from $wpdb->users");   
    foreach($authors as $author) {
        $author_rewrite["({$author->nicename})/page/?([0-9]+)/?$"] = 'index.php?author_name=$matches[1]&paged=$matches[2]';
        $author_rewrite["({$author->nicename})/?$"] = 'index.php?author_name=$matches[1]';
    }  
    return $author_rewrite;
}

// The second part //
add_filter('author_link', 'no_author_base', 1000, 2);
function no_author_base($link, $author_id) {
    $link_base = trailingslashit(get_option('home'));
    $link = preg_replace("|^{$link_base}author/|", '', $link);
    return $link_base . $link;
}

Props to WP-Snippet for this amazing tricks.

Monday 28 October 2013

Allow Contributors To Upload Images In WordPress

Are you running a WordPress website with bunch of contributors who are willing to post on your website? If yes then this article contains a great tip for you.

As I mention on previous articles, every post on your blog must contain at least one image related to the article. It's really great for SEO and other things.

This code will help us to allow users with contributor role to upload images on your WordPress site.

Add this code to your functions.php file:

if ( current_user_can('contributor') && !current_user_can('upload_files') )
     add_action('admin_init', 'allow_contributor_uploads');
    
     function allow_contributor_uploads() {
          $contributor = get_role('contributor');
          $contributor->add_cap('upload_files');
     }

Thursday 24 October 2013

How To Disable Smart/Curly Quotes In WordPress

There are lot of word processor programs which itself converts all yours simple quotes to curly quotes (aka s mart quotes). It looks like small figures six and nine raised above the baseline (like 6...9 and 66...99).

It's a huge problem if you're writing codes in your posts as WordPress automatically converts all quote symbols to smart quotes. So if anyone is copying a snippet from your blog post would have problems with running to code in their own text file.

You can easily disable this feature with a small snippet. Just add following snippet to your functions.php file:

<?php
remove_filter('the_content', 'wptexturize');
remove_filter('comment_text', 'wptexturize');
remove_filter('the_excerpt', 'wptexturize');
?>

That's it!

Thursday 10 October 2013

Send Email Notifications When User Role Changes In WordPress

Yesterday I shared a code which sends an email to the user when the user updates their profile. Today I have something similar, but a bit different. This code sends an email the user when the user's role has changed.

It's a great way to let a member know about the role changes that you'll make. It's also a great trick if you're running a WordPress site with bbPress forum or multiple wirters & contributors.

Just add following to your functions.php:

function user_role_update( $user_id, $new_role ) {
        $site_url = get_bloginfo('wpurl');
        $user_info = get_userdata( $user_id );
        $to = $user_info->user_email;
        $subject = "Role changed: ".$site_url."";
        $message = "Hello " .$user_info->display_name . " your role has changed on ".$site_url.", congratulations you are now an " . $new_role;
        wp_mail($to, $subject, $message);
}
add_action( 'set_user_role', 'user_role_update', 10, 2);

That's it.

Wednesday 9 October 2013

Send Email Notifications When User Profile Updates In WordPress

Adding this snippet to your functions.php file will send an email to the user when the user updates their profile. It's really great way to provide more security to your users. It's also a great trick if you're running a WordPress site with BuddyPress or bbPress. It makes your website look more advance, and keeps your user secure from hackers.

Just add following to your functions.php:

function user_profile_update( $user_id ) {
        $site_url = get_bloginfo('wpurl');
        $user_info = get_userdata( $user_id );
        $to = $user_info->user_email;
        $subject = "Profile Updated: ".$site_url."";
        $message = "Hello " .$user_info->display_name . "\nYour profile has been updated!\n\nThank you for visiting\n ".$site_url."";
        wp_mail( $to, $subject, $message);
}
add_action( 'profile_update', 'user_profile_update', 10, 2);

Monday 7 October 2013

How To Hide Post View And Post Preview Buttons From WordPress Post Editor

Ever wanted to remove "preview post" & "view post" option from the WordPress' post editor? Here is the solution how to do this. Just add following snippet to your theme's functions.php file and don't forget to update the post type array in the following code:

function posttype_admin_css() {
    global $post_type;
    $post_types = array(
                        /* set post types */
                        'post_type_name',
                        'post',
                        'page',
                  );
    if(in_array($post_type, $post_types))
    echo '<style type="text/css">#post-preview, #view-post-btn{display: none;}</style>';
}
add_action( 'admin_head-post-new.php', 'posttype_admin_css' );
add_action( 'admin_head-post.php', 'posttype_admin_css' );

How To Remove URL Field From WordPress Comment Form

For some WordPress sites, such as themes, review, and all, you may want to remove Website URL field from the WordPress' comment form. Removing the field could be used for product reviews or if they created a support tickets theme that does not require a url field.

It's not much hard to remove/unset the website url from the comment form. Just add following snippet to your functions.php file and it's done:

add_filter('comment_form_default_fields', 'unset_url_field');
function unset_url_field($fields){
    if(isset($fields['url']))
       unset($fields['url']);
       return $fields;
}

Change Post Color By Status In WordPress Admin Panel

It's a great trick if you manage a WordPress site with multiple writers/contributors.It's a great trick if you manage a WordPress site with multiple writers/contributors.

Adding this snippet to your theme's functions.php file will change the background colors of the post / page within the admin based on the current status. Draft, Pending, Published, Future, Private.

add_action('admin_footer','posts_status_color');
function posts_status_color(){
?>
<style>
.status-draft{background: #FCE3F2 !important;}
.status-pending{background: #87C5D6 !important;}
.status-publish{/* no background keep wp alternating colors */}
.status-future{background: #C6EBF5 !important;}
.status-private{background:#F2D46F;}
</style>
<?php
}

How To Login To WordPress Using Your Username Or Email Address

By default, WordPress only allows us to login to WordPress powered sites only with our username. But most of us prefer to enter our email address to login because remembering your email is more simple than usernames.

C. Bavota from bavotasan.com found a great way to allow your users to use either their username or email address to log into WordPress without any plugin. Just add following code to your functions.php file:

function login_with_email_address($username) {
    $user = get_user_by_email($username);
    if(!empty($user->user_login))
        $username = $user->user_login;
    return $username;
}
add_action('wp_authenticate','login_with_email_address');

Kevin Chard improved this trick by adding a snippet to it, which will change the text on the login page from “username” to “username / email.” Add following snippet to your functions.php just below the first code:

function change_username_wps_text($text){
       if(in_array($GLOBALS['pagenow'], array('wp-login.php'))){
         if ($text == 'Username'){$text = 'Username / Email';}
            }
                return $text;
         }
add_filter( 'gettext', 'change_username_wps_text' );

Popular Posts

 
Powered by Blogger.