如何自定义wordpress短代码功能,通过短代码变量获取每个类别的帖子?

时间:2017-02-14 10:56:32

标签: wordpress function categories shortcode posts

我使用以下代码创建一个WordPress短代码[educposts]来显示名为" education"的类别的帖子。

如何将此短代码功能设置为灵活,可以通过更改此类短信代码来显示任何类别[posts = education]或[posts = blog]

由于

/*** show post category ***/
function pwp_postsbycategory() {
$the_query = new WP_Query( array( 'category_name' => 'education', 'posts_per_page' => 5 ) ); 

if ( $the_query->have_posts() ) {
    $string .= '<ul class="postsbycategory widget_recent_entries">';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        if ( has_post_thumbnail() ) {
            $string .= '<li>';
            $string .= '<a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_post_thumbnail($post_id, array( 75, 75) ) . get_the_title() .'</a></li>';
        } else { 
            // if no featured image is found
            $string .= '<li><a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_title() .'</a></li>';
        }
    }
} else {
    // no posts found
}
$string .= '</ul>';

return $string;

/* Restore original Post Data */
wp_reset_postdata();
}
// Add a shortcode
add_shortcode('educationposts', 'pwp_postsbycategory');
/*** show post category ***/

1 个答案:

答案 0 :(得分:0)

我通过在函数中设置$ atts来解决它。

/*** show post category ***/
function pwp_postsbycategory($atts) {
$the_query = new WP_Query( array( 'category_name' => $atts['cat'], 'posts_per_page' => 5 ) ); 

if ( $the_query->have_posts() ) {
    $string .= '<ul class="postsbycategory widget_recent_entries">';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        if ( has_post_thumbnail() ) {
            $string .= '<li>';
            $string .= '<a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_post_thumbnail($post_id, array( 75, 75) ) . get_the_title() .'</a></li>';
        } else { 
            // if no featured image is found
            $string .= '<li><a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_title() .'</a></li>';
        }
    }
} else {
    // no posts found
}
$string .= '</ul>';

return $string;

/* Restore original Post Data */
wp_reset_postdata();
}
// Add a shortcode
add_shortcode('posts', 'pwp_postsbycategory');
/*** show post category ***/