Hiện tại, em không muốn xài cái bài viết mới nhất trong widget có sẵn vì nó không lấy được theo category mà nó lấy hết, bây giờ em muốn nếu là trang chủ thì nó lấy bài viết random ngẫu nhiên, còn nếu là trang chuyên mục nó sẽ lấy tất cả bài viết mới. Bạn nào có code chèn vào function.php để tạo Shortcode xong vào widget tạo file html text cái mình gọi Shortcode đó ra để lấy danh sách bài viết theo mình yêu cầu ở trên không?
Thêm code sau vào function.php của themes nhé: PHP: //[itseovn_postsbycategory page="5"]function itseovn_postsbycategory($args, $content) { $string .="<div class='cs-witem'>"; if ( is_front_page()) { $the_query = new WP_Query( array( 'orderby' => 'rand', 'posts_per_page' => $args['page'] ) ); $string .= '<h2 class="widget-title">Có thể bạn quan tâm?</h2>'; }else{ $the_query = new WP_Query( array( 'orderby' => 'desc', 'posts_per_page' => $args['page'] ) ); $string .= '<h2 class="widget-title">Bài viết mới</h2>'; } if ( $the_query->have_posts() ) { $string .= '<ul class="postsbycategory widget_recent_entries">'; while ( $the_query->have_posts() ) { $the_query->the_post(); $string .= '<li><a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_title() .'</a></li>'; } }else{ } $string .= '</ul>'; $string .="</div>"; return $string; wp_reset_postdata();}add_shortcode('categoryposts', 'itseovn_postsbycategory');add_filter('widget_text', 'do_shortcode'); Để gọi nó ra ngoài thì bạn tạo 1 widget tùy biến HTML và chèn shortcode Mã: [itseovn_postsbycategory page="5"] Hoặc có thể tùy biến lại lấy theo category thì thay câu query bằng: Lấy theo category name truyền vào PHP: $the_query = new WP_Query( array( 'category_name' => $args['catename'], 'posts_per_page' => $args['page'] ) ); Gọi: [itseovn_postsbycategory catename="tên category" page="5"] Lấy theo category id truyền vào PHP: $the_query = new WP_Query( array( 'category_name' => $args['cateid'], 'posts_per_page' => $args['page'] ) ); Gọi: [itseovn_postsbycategory cateid="cate id" page="5"] Tự động lấy theo category hiện tại PHP: $current_cat_id = get_query_var('cat');$the_query = new WP_Query( array( 'cat' => $current_cat_id, 'posts_per_page' => $args['page'] ) );