Share Tweet Reccomend

WordPress Shortcode: Popular Posts in Last X Number of Days

Shortcode Sunday! The time when we provide a semi-useful WordPress shortcode to kick your week off on a good note! This shortcode will allow you to display your most popular posts in the last 20 days or 30 days or 60 days or any number of days that you want to specify. The way that it determines what is “popular” is by the number of comments that the post has received. You will also be able to specify a limit to the number of popular posts you want to show.

So go ahead and add this function to wherever it is you are registering your shortcodes in WordPress…

function popularPostsShortcode($atts, $content = null) {
    extract(shortcode_atts(array("limit" => '4', "days" => '60'), $atts));
    global $wpdb;
    $sql = $wpdb->prepare("SELECT comment_count, ID, post_title, post_date FROM $wpdb->posts WHERE post_date BETWEEN DATE_SUB(NOW(), INTERVAL $days DAY) AND NOW() ORDER BY comment_count DESC LIMIT 0, $limit");
    $posts = $wpdb->get_results($sql);

    $list = '<div>';
        foreach ($posts as $post) {
            setup_postdata($post);
            $id = $post->ID;
            $title = $post->post_title;
            $count = $post->comment_count;
            
            if ($count != 0) {
                $list .= '<a href="'.get_permalink($id).'" title="'.$title.'">'.$title.'</a> ('.$count.' comments)';
            }
        }
        $list .= '</div>';
    return $list;		
}

Then all you have to do is register this shortcode after declaring the function…

add_shortcode('popularposts', 'popularPostsShortcode');

or if you are using it inside a class (as I highly recommend) you would register it in the following manner…

add_shortcode('popularposts', array($this, 'popularPostsShortcode'));

