2017-02-14 108 views
0

我使用下面的代碼來創建一個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 ***/ 

回答

0

我解決它通過表現出任何類別設置$ 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 ***/ 
相關問題