Tuesday, 5 November 2013

Filled Under: ,

Top 20+ Must-Have Essential WordPress Tips & Tricks

04:07:00

WordPress is fantastically versatile blogging platform with next-to endless potential for tweaking and customization. Whether you’re an advanced web developer or a WordPress newbie there are a number of solutions you can employ to give your project something extra.

I have been using WordPress for quite some time now and even I still find new solutions and tricks on a regular basis. Today, I am using my experience to bring you the best 20 WordPress tips and tricks that will have you stop reaching for Panadol in no time.

1. How to Use a Custom Page as a Home Page

This is pretty basic, however it is probably one of the most popular WordPress tips for beginners. Creating a custom page and using it as a homepage is great for creating a truly unique homepage.
  1. <?php /* Template Name: MyCustomWPTemplate */ ?>

  2. <!-- Your Custom Page Content -->
Save this file as MyCustomWpTemplate.php and place it in your WordPress theme directory. You can edit the name and content of the file to whatever you like. Now when you create a new page, you can use your newly created php file as the template for that page.
Create a new page and choose your new template as the page template.
custom-template1
Once you have published this page go to Settings » Reading in your admin panel. And select your page to be the homepage. Now you have yourself a Custom Home Page.

2. Create A Custom Loop

Creating a custom loop is one of the greatest fundamental functions of WordPress. A custom loop can lead to big improvements for your site in terms of both usability and visual aesthetics. Displaying a custom loop is pretty easy.
  1. <?php query_posts(array(
  2. 'post_type' => 'post',
  3. 'posts_per_page' => 10 ));
  4. if (have_posts()) : while (have_posts()) : the_post(); ?>

  5. <!--Your Custom Loop Content Goes Here-->

  6. <?php endwhile; endif; wp_reset_query(); ?>
This is the quickest and most widely accepted way of creating a custom loop. Basically we are just creating a query that displays posts which are filtered by the queries conditions. You can use a number of different filters for custom loop queries like using tags, categories, authors or even displaying random posts. Here the only condition we have applied is the number of posts to display (10), but you can change this to as many as you like.

3. Filter Posts From Tag or Categories

So presuming you have made a custom loop, you may want to filter your loop by taxonomy or category. This is great for custom homepages as you can have multiple categorized loops on one page.
  1. <?php query_posts(array(
  2. 'post_type' => 'post',
  3. 'cat' => 'post_category', // This will filter by category
  4. 'tag__in' => array( 'post_tag' ), // This will filter by tag
  5. 'posts_per_page' => 10 ));
  6. if (have_posts()) : while (have_posts()) : the_post(); ?>

  7. <!--Your Loop Custom Content Goes Here-->

  8. <?php endwhile; endif; wp_reset_query(); ?>

4. Reference An External .php file As Content

If you are creating complicated queries using if statements you can reference external php pages rather than including your conditional content directly in a page or loop. This will make your page load a lot faster as WordPress doesn’t need to process as much php. This is why most professional web developers organize their content in external php files and then reference it when needed.
Create a php file and name it mycontent.php. Now when you create a conditional if statement reference your page as follows:
  1. <?php get_template_part('content', 'mycontent'); ?>

5. Display Random Posts In A Loop

A cool feature in WordPress is the ability to create custom loops that will display a random post. This is useful for creating ‘Surprise Me’ style pages that will display a random post every time it is clicked.
  1. <?php
  2. query_posts(array(
  3. 'post_type' => 'post',
  4. 'orderby' => 'rand',
  5. 'posts_per_page' => 1 ));
  6. if (have_posts()) : while (have_posts()) : the_post(); ?>

  7. <?php the_content(); ?>

  8. <?php endwhile; endif; ?>
Again, this is just a basic loop running a post query. You can combine this function with other things like category and tag filters for some interesting combinations.

6. Remove Image Attributes For Inserted Images

