[英]PHP Shortcode - How to accept category argument for WP blog posts
我有一些 PHP 可以在 Wordpress 中按類別顯示博客文章片段,但我無法讓它接受該類別的參數。
無論我在短代碼的“pageCategory”部分中添加什么內容,短代碼都會顯示所有博客文章。
但是,如果我將 'pageCategory' => ' ' 硬編碼到特定類別,它確實會顯示特定類別的帖子。
如何讓這個函數接受變量類別?
function wpb_postsbycategory($atts) {
$a = shortcode_atts( array(
'pageCategory' => ''
), $atts );
// the query
$the_query = new WP_Query( array(
'category_name' => $a['pageCategory'],
'posts_per_page' => 15
) );
// The Loop
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( 50, 50) ) . 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 .= '<li>No Posts Found</li>';
}
$string .= '</ul>';
return $string;
/* Restore original Post Data */
wp_reset_postdata();
}
// Add a shortcode
add_shortcode('categoryposts', 'wpb_postsbycategory');
短代碼
[categoryposts pageCategory='aCategory']
解決了。 對於任何在同一問題上苦苦掙扎的人,我刪除了所有的 camelCase 並用下划線替換它
例子:
從'category_name' => $a['pageCategory'],
到'category_name' => $a['page_category'],
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.