1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

[Docs] Making Custom Widgets

Discussion in 'Design and Layout' started by Nick, Nov 18, 2009.

  1. Nick

    Nick Well-Known Member

    You know how to use the Posts Widget plugin, but how do you show, for example, the top 10 best posts ever?

    To do that, you'll need the Text Widget plugin as well as the Widgets and Posts Widget plugins. The Text Widget plugin simply lets you make an unlimited number of empty boxes to paste text or code into.

    1. Go to Admin -> Text Widget
    2. Give your widget a name, e.g. "Best Posts Ever".
    3. Below that, check the PHP box.
    4. In the box, paste the following:

    PHP:
    $pw = new PostsWidget();

    $the_posts $pw->getPostsWidget($h'top-all-time'); 

    echo 
    $pw->getPostsWidgetItems($h$the_posts'top-all-time'); 
    The first line lets us use the code from the Posts Widget plugin.
    The second line gets the "top-all-time" posts.
    The third line displays the posts as a list in the sidebar.

    If you save the widget and view your site, you should see your new sidebar box. If it doesn't show, try these:

    1. Go to Admin -> Widgets and make sure your Text Widget is turned on.
    2. Go to Admin -> Maintenance and clear the HTML cache.

    Okay, so now you have your new widget, how about a box for the last 30 days or one for "upcoming" posts? Easy just change the filter (i.e. the two occurrences of top-all-time in the above code.

    Filters:

    top
    new
    upcoming
    top-24-hours
    top-7-days
    top-30-days
    top-365-days
    top-all-time

    Going Further...

    If your text widgets are getting big and hard to edit, you might prefer to move the code into a template.

    To do that, you'll still need text widgets to point to your templates. Here's how:

    1. Make a new text widget with the following code:

    PHP:
    $h->displayTemplate('all_time_widget');
    2. In your own theme folder make a new .php template containing this code:

    PHP:
    <?php
    $pw 
    = new PostsWidget(); 
    $top_posts $pw->getPostsWidget($h'top'); 
    ?>

    <ul class='widget_body posts_widget_items'>
        <?php echo $pw->getPostsWidgetItems($h$top_posts'top'); ?>
    </ul>
    That's it! You can use these methods to make all kinds of custom widgets.
     
    Last edited: Jan 7, 2010

Share This Page