【问题标题】:Display Posts from Category Shortcode显示类别简码中的帖子
【发布时间】:2014-08-02 07:11:54
【问题描述】:

我正在尝试在 Wordpress 中创建一个简码,以显示来自某个类别(ID=1361...我们的播客类别)的帖子列表。当我使用下面的代码时,它只显示短代码文本([pages_posts]),而不是帖子列表。有什么想法吗?

// Podcast Page Listing shortcode
function podcast_pages_posts() {
$args = array(
    'post_type' => 'post',
    'posts_per_page'=> -1,
    'cat'=> 1361,
);

$podcast_pages_posts = new WP_Query( $args );

if( $podcast_pages_posts->have_posts() ):
    $ppp_output = '<ul>';
    while ( $podcast_pages_posts->have_posts() ) : $podcast_pages_posts->the_post();
        $ppp_output .= '<li><a href="' . get_permalink() . '" title="' . get_the_title() . '">' . get_the_title() . '</a></li>';
    endwhile; 
    $ppp_output .= '</ul>';
endif;

return $ppp_output;
wp_reset_postdata();

}
add_shortcode( 'pages_posts', 'podcast_pages_posts' );

这是一个无法正常工作的页面:http://www.churchmarketingsucks.com/developer-test/ 这是同一站点上另一个正在运行的短代码的页面(它是底部的列表),所以我认为该站点并没有完全拒绝短代码:http://www.churchmarketingsucks.com/cmp/

【问题讨论】:

  • 澄清一下,这段代码在你当前活动主题的functions.php文件中吗?
  • 另外,return 声明之后你不能有任何东西
  • @celeriko 是对的,您应该在返回之前运行wp_reset_postdata();(尽管大多数人使用 wp_reset_query() 效率低下,但值得称赞)。您能否通过可能返回静态字符串来验证此短代码是否正常工作,代码看起来不错。
  • @celeriko - 这是关键!我像个白痴一样,在我的 MOBILE 主题中使用 functions.php 而不是我的主题。 #fail 我还按照建议将 wp_reset_query() 移到了返回上方。现在一切正常!多谢你们!我怎样才能正确地将其标记为已回答?我要标记原始帖子吗?
  • @user2805240 发生在我们最好的人身上,很高兴我能提供帮助

标签: wordpress function shortcode


【解决方案1】:

我一直在修补同样的问题,并发现此解决方案可行。放置在functions.php 文件中。然后将短代码放在您的页面中,例如 [homepage_info id="234"]

// shortcode for specific category.  Use on homepage (or wherever) to display a list of categories of posts
function quick_info_shorty( $atts ) {
    extract( shortcode_atts( array(
        'id' => 17      // Add the *default category id
    ), $atts ) );

    $posts = get_posts( array(
        'posts_per_page' => -1,
        'post_status'    => 'publish',
        'cat'       => $id,
    ) );

    $return = '';
    $return .= '<div class="homepage_info_box">';

    foreach ( $posts as $post ) {
        $permalink = get_permalink($post->ID);
        $return .= '<a class="item" href="' . $permalink . '">' . apply_filters( 'the_title', $post->post_title ) . '</a>';
    } 

$return .= '</div>';
return $return;
}
add_shortcode( 'homepage_info', 'quick_info_shorty' );  
// place in page: [homepage_info]   Simple & clean for clients
// OR
// [homepage_info id="x"]           (x = id of category/categories other than *default category id.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    相关资源
    最近更新 更多