When you upload an image through your media importer and insert it into a post, WordPress will automatically add HTML attributes defining the width and height of the image. If your website is responsive, this is especially irritating as you will have to manually delete the width and height of every inserted image. The code below removes the inserted HTML attributes making all your images 100% responsive.
  1. add_filter( 'get_image_tag', 'remove_width_and_height_attribute', 10 );
  2. add_filter( 'post_thumbnail_html', 'remove_width_and_height_attribute', 10 );
  3. add_filter( 'image_send_to_editor', 'remove_width_and_height_attribute', 10 );

  4. function remove_width_and_height_attribute( $html ) {
  5. return preg_replace( '/(height|width)="\d*"\s/', "", $html );
  6. }

7. Force High Quality JPG Images

If your site relies on a lot of images in your content (maybe you’re a photographer), you’ll want these to be high quality. By default, WordPress reduces all your images to 90% quality to reduce page size. You can change this to 100% quality quite easily. Alternatively you can also lower this to 85 or 80 if you want to save some size on your pages. Just add the following code in your themes functions.php file.
  1. add_filter('jpeg_quality', function($arg){return 100;});

8. Conditionally Apply Content

One handy tip is to conditionally display content depending on the page type. This can be used for a number of optimizations including external stylesheets, custom JavaScript or even in your footer, sidebar or header. Below are a number of useful conditional statements, in no-particular order. You can use different combinations of them by using ifelse and elseif statements.
  1. <?php if(is_home()) { ?> <!--Your Conditional Content--> <?php }
  2. // Returns true only on the homepage ?>
  3. <?php if(is_single()) { ?> <!--Your Conditional Content--> <?php }
  4. // Returns true only on Single post pages ?>
  5. <?php if(is_post_type_archive()) { ?> <!--Your Conditional Content--> <?php }
  6. // Returns true only post type archives?>
  7. <?php if(comments_open()) { ?> <!--Your Conditional Content--> <?php }
  8. // Returns true only if comments are open for a post?>
  9. <?php if(is_page()) { ?> <!--Your Conditional Content--> <?php }
  10. // Returns true only if a page is being displayed?>
  11. <?php if(is_page_template( 'pagetemplate.php' )) { ?> <!--Your Conditional Content--> <?php }
  12. // Returns true if page template is being used?>
  13. <?php if(has_term('green')) { ?> <!--Your Conditional Content--> <?php }
  14. // Checks if a term appears in a post ?>
  15. <?php if(is_author('Jonhn-Doe')) { ?> <!--Your Conditional Content--> <?php }
  16. // If John Doe has written this post ?>
WordPress has a lot more of these useful conditional statements, you can find more of them here.

9. Display Twitter Follower Count as Text

Displaying your twitter follower count is a great feature to add to make your website more social-media friendly and can be done quite easily. Create a file named twitter.php and paste the following code into it.
  1. $tw = get_option("twitterfollowerscount");
  2. if ($tw['lastcheck'] < ( mktime()3600 ) )
  3. {
  4. $xml=file_get_contents('http://twitter.com/users/show.xml?screen_name=wpbeginner');
  5. if (preg_match('/followers_count>(.*)</',$xml,$match)!=0) {
  6. $tw['count'] = $match[1];
  7. }
  8. $tw['lastcheck'] = mktime();
  9. update_option("twitterfollowerscount",$tw);
  10. }
  11. echo $tw['count'];
Replace YOURTWITTERID with your real ID. Now when you want display your twitter count simply use the following code.
  1. <?php include("twitter.php"); ?>

10. Customize Blog Title Depending On Page

In your WordPress admin panel you can choose your website title. This title will show up in Google search results as well as in the browser tab. You can customize this title depending on the page. Add the following code into your theme’s functions.php file.
  1. function mycustomthemetitle( $title ) {
  2. global $paged, $page;
  3. if ( is_feed() )
  4. return $title;
  5. if ( is_singular() || is_archive() || is_category() )
  6. return $title;
  7. $title .= get_bloginfo( 'name' );
  8. if ( $paged >= 2 || $page >= 2 )
  9. $title = sprintf( __( 'Page %s' ), max( $paged, $page ) );
  10. return $title;
  11. }
  12. add_filter( 'wp_title', 10, 2 );

