Wordpress Shortcode为类别中的最新帖子

时间:2014-03-04 00:36:47

标签: php wordpress wordpress-plugin

我需要创建一个自定义短代码,以允许我动态填写给定类别中的顶部帖子的3个值(帖子标题,发布日期,发布链接)。

我想的是:[top_post cat =“5”]

它会输出如下内容:

<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>

这可行吗?

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

在functions.php中,就像这样......

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' );

答案 1 :(得分:0)

您可以使用插件执行此操作

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