And if you want to use it in a page or post somewhere you’d just have to call it like so.

    Limit refers to the maximum number of posts you want to show and days refers to the number of days prior to the current day that you want to get popular posts for. So this shortcode would get the top 5 most commented on posts in the last 60 days.

    Enjoy 🙂

    , , ,
    Share Tweet Reccomend

    Clean Up Your functions.php file by Using Classes in WordPress

    If you have done WordPress development for any extended perious of time, you inevitably go searching for different ways to do things. A lot of times what these tutorials will do will give you some code and say…

    Just add the following snippet of code to your functions.php file and all will work great.

    Having written tutorials for WordPress, I have been guilty of this. It’s a quick and easy way to give a user some functionality.

    That’s all well and good when your first starting out, but after awhile if you’re not careful, you can end up just adding and adding and adding to your functions.php file and then pretty soon you have a massive document on your hands before you know it. It’s never good from programming perspective of maintainability and scalability to have large amounts of code concentrated that perform many diverse aspects of functionality located in a single place.

    But what’s the alternative? I’m glad you asked. Well, by using classes in WordPress you can divide the code that handles the functionality for your website up into smaller parts each representing one piece of functionality. And in your functions.php file all you have to do is include the class. Then your functions file becomes a lot more lightweight and it is much nicer to work with when you have to use it for something else.

    Let’s see an example of this. Let’s do something fairly standard that you’d normally do in WordPress: registering a shortcode. For the sake of example, let’s register a shortcode that does something simple like say hello. Maybe a previous tutorial would tell you to do something like put the following in your functions.php file…

    function sayHelloShortcode($atts, $content = null) 
    {
        return 'I am happy to say hello!';
    }
    add_shortcode('say_hello', 'sayHelloShortcode');
    

    So now if you’d typed [say_hello] in into the editor in a page or post the text “I am happy to say hello!” would appear. Real world shortcodes are obviously much more complex than this but for the sake of example is best to keep things simple.

    Now that’s nice. But as you add more and more shortcodes (and more complex shortcodes with large amounts of code inside the body of each function, your functions.php file could start to get out of hand.

    So how can we solve this problem? Well it would actually make sense to take all of our shortcodes out of functions.php and group all of our shortcodes inside of one class. That way, we can have them all centralized in one location and if we want to add more, we’ll know where do do it. So if we wanted to add a shortcode to a class, this is how we’d do it. Create a new PHP file called Shortcodes.php and add the following…

    <?php
    class Shortcodes {
        function __construct() {
            add_shortcode('say_hello',  array($this, 'sayHelloShortcode'));
        }
    
        function sayHelloShortcode($atts, $content = null) 
        {
            return 'I am happy to say hello!';
        }
    
    }
    ?>
    

    So the add_shortcode action will be executed inside the constructor of the class when the class is instantiated.

    There is one distinctive difference when adding in action hooks or filters inside a class in WordPress. When specifying the callback function you have to specify that you want to access the callback function inside of **this** class. To do this you use the following syntax.

    add_shortcode('say_hello',  array($this, 'sayHelloShortcode'));
    

    Whereas before you just used the string name of the callback…

    add_shortcode('say_hello', 'sayHelloShortcode');
    

    That’s really the only difference. After this you can create as much as you want and add as many functions as you want just as you were doing to your functions.php file and you can have the same functionality. Only now this piece of functionality is nicely wrapped up in your class. For example, if we wanted to extend the shortcodes class by adding more shortcodes, we can just add another “add_shortcode” to our constructor and add the callback function.

    <?php
    class Shortcodes {
        function __construct() {
            add_shortcode('say_hello',  array($this, 'sayHelloShortcode'));
            add_shortcode('say_something_else',  array($this, 'saySomethingElseShortcode'));
        }
    
        function sayHelloShortcode($atts, $content = null) 
        {
            return 'I am happy to say hello!';
        }
    
        function saySomethingElseShortcode($atts, $content = null) 
        {
            return 'Something else';
        }
    }
    ?>
    

    The other great part of this is that if you use classes to do other things like register custom post types, or add meta boxes, you can give your functions really simple names like “register” or “add” and there’s no risk having a conflicting function name from some other plugin or anywhere else because your function is wrapped up this class. You could use “register” as a function name in each one of your classes. That’s great! If you tried to do this functions.php you’d get a duplicate function definition.

    But there’s one important final step we have to do and that’s actually create an instance of this class so that the code will actually run because the PHP classes don’t run by themselves they have to be declared and called. But this is easy enough. You can just create a variable and give it any name and set it equal to a new instance of the class right after the closing } of your class.

    ...
    
        function saySomethingElseShortcode($atts, $content = null) 
        {
            return 'Something else';
        }
    }
    
    $shortcodes = new Shortcodes();
    

    Then in your functions.php file just include this class and all the code inside of it will run.

    include('Shortcodes.php')
    

    You could even throw all of your classes in a “classes” folder and include it…

    include('classes/Shortcodes.php')
    

    That way you can keep your project directory nice and organized.

    As far as naming your classes go, you’re usually okay but sometimes it’s a good idea to add a prefix to your class name. It’s conceivable that perhaps one of the plugins you have activated has also used a class named “Shortcodes.” So it’s a good idea to add a short sequence of characters to the beginning of your class name (e.g. MYNAME_Shortcodes). I use NBS (for nine bit studios). So my classes have names like NBS_Shortcodes, NBS_Meta, NBS_Portfolio. You just want to make sure that you don’t use the WordPress prefix WP_. WordPress uses this prefix so use your own to make it distinct from core WordPress classes.

    So what are you waiting for? Get into your functions.php file and start grouping some of those functions into classes! You’ll be happy you did 😉

    ,
    Share Tweet Reccomend

    Display an Author Box in WordPress

    This post will teach you how to display an author box in WordPress. You may have seen small excerpts of information at the end of single WordPresss posts that give a little bit of information on the author (and sometimes there’s a picture there as well). Where do these items come from and how do you display these?

    It turns out we’ll be getting the information from the “Users” section of the WordPress dashboard. If you click on the “Users” section, you can find the post author in a list of users. From there you can edit the “Biographical Info” section and that’s where we’ll be pulling the author info from. As for the image, we’ll just use Gravatar (what WordPress uses by default)

    So to start, we will lay out our basic HTML. We’ll have a wrapper author box and an image and that we will float to the left of the author text. Add the following somewhere down near the bottom of your single.php file of your WordPress theme…

    <div class="authorBox">
    <h4>About the Author:</h4>  
    <div class="authorBoxImage">
    </div>
    
    </div>
    

    Now we are going to want to add in the WordPress functions that we can call to get the post author information. Add following code to our markup…

    <div class="authorBox">
    <h4><?php printf( __( 'About the Author:', 'ninebit' ).' %s', get_the_author() ); ?></h4>  
    <div class="authorBoxImage">
    <?php echo get_avatar(get_the_author_meta('ID'), 48); ?> 
    </div>
    <?php the_author_meta('description'); ?>  
    </div>
    <div class="clearout"></div>
    

    So far so good. Note that number 48 when we’re calling get_avatar(). What that is saying is make the avatar 48px by 48px. If you wanted to make the avatar larger or smaller, you could pass in a different number here.

    We’ve got our information down on the page, but it does not yet have any styling. So to style it up we’ll have to add the following CSS somewhere to our stylesheet…

    .authorBox {
      padding: 10px 10px 20px 10px;
      overflow: auto;
      border: 1px solid #eee;
      -moz-border-radius: 5px;
      border-radius: 5px;
      -webkit-border-radius: 5px;
      box-shadow: 0 0 2px #eee;
      -moz-box-shadow: 0 0 2px #eee;
      -webkit-box-shadow: 0 0 2px #eee;
    }
    .authorBox .authorBoxImage {
      float: left;
      margin-right: 10px;
      border-width: 2px;
      border-style: solid;
      border-color: #fcfcfc;
      box-shadow: 0 0 4px #999;
      -moz-box-shadow: 0 0 4px #999;
      -webkit-box-shadow: 0 0 4px #999;
    }
    

    The styling is fairly basic. If you wanted to add more bells and whistles to spice things up you could certainly do so.

    Now if you go to one of your blog posts in your WordPress site, you should be able to see the post author’s avatar and information at the bottom of the post.

    , ,
    Share Tweet Reccomend

    Add Simple Infinite Scrolling to Your WordPress Site

    This post will show you how to do some simple infinite scrolling for WordPress — or really, with a few small tweaks, any other system for that matter. A lot of times on websites when you have multiple pages of results you will see pagination at the bottom of the page with page 1,2,3 etc. and there will often be first, next, previous and last links in there as well. WordPress does this when blog posts, search results, comments and a number of other sets of results in a WordPress site are broken up into different pages. A lot of WordPress themes will show only the “Previous Posts “and “Next Posts” links by default (referred to as “paging”) but some themes will extend functionality beyond this to full on pagination.

    Not all users are super exited about having to click links continuously to go to the next page of results. What infinite scrolling does is get the content found on those pages and append it to the current page so the user never has to click on the pagination links… making for a really nice user experience. You may have seen it on other websites you have visited. This tutorial will show you how to implement it in your own WordPress site.

    99% of all WordPress themes’ index.php file has a call to get_header(), get_sidebar() and get_footer() (so I’m kinda assuming yours does as well). In your WordPress theme’s index.php file place the following code right before your call to get_footer();

    <div class="xhrStatus"></div>
    <script type="text/javascript">
    jQuery(document).ready(function($){
    				
    var currentPage = 2;
    var containerItemSelector = "#main";
    var postItemSelector = "article";
    
    $(window).scroll(function() {
    	
      if($(window).scrollTop() + $(window).height() == $(document).height()) {
    
        $.ajax({	
          type: "GET",
          url: "<?php echo $_SERVER["REQUEST_URI"] ?>?paged=" + currentPage,
          data: "",
          success: function(results) {
            var item = $(containerItemSelector + " > " postItemSelector, results);
            item.each(function() {
              $(containerItemSelector).append($(this));
            });
           currentPage++;
    
          },
          error: function(results) {
            if(results.status == 404) {
              $(".xhrStatus").html('No more posts to show...');
            }
            else {
              $(".xhrStatus").html('Error retriving posts...');
            }
          }
    
        });
      }
    
    });
    
    });
    </script>
    

    Now, there are a couple of variables that you’ll probably have to change to get infinite scrolling working properly on your site. These are the “containerItemSelector” and the “postItemSelector” variables. You can find them somewhere near the top of the above block of code. These variables tell the infinite scrolling code which container HTML DOM Element to put the next pages of posts in and giving it a wrapper for each post.

    Let’s take a look at a very simple sample index.php file to illustrate what is being talked about here…

    <?php get_header(); ?>
    
    <div class="blog">
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
       <div class="postContent">
          <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
          <?php the_content(); ?>   
      </div>
      <?php endwhile; ?>
      <?php else: ?>
      <div class="postContent">
        <h2>Not found</h2>
        <p>Sorry, no posts were found</p>
      </div>      
    <?php endif; ?>
    </div>
    
    <?php get_sidebar(); ?>
    
    <?php get_footer(); ?> 
    

    So in the instance above, the div with the class “blog” is the wrapper element that we will be adding new posts to and each of those items are contained within a div with a class “postContent”. So we’d want to change our variables to the following…

    var containerItemSelector = ".blog";
    var postItemSelector = ".postContent";
    

    So the entirety of the code of index.php would look like the following…

    <?php get_header(); ?>
    
    <div class="blog">
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
       <div class="postContent">
          <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
          <?php the_content(); ?>   
      </div>
      <?php endwhile; ?>
      <?php else: ?>
      <div class="postContent">
        <h2>Not found</h2>
        <p>Sorry, no posts were found</p>
      </div>      
    <?php endif; ?>
    </div>
    
    <?php get_sidebar(); ?>
    
    <div class="xhrStatus"></div>
    <script type="text/javascript">
    jQuery(document).ready(function($){
    				
    var currentPage = 2;
    var containerItemSelector = ".blog";
    var postItemSelector = ".postContent";
    
    $(window).scroll(function() {
    	
      if($(window).scrollTop() + $(window).height() == $(document).height()) {
    
        $.ajax({	
          type: "GET",
          url: "<?php echo $_SERVER["REQUEST_URI"] ?>?paged=" + currentPage,
          data: "",
          success: function(results) {
            var item = $(containerItemSelector + " > " postItemSelector, results);
            item.each(function() {
              $(containerItemSelector).append($(this));
            });
           currentPage++;
    
          },
          error: function(results) {
            if(results.status == 404) {
              $(".xhrStatus").html('No more posts to show...');
            }
            else {
              $(".xhrStatus").html('Error retrieving posts...');
            }
          }
    
        });
      }
    });
    
    });
    </script>
    <?php get_footer(); ?> 
    

    What the code above does is execute an AJAX call to do a “GET” on the next page of results when the user has scrolled to the bottom of the page. The URL that we are getting the results from is represented by the “url” property in the $.ajax block of code. The PHP variable of this property will get the current URL and will get ?paged=[value of the currentPage variable] appended to the end of it. The value of the currentPage variable will start at 2 (since we are already on page 1) and will be incremented every time we do a successful GET of results.

    This URL is WordPress’ structure for breaking up content into different pages. If you wanted to add infinite scrolling to a site being run on another system you could use a similar technique, but you’d just have to provide the proper URL for how that system divided things up into pagination.

    Note too that we have also added an extra <div> with a class of “xhrStatus” right above the start of our <script> block. We are going to use this div to provide messaging if an error occurs in trying to get the next page of results. If we have reached the end of the results and there are no more posts to show, the server will return a 404 error.

    If you wanted to, you could change the HTML element where this message gets displayed. You’d simply have to edit the selector value in jQuery where the message gets outputted to the one that you want.

    If you wanted to implement infinite scrolling on different pages (e.g. a page template with custom post type results), you could simply add the above code to that page as well and make any necessary modifications.

    Happy scrolling!

    , , , , ,
    Share Tweet Reccomend

    Simple Social Sharing Links for WordPress Without a Plugin

    Today I am going to show you how to create very simple social sharing links for your WordPress blog. We all know that there are a gazillion different WordPress plugins out there to handle social media, but these may not always give you the exact customization that you want. Maybe you want to have text-only “share” links and the plugin does not support this. Maybe you want to use different icons than the ones the plugin provides. Maybe you want to format/position these icons differently from how the plugin does it by default. If this describes your situation, this post will help you get off to a good start with that.

    So below are some basic WordPress ready sharing links for some popular social media websites. Please note that these links will work at the time this post was written. Websites often change their APIs and it is possible that the URLs to share out content on these social sites may have changed since the writing of this post… so be sure to check that all of these examples still work. If any do not, consult the website of the social platform in question and look for any advice on blogs and forums on how to change the link to something that will work with an updated API. And please do let me know if any of these do not work as well. 🙂

    I have just kept the format of the links as plain text since it’s the most basic HTML that most people probably understand best. All you have to do is simplly paste the following code into the index.php or single.php or any other .php file of your WordPress theme. From there you can format and style these links however you like.

    <a href="https://facebook.com/sharer.php?s=100&p[title]=<?php the_title(); ?>&p[url]=<?php the_permalink(); ?>" target="_blank">Facebook</a>
    <a href="https://twitter.com/home/?status=<?php the_title(); ?>%20<?php the_permalink(); ?>" target="_blank">Twitter</a>
    <a href="https://plus.google.com/share?url=<?php the_permalink(); ?>" target="_blank">Google+</a>
    <a href="https://digg.com/submit?phase=2&amp;url=<?php the_permalink(); ?>&amp;title=<?php the_title(); ?>" target="_blank">Digg</a>
    <a href="https://stumbleupon.com/submit?url=<?php the_permalink(); ?>&amp;title=<?php the_title(); ?>" target="_blank">StumbleUpon</a>
    <a href="https://delicious.com/post?url=<?php the_permalink(); ?>&amp;title=<?php the_title(); ?>" target="_blank">Delicious</a>
    <a href="https://reddit.com/submit?url=<?php the_permalink(); ?>&amp;title=<?php the_title(); ?>" target="_blank">Reddit</a>
    

    And that’s all there is to it!

    , , ,