我需要一个短代码,列出某个类别的所有帖子。
我发现这个php代码适用于页面模板,但是只要我在短代码中添加它就不起作用(我真的需要它以短代码格式):
<ul>
<?php
$catPost = get_posts(get_cat_ID("31")); //change this
foreach ($catPost as $post) : setup_postdata($post); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach;?>
</ul>
那我该怎么做呢?
答案 0 :(得分:0)
它应该是这样的(将它添加到你的functions.php文件中)
function posts_in_category_func( $atts ) {
$category_id = $atts['cat'];
?>
<ul>
<?php
$args = array( 'category' => $category_id, 'post_type' => 'post' );
$catPost = get_posts($args);
foreach ($catPost as $post) : setup_postdata($post); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach;?>
</ul>
<?
}
add_shortcode( 'posts_in_category', 'posts_in_category_func' );
你可以像[posts_in_category cat=1]
答案 1 :(得分:0)
这是Amin的更新和经过测试的版本。 T的代码。添加到您的functions.php文件中。
/*
* Output a simple unordered list of posts in a particular category id
* Usage e.g.: [posts_in_category cat="3"]
*/
function posts_in_category_func( $atts ) {
$category_id = $atts['cat'];
$args = array( 'category' => $category_id, 'post_type' => 'post' );
$cat_posts = get_posts($args);
$markup = "<ul>";
foreach ($cat_posts as $post) {
$markup .= "<li><a href='" . get_permalink($post->ID) . "'>" . $post->post_title . "</a></li>";
}
$markup .= "</ul>";
return $markup;
}
add_shortcode( 'posts_in_category', 'posts_in_category_func' );