如何在wordpress短代码中列出某个类别的所有帖子?

问题描述 投票:0回答:2

我需要一个短代码,列出某个类别的所有帖子。

我发现这个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>

那我该怎么办呢?

wordpress shortcode
2个回答
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]那样称呼它


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' );
© www.soinside.com 2019 - 2024. All rights reserved.