Patrick Galbraith

Web developer - Adelaide, Australia

Recent Posts Plus (WordPress Widget) 357

An advanced version of the WordPress Recent Posts widget, allows display of thumbnails, post excerpt, author, comment count, and more. Provides options to trim the title and override the post order and type. Also includes a simple template parser so you can override the default output.

Download: http://wordpress.org/extend/plugins/recent-posts-plus




1: Title

Default: Recent Posts

This field sets the title of the widget. It works the same as every other widget.

2: Number of posts

Default: 5

Changes how many posts are displayed in the widget. Enter ‘-1′ to display all posts.

3: Include post thumbnail

Default: no

Displays the post thumbnails of each post.

If this option is hidden you may not have a theme with post-thumbnails enabled. You can manually enable and add post-thumbnails to each post or you can download the Default Thumbnail Plus plugin automatically display a default image.

4: Include post excerpt

Default: no

Displays the post excerpt of each post.

5: Show expert options

Default: no

Show/hide the expert options panel. These options should be used with more care.

6: Limit post title

Default: (no limit)

Limits the numbers of characters or words to display of each posts title.
Example: For the post title “Look at this title” setting this option to 7 chars would result in “Look at…”

7: Limit post excerpt

Default: (no limit)

Limits the numbers of characters or words to display of each posts excerpt.

8: Limit ellipsis

Default: …

Sets the string to append to post titles or excerpts that have been shortened.

9: Post date format

Default: M j

Sets the PHP date format to use when displaying the post date.
See http://php.net/manual/en/function.date.php for overview of the options available.

Note: the date format can be overriden in the output template, which allows for multiple date formats in one entry, see section “12: Widget output template”.

10: Thumbnail size

Default: 50 x 50

Sets the size of the post thumbnail in pixels.

11: WP_Query options

This is an advanced option that modifies what posts are shown in the widget. This option specifies extra arguments to use in the WP_Query request and as such is very flexible even allowing this widget to show pages rather than posts, show oldest posts first, or filter posts by tag or category. The WP_Query options must be specified in valid JSON format (validate here http://jsonlint.com/).

These are the default args that are sent to WP_Query:

{
"post_type": "post",
"posts_per_page": <same as Number of posts setting>, 
"orderby": "date",
"order": "DESC"
}

List of options:

{
"post_type": "post", //post, page, revision, attachment, any
"post_status": "publish", //publish, pending, draft, auto-draft, future, private, inherit, trash, any.
"posts_per_page": "5", //overrides number of posts setting
"offset": "3", //number of posts to skip over 
"post__in": [2, 3, 4], //only show posts 2, 3 and 4
"post__not_in": [2, 3, 4], //exclude posts 2, 3 and 4
"ignore_sticky_posts": "1", //ignore sticky posts or not. Default value is 0, don't ignore (requires WordPress 3.1+).
"caller_get_posts": "1", //ignore sticky posts or not. Deprecated as of Version 3.1 in favor of 'ignore_sticky_posts'.
"author": "1", //author ID
"author_name": "john", //post author's name, use 'user_nicename' (NOT name)
"orderby": "date", //none, ID, author, title, date, modified, parent, rand, comment_count, meta_value, meta_value_num  
"order": "DESC", //ASC or DESC
"tag": "cooking,baking", //display posts that have "either" of these tags
"tag": "bread+baking+recipe", //display posts that have "all" of these tags
"tag_id": "13",
"cat": "1, 2, -3", //category ID 1, 2 but not 3
"category_name": "articles,news",
"year": "2011",
"meta_query" : [] //see below
}

For a full listing see http://codex.wordpress.org/Class_Reference/WP_Query

Ordering by custom fields

You can change the sort order to be based on a specified custom field using meta_value and meta_value_num as the orderby option.

Note: The difference between meta_value and meta_value_num is that the meta_value_num is sorted as a numeric value (i.e. meta_value would be ordered as a string e.g. 1, 3, 34, 4, 56, 6 whereas meta_value_num would be 1, 3, 4, 6, 34, 56).

The following example would order posts by custom field rating showing in order of highest rated to lowest rated.

{
     "meta_key": "rating",
     "order": "DESC",
     "orderby": "meta_value_num"
}

Utilizing the meta_query option

Note: This option requires WordPress 3.1+

Filter or show posts with a certain custom field value using the meta_query option.

The following example would display posts with a custom field called mood with a value of happy:

{
    "meta_query": [
        {
           "key": "mood", //Custom field key
           "value": "happy", //Custom field value
           "type": "CHAR", //Custom field type. Possible values are 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'
           "compare": "=" //Operator to test. Possible values are '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'
        }
    ]
}

The following example would display posts if they have a custom field rating of between 5 and 10 or if they have a custom field mood with a value of happy:

{
    "meta_query": {
        "relation": "OR", //Possible values are 'AND', 'OR'
        "0": {
            "key": "rating",
            "value": [5, 10],
            "type": "NUMERIC",
            "compare": "BETWEEN"
        },
        "1": {
            "key": "mood",
            "value": "happy",
            "type": "CHAR",
            "compare": "="
        }
    }
}

12: Widget output template

This is an advanced option that modifies the output of the widget. You can modify the output with template tags and add custom classes or tags for styling.

By default the widget outputs posts in this format:

<li>
{THUMBNAIL}
<a title="{TITLE_RAW}" href="{PERMALINK}">{TITLE}</a>
{EXCERPT}
</li>

You can modify the output by including the following template tags:

{ID} The post ID
{THUMBNAIL} The post thumbnail IMG tag if it exists, otherwise nothing
{TITLE_RAW} The post title
{TITLE} The post title, will be trimmed if it exceeds "Option 6: Limit post title chars"
{EXCERPT_RAW} The post excerpt
{EXCERPT} The post excerpt, will be trimmed if it exceeds "Option 7: Limit post excerpt chars"
{PERMALINK} The post permalink url
{DATE} The post date, the format is defined by the "Option 9: Post date format" setting
{DATE[php_date_format]} As of 1.0.4: Customized date format which overrides the default date format setting. E.g. {DATE[l jS F Y]} would display like "Monday 1st January 2011"
{AUTHOR} The post author name
{AUTHOR_LINK} The post author website url
{AUTHOR_AVATAR} As of 1.0.7: Displays the author's avatar if available
{COMMENT_COUNT} The total number of comments, Trackbacks, and Pingbacks for the post
{META[name]} As of 1.0.5: Displays the value of the specified custom field. E.g. {META[Currently Reading]} or {META[Rating]}. Note: Only returns the first result.
{ELLIPSIS}...{/ELLIPSIS} As of 1.0.9: Overrides option "8: limit ellipsis" for the excerpt. 
                         You can use other templates tags within the {ELLIPSIS} tags but not PHP and it will only be appended to the excerpt if it is truncated. 
                         Example: {ELLIPSIS}... <a href="{PERMALINK}">(more)</a>{/ELLIPSIS}

Using raw PHP in the Widget output template

As of 1.0.7 you can add raw PHP code to the widget output template.

Note: This will require the PHP code you enter to be run though eval which will likely have a small performance penalty. However if you don't enter any PHP code eval will not be run. Be careful not to give untrusted users permission to modify widget settings since it could be a potential security risk.

The following example displays the author's avatar at 32px size:

<li>
<?php echo get_avatar(get_the_author_meta('user_email'), 32); ?>
<a title="{TITLE_RAW}" href="{PERMALINK}">{TITLE}</a>
{EXCERPT}
</li>

You can access some of the existing template tag values with the $widget_ouput_template_params array e.g. $widget_ouput_template_params['{ID}'] contains the current posts ID.


Examples of Styling the Output

The look of the widget output depends a lot on what theme you are using. By default the output looks somewhat like the image below. Thankfully we can improve this with very little effort and a few additions to your themes stylesheet.

The first thing you need to do is go to Appearance -> Editor and select the Stylesheet option on the right (it should be selected by default but just make sure). After that paste one of the following styles at the bottom of the stylesheet depending on the look you want.

Note these are just basic examples you can do a lot more with more with CSS. These examples also depend a lot on the theme you are using, more complex themes may require additional styling. Hopefully these examples can point you in the right direction.

.widget_recent_entries li {
    clear: both;
    margin: 5px 0;
}
.widget_recent_entries .wp-post-image {
    vertical-align: text-top;
    margin: 0 5px 0 0;
}
.widget_recent_entries li {
    clear: both;
    margin: 15px 0;
}

.widget_recent_entries .wp-post-image {
    float: left;
    margin: 0 5px 0 0;
}

.widget_recent_entries li p {
    margin-top: 5px;
    color: #707070;
}
.widget_recent_entries li {
    clear:both;
    margin: 5px 0;
}

.widget_recent_entries .wp-post-image {
    vertical-align: middle;
    margin: 0 5px 0 0;
}

The above example has the thumbnail size set to 25px x 25px.

.widget_recent_entries li {
    clear:both;
    margin: 10px 0;
    text-align: center;
}

.widget_recent_entries .wp-post-image {
    margin: 0 5px 0 0;
}

.widget_recent_entries li a {
    display: block;
}

The above example has the thumbnail size set to 100px x 100px.

COMMENTS

Leave a reply

  1. WP_Query Options (?)
    {
    “post__in”: [1330,1125,970,128,113,1351]
    }
    Widget Output Template (?)
    {THUMBNAIL}{TITLE}{EXCERPT}
    No matter where I put post no. 1351 in the list, he always comes first in the list. Why ? What can I do? Thank you!

  2. Hi Patrick, thanks for your great plug-in. Still the best plug-in for displaying all kind of posts in a nice way. Question, is it possible to show the “read more” tag behind the excerpt instead of below the excerpt? Code I use:
    {DATE}

    {EXCERPT}read more

    Thanks!

  3. me here said

    what code will make the recent post list be alphabetical?

  4. rsspanic said

    Hi, I would like to know how it might be possibler to

    1) show a gray 1 pixel wide frame around the recent posts widget;

    2) show a 281×61 pixel large jpg as a standard header above the widget (but inside the frame above)

    thanks

  5. Goran said

    Like many other I also have the problem to pull latest post from specific category. Iz pulls latest posts from all categories. My querys are fine. Do not know what to do. :(

  6. Peter said

    I am using Version 1.0.11 and it appears to be stripping hyperlinks from excerpts again. I saw this was a problem back in 2011 with version 1.0.5 and was apparently fixed in a version after that. Is this still a bug?

  7. We are using this widget to display “recent news” on all landing pages except for our homepage – Here is our bug: new postings are showing in Safari on Mac but not Chrome on Mac. Still need to test other browsers. I am not a JS expert, so please help. Thank you.

  8. Johnc152 said

    Very informative article post.Really looking forward to read more. Fantastic. eeccafgecbek

  9. Chris said

    How would I put the whole widget within it’s own container? or put it within its own class?

  10. Hi Patrick, I just wanna say: THX for your *AWESOME* plugin! I’ve been using RP+ for a couple of years now – it’s still by far the most flexible solution I’ve ever come across. I hope you’ll keep supporting this genius piece of software for a long, long time! greetings from Vienna, Ritchie

  11. I can’t make this work. I want to hide a category. “cat”: “1, 2, -3″, //category ID 1, 2 but not 3 in the widget query options. not sure how to find the category number of the one I want to hide but I only have 5 categories and I’ve tried minusing all of them and no luck.

  12. I can’t seem to get the offset to work.
    “offset”: “20”,

    It’s still starts at first post

  13. Nevermind. I got it to work. I included a comma after last query option

  14. bahuett said

    if you are using page builder and you want to address recent posts or their images u may want to go this way

    *[class*=’widget_recent’] .wp-post-image {
    yoursettings…..
    }

  15. bahuett said

    (for css of course)

  16. Is there a way to specify which thumbnail to use? For example, my theme has a square thumbnail called “archive-thumb” and I would like to use this rather than the default thumbnail which is rectangular.

  17. I’ve been using the plugin for several years and it’s worked great. Suddenly, the “rand” part isn’t working — it just shows the newest post(s) of the given group. Any ideas as to why? or more, importantly, how to fix it?

  18. Never mind. Figured out that it’s WP Engine that blocks “rand” and I just switched my hosting to them.

  19. Hi i have download and installed this plugin on my site but the widget does not appears on my sidebar, how to fix this issue.. thanks

  20. Hi,

    I want to display the post with three categories. Like
    * Featured
    * Latest
    * Most Popular

    As of now I have added only two post. One with Featured category and another one with Latest catgory.

    But its showing same post in both blogs. Kindly suggest any idea to do this. Looking forward to here from you.

  21. In “Ordering by custom links” chapter, there’s an error:

    “meta_key” => “rating”
    should read:
    “meta_key”: “rating”

  22. Hi Patrick,

    I still use your widget with much pleasure. I’ve one question though. On my website I review books and on the homepage, right in the middle you’ll find the ‘ Absolute aanraders’. Those are the books I recommend to read, I show the cover of 7 books only. They’re the 7 most recent books tagged as ‘ aanrader’. I was wondering if there’s a way to random show 7 covers, instead of just a descending order in date?

  23. Juan said

    Hi!

    I have a custom post type called ‘movies’ and I have a certain taxonomy for these custom posts called ‘esta-semana’….how can I display in the widget the ‘movies’ with the taxonomy ‘esta-semana’

    Thanks very much!

  24. Alex said

    Here’s how I managed to exclude sticky posts from the widget output. Maybe someone will find it useful – it wasn’t exactly easy:

    <li class="hidden">{DATE} {TITLE}

    • Alex said

      Parser has eaten all the markup… Maybe this time (feel free to remove this Patrick):

      <code>
      <li <?php if (in_array($widget_ouput_template_params['{ID}'], get_option( 'sticky_posts' ))) {?>class="hidden"<?php }?>><time datetime={DATE[Y-m-d]}>{DATE}</time> <a title="{TITLE_RAW}" href="{PERMALINK}">{TITLE}</a></li>
      </code>

  25. John said

    First of all thank you for your work!

    I have a small question: Is it possible to display this widget with a php function reference?
    Example:

    I would like to display the output in a center column (not in sidebar)

    Thank you in advance.

  26. John said

    Opps for got my example,

  27. Goose said

    Hello Patrick, i hope you still keep that wonderful plugin alive?! I´m using it in my new webpage and would like to know if it is possible to show ALL the existing posts in a single widget with e.g. 3 or 4 columns. The result should look like a gallery of all existing posts. I´m looking hard for a solution and think with your plugin it maybe could be realized.

    Thank you
    Best regards, Goose

  28. Goose said

    Hi Patrick, thank you for your answer. In the meanwhiel i did it in a different way. I placed your plugin in several single widges and let them skip the newest posts.

    1st widget:
    {
    “orderby”: “date”,
    “order”: “DESC”
    }

    2nd widget:
    {
    “orderby”: “date”,
    “order”: “DESC”,
    “offset”: “3”
    }

    3rd widget:
    {
    “orderby”: “date”,
    “order”: “DESC”,
    “offset”: “6”
    }

    etc…..

    That made it work fine for me. I do not like the wordpress default posts page and want to be able to show only an individual amount of posts. So I built 3 pages only using your plugin and built my own navigation on every page. That is maybe not very professional but it works.

    A much better way would be to get a dynamic navigation on each page which makes it easier to handle more of these manual build pages. But unfortunately my programmer skills are limited and i did not find a really good working navigation plugin for wordpress with the ability to define the number of pages that should be shown.

    best regards, Goose

  29. Laura said

    Hi there, I realize this plugin is not being updated but what i’m trying to do is include posts by a specific author while excluding certain categories that that author’s posts are in.

    The syntax I used was this:

    {“author”: “2”}
    {“cat”: “-3″}

    and what seems to happen is that the author part of that equation gets ignored when I add the category exclusion (it works fine until I add it).

    I just wonder if there is a workaround for this or if I am doing something wrong.

  30. This way you can drive traffic to your website through Word – Press
    blog. Go To And Get A Free Web Page Design For Your Business.
    Based on condition statements, menu items can be shown or hidden using this plug-in.

  31. What’s up, I would like to subscribe for this blog to obtain newest updates,
    so where can i do it please assist.

  32. Hank said

    Hi Patrick,
    Thanks for the great plugin and update to allow for meta_query! I am trying to filter for post custom meta with expiration date. Wondering how to set “value” to current time? Is it possible to use current_time(‘Y-m-d’) as value? Also, what should be the “type”?

    Thanks so much!

  33. En nuestra sociedad encontrara un amplio numero de instaladores de gas de Elche con una dilatada experiencia en el
    campo de la cerrajeria. Cada los trabajadores de la cerrajeria son altamente profesionales y disponen de una amplia experiencia.
    Realizan cualquier labor de cerrajeria, sin embargo, los mas solicitados son estos: reparacion de puertas o
    cambio de cerraduras. La totalidad de los trabajos que confeccionan nuestros instaladores de
    gas de Elche se pueden realizar de forma urgente
    durante las 24 horas, o de forma aplazable.
    El monto de cada tarea es una ganga, pero obedeciendo la calidad absoluta y usando los materiales mas deseables.
    Cada trabajo es realizado de modo eficaz y con rapidez. Por este motivo, todos los clientes
    quedan constantemente dichosos con el trato recibido.
    Nuestra empresa da las gracias a sus usuarios agasajandoles una incondicional garantia de agrado en la integridad de las tareas
    y por esa razon, cada consumidor habla bien sobre nosotros e interceden por nosotros ante sus conocidos.
    Entre las labores que ejecutamos para personas fisicas,
    puede encontrar esencialmente: cambio de cerraduras, sustitucion de bombillos…
    En los trabajos realizadas los trabajadores de nuestra empresa con cajas de seguridad encontramos: la
    colaboracion experto por personas que trabajan para nosotros capacitadas, cambio de alguna parte (dial, cerradura, circuito electronico, etc.), abertura sin estropear la caja fuerte, puesta en funcionamiento de cajas de
    seguridad restablecimiento de clave de seguridad, etc. Todos los
    labores es posible ejecutarse en cualquier lugar, pudiendo ser,
    en una vivienda de una familia, en una empresa, comunidades de propietarios, empresas del gobierno, etc.

    Tambien, existe la posibilidad de realizado de manera inmediata (siempre que
    que sea necesario), desplazandonos a todos los lugares donde
    nos necesite de modo veloz. Puede disponer con nosotros para todos de las tareas mencionadas
    con anterioridad.

  34. Chris said

    Hello and congratulations for the widget!

    I would like to know if i can replace the horizontal line in front of the post title with a bullet – circle or a horizontal line.

    Thank you in advance!

  35. En nuestro negocio podra descubrir un extenso numero de instaladores de gas de en esta zona con una dilatada experiencia en el campo de la cerrajeria.

    Cada uno de profesional de la cerrajeria estan muy cualificados y poseen una
    dilatada experiencia. Elaboran cualquier las labores de cerrajeria, sin embargo, los
    mas comunes son estos: instalar, reparar o sustituir cierres metalicos.
    Todos las labores que confeccionan nuestros profesionales instaladores de gas de en esta zona se pueden hacer con urgencia a cualquier hora del dia, o sin urgencia.
    El precio de cada servicio en muy asequible, pero estimando la calidad total
    y empleando los mejores materiales. Cada tarea se realiza con eficacia y de forma rapida.
    Por este motivo, todos los clientes quedan en todo momento complacidos con el trabajo realizado.
    Nuestro negocio fideliza a sus usuarios ofreciendoles una incondicional garantia de satisfaccion en la totalidad de los servicios
    y por ese motivo, cada consumidor habla bien sobre
    nosotros y nos apoyan a sus amigos. Dentro de las tareas que desarrollamos para personas fisicas, podemos encontrar esencialmente: reparacion de
    puertas, cambio de cerraduras… En las tareas que
    hacen nuestros expertos con calderas de gas natural encontrara:
    el amparo entendida por personas que trabajan para nosotros
    cualificados, reemplazo de alguna parte (circuito electronico, dial, cerradura, etc.), reparacion sin perjudicar la caja fuerte, puesta en funcionamiento de
    cajas de seguridad recuperacion de combinacion de seguridad…

    Cada servicio puede realizarse en cualquier lugar, pudiendo
    ser, en un piso de una familia, en un negocio, comunidades de propietarios,
    organismos del gobierno, etc. Tambien, puede ser hacer de
    forma urgente (siempre que que sea necesario), desplazandonos a todos los lugares sea
    necesario de manera veloz. Podra disponer de nuestros trabajadores para cualquiera
    de las labores mencionadas anteriormente.

  36. Several of the t-shirts come in hoodie style and vice versa.

  37. Remarkable things here. I am very satisfied to peer your post.
    Thanks a lot and I am taking a look ahead to
    contact you. Will you please drop me a e-mail?

  38. Apply that to dwelling human tissue, and it is gonna burn.

  39. Excellent web site. Lots of useful information here.

    I’m sending it to some friends ans also sharing in delicious.
    And certainly, thanks in your sweat!

  40. Hurrah, that’s what I was seeking for, what a data!

    existing here at this web site, thanks admin of this website.

  41. Simply desire to say your article is as astonishing.
    The clarity in your post is just excellent and i can assume you are an expert on this subject.

    Well with your permission let me to grab your feed to keep
    updated with forthcoming post. Thanks a million and please keep up the gratifying work.

  42. Hi admin, i must say you have very interesting content here.
    Your website should go viral. You need initial traffic only.
    How to get it? Search for: Mertiso’s tips go viral

  43. Excellent way of describing, and good piece of writing to take information about my presentation subject
    matter, which i am going to deliver in institution of higher education. https://blogs.umass.edu/natsci397a-eross/economic-benefits-of-urban-green-spaces/

  44. Thank you, I have recently been searching for information about this subject for a while
    and yours is the greatest I have found out so far.
    But, what in regards to the conclusion? Are you certain concerning the
    source?

  45. I intended to post you this very small word to help give many thanks over again for your superb things you’ve shown in this article. It is really extremely open-handed with you giving publicly exactly what many individuals could possibly have offered for sale as an electronic book to get some profit on their own, chiefly considering that you could have done it in case you considered necessary. Those good ideas additionally acted as a easy way to know that someone else have the identical desire similar to my very own to learn a little more on the topic of this problem. I know there are a lot more pleasurable occasions up front for those who look over your website.

  46. I precisely wished to thank you very much once more. I’m not certain the things I would have taken care of in the absence of these points provided by you regarding that area. It absolutely was the frightful setting for me, however , witnessing your expert approach you resolved the issue took me to jump for happiness. I’m just thankful for the guidance and in addition have high hopes you comprehend what an amazing job you have been accomplishing educating most people using your site. Most likely you’ve never come across all of us.

  47. Enter the terms you wish to search for. Enter the terms you wish to search for.

  48. I’ve been exploring for a little bit for any high quality articles or weblog posts on this sort of area .

    Exploring in Yahoo I eventually stumbled upon this web site.
    Reading this information So i’m satisfied to express that I
    have a very just right uncanny feeling I came upon exactly what I needed.
    I such a lot for sure will make certain to do not put out of your mind this web site and
    give it a look on a constant basis.

  49. Ꮃhat’s Going down i’m neԝ to this, I stumbled upon thіs I’ve foսnd It positively helpful аnd it һas aided mе out loads.
    I hope to give a contribugion & aid ⲟther uѕers like іts aided mе.
    Ԍood job.

    Feel free tо surf t᧐᧐ my website :: geolocation

  50. I learn something very complicated on various blogs everyday.

Leave a Reply to Dan Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

PINGBACKS