如何自定义WordPress短代码功能,通过shortcode获取每个类别的帖子变量?
问题描述:
我使用下面的代码来创建一个WordPress简码[educationposts]来显示名为“education”的类别的帖子。如何自定义WordPress短代码功能,通过shortcode获取每个类别的帖子变量?
如何设置这个简码功能是灵活的,因为可以通过改变这样的[帖=教育]简码或[帖=博客]
感谢
/*** 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 ***/
答
我解决它通过表现出任何类别设置$ atts in函数。
/*** 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 ***/