11. Modify Excerpt Length and More Tags

Customizing your excerpt length is pretty easy. By defualt WordPress uses words to count the excerpt length. You can easily change this length and also the edit the read more text. Drop the following code in your theme’s functions.php file.
  1. // Changing excerpt length
  2. function new_excerpt_length($length) {
  3. return 100;
  4. }
  5. add_filter('excerpt_length', 'new_excerpt_length');

  6. // Changing excerpt more
  7. function new_excerpt_more($more) {
  8. return '...';
  9. }
  10. add_filter('excerpt_more', 'new_excerpt_more');

12. Link to Your Blog Post In The Excerpt’s More Tag

When you call the_excerpt() function, WordPress automatically includes the more tag. You can link to you blog post easily by changing the default more tag. Place the following code in your theme’s functions.php file.
  1. // Replaces the excerpt "more" text with a link
  2. function new_excerpt_more($more) {
  3. global $post;
  4. return '<a class="moretag" href="'. get_permalink($post->ID) . '"> Read the full article...</a>';
  5. }
  6. add_filter('excerpt_more', 'new_excerpt_more');

13. Limit Excerpt Length by Characters

By defualt, WordPress uses a word count to count the excerpt length. If you have specific space requirements or mabye you just want a more precise excerpt length, you can use characters instead of words for the excerpt count. Drop the code below into your theme’s function.php file.
  1. function get_excerpt($count){
  2. $permalink = get_permalink($post->ID);
  3. $excerpt = get_the_content();
  4. $excerpt = strip_tags($excerpt);
  5. $excerpt = substr($excerpt, 0, $count);
  6. $excerpt = substr($excerpt, 0, strripos($excerpt, " "));
  7. $excerpt = $excerpt.'... <a href="'.$permalink.'">more</a>';
  8. return $excerpt;
  9. }
Now when you want to display the excerpt length by characters simply use the following code. You can change the number to whatever length you like. This is particularity handy as the length is defined in the functions call rather than the function itself. This way if you are using multiple excerpt lengths you can easily change them.
  1. <?php echo get_excerpt(125); ?>

14. Display Breadcrumb Navigation in WordPress

A lot of blogs use breadcumb navigation to show readers exactly where the current page they are viewing is located. There are a number of plugins to achieve this, however you can achieve the same results quite easily without the use of any plugins. Place the following code into your theme’s functions.php file.
  1. function MyBreadcrumb() {
  2. if (!is_home()) {
  3. echo '<a href="';
  4. echo get_option('home');
  5. echo '">';
  6. echo 'Home';;
  7. echo "</a> » ";
  8. if (is_category() || is_single()) {
  9. the_category('title_li=');
  10. if (is_single()) {
  11. echo " » ";
  12. the_title();
  13. }
  14. } elseif (is_page()) {
  15. echo the_title();
  16. }
  17. }
  18. }
Now when you want to display breadcrumb navigation, use the code below.
  1. <code><?php MyBreadcrumb(); ?></code>

15. Organise Your Functions.php file

Depending on your theme’s back-end setup, your functions .php file can get pretty messy and complicated, particularly if you frequently add custom codes into it. However there is a much easier way to organize things. Create a new file and name it mycustomfunctions.php. Add all your custom functions in this file. Then all you need to do is reference this file from your functions.php file.
  1. include("mycustomfunctions.php");
This is a really good workflow to follow as you can create a number of different files for different things like different widgets and short-codes. It helps keep things organized.

16. Enqueue JavaScript Properly

WordPress has a built in function for inserting external JavaScript into your theme’s <head>, as apposed to inserting it directly. The benefit of using the enqueuescript function is that resolves any conflict issues that arise from multiple external script files. It also ensures they are loaded after any CSS. Drop the following code into your theme’s function.php file.
  1. function add_scripts() {
  2. global $data; //get theme options

  3. //replace jQuery with Google hosted version
  4. wp_deregister_script('jquery');
  5. wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"), false, '1.7.1');
  6. wp_enqueue_script('jquery');

  7. //replace jQuery UI with Google hosted version
  8. wp_deregister_script('jquery-ui');
  9. wp_register_script('jquery-ui', ("http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"), false, '1.8.16');
  10. wp_enqueue_script('jquery-ui');

  11. // Site wide js
  12. wp_enqueue_script('customscript', get_template_directory_uri() . '/js/customscript.js');

  13. }
  14. add_action('wp_enqueue_scripts');

17. Use Google Fonts Through CSS Enqueue

If you want to use Google’s WebFont archive you can enqueue the external font file directly from your theme’s functions.php file.
  1. add_action('init', 'google_font_style');
  2. function google_font_style(){
  3. wp_register_style( 'GoogleFonts', 'http://fonts.googleapis.com/css?family=SOMEFONT');// Replace this url with the google font url you want to use
  4. wp_enqueue_style( 'GoogleFonts' );
  5. }

18. Disable HTML in WordPress Comments

Are you sick of getting lots of spam in your comments? Most spammers use html code to post links into comments, this is how they bypass your default spam security. You can disable this ability easily, add the following code into your theme’s functions.php file.
  1. <pre>// This will occur when the comment is posted
  2. function plc_comment_post( $incoming_comment ) {

  3. // convert everything in a comment to display literally
  4. $incoming_comment['comment_content'] = htmlspecialchars($incoming_comment['comment_content']);

  5. // the one exception is single quotes, which cannot be #039; because WordPress marks it as spam
  6. $incoming_comment['comment_content'] = str_replace( "'", '&apos;', $incoming_comment['comment_content'] );

  7. return( $incoming_comment );
  8. }

  9. // This will occur before a comment is displayed
  10. function plc_comment_display( $comment_to_display ) {

  11. // Put the single quotes back in
  12. $comment_to_display = str_replace( '&apos;', "'", $comment_to_display );

  13. return $comment_to_display;</pre>

19. Styling Author Comments

Did you know you can style the author’s comments in WordPress? This is great for making your replies to your readers stand out more among other things. Use the CSS selectors below to change the author’s comments styling.
  1. .commentlist .bypostauthor {}
  2. .commentlist li ul.children li.bypostauthor {}

20. Remove Detailed Login Error Information for Security

If you use the wrong name or password when trying to login to your admin panel, WordPress displays information on why the attempt was unsuccessful, like Incorrect Email Address or Incorrect Password. This poses a serious security threat as hackers can use this information to compromise your website. To remove the displaying of this information, add the following code into your theme’s funtions.php file.
  1. add_filter('login_errors',create_function('$a', "return null;"));

21. Add Edit This Post Butom On Posts And Pages

Sometimes when you are reading over your latest post after you have published it, you may find a spelling error or something you would like to change. So you go to your admin panel and find the post and then edit it. This a lengthy process, particularly if you have a lot of posts. Luckily you can add an ‘Edit This Post’  button that will only appear for logged in administrators or authors. Place the following code where you would like the link to appear.
  1. <?php edit_post_link(__('Edit This')); ?>

22. Display Feedburner Subscriber Count as Text

Another great trick is displaying your FeedBurner count as text. This helps gain more subscribers to your website and also just gives you bragging rights. Simply copy and paste the code below where you would like to display your count.
  1. <?php
  2. //get cool feedburner count
  3. $whaturl="http://api.feedburner.com/awareness/1.0/GetFeedData?uri=your feedburner id";

  4. //Initialize the Curl session
  5. $ch = curl_init();

  6. //Set curl to return the data instead of printing it to the browser.
  7. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  8. //Set the URL
  9. curl_setopt($ch, CURLOPT_URL, $whaturl);

  10. //Execute the fetch
  11. $data = curl_exec($ch);

  12. //Close the connection
  13. curl_close($ch);
  14. $xml = new SimpleXMLElement($data);
  15. $fb = $xml->feed->entry['circulation'];
  16. echo $fb;
  17. //end get cool feedburner count
  18. ?>

0 comments:

Post a Comment