Question

I need to create a custom short code to allow me to dynamically fill in 3 values (post title, post date, link to post) for the top post in a given category.

I was thinking of something like: [top_post cat="5"]

It would output something like this:

<div class="three_fourth ">
<h2>[POST_TITLE] - [POST_DATE]</h2>
</div>
<div class="one_fourth last">
<a class="button" href="[LINK_TO_POST]" style="background-color: #c62b02">
</div>

Is this doable?

Thanks for the help.

Was it helpful?

Solution

In functions.php, something like this...

function shortcodeFunction( $atts ) {
  extract( shortcode_atts( array(
    'cat' => '' //the attr in the shortcode
  ), $atts ) );
  if($cat){ //$cat is extracted from $atts
      $args = array(
      'category' => $cat,
      'orderby' => 'post_date',
      'order' => 'DESC', // Show only latest, rejig as needed
      'posts_per_page' => 1 // Only show 1
    )
    $allPosts = get_posts($args);
    $return = '';
    foreach($allPosts as $p){ // Bog standard get post foreach
      $thePost = get_post($p);
      $date = $thePost->post_date;
      $date = strtotime($date);
      $date = gmdate('jS F Y',$date);
      $link = get_permalink($thePost->ID);
      $return .= '<div class="three_fourth "><h2>'.$thePost->post_title.' - '.$date.'</h2></div><div class="one_fourth last"><a class="button" href="'.$link.'" style="background-color: #c62b02"></div>';
    }
} return $return;
} else {
    return false;   
}
add_shortcode( 'top_post', 'shortcodeFunction' );

OTHER TIPS

You can using plugin to do this

http://wordpress.org/plugins/list-category-posts/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top