为自定义文章类型(CPT)与自定义分类法创建短代码列文章标题
自定义文章类型与分类法的短代码修复方案
以下是适配自定义文章类型demo_listing和自定义分类法demo_8的完整短代码实现,解决筛选无效或列出所有文章的问题:
function kat_post_list_func($atts) { // 提取短代码参数,默认cat为空 $atts = shortcode_atts( array( 'cat' => '', ), $atts, 'kat_post_list' ); $category_id = $atts['cat']; $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $posts_per_page = 2; // 构建WP_Query参数 $args = array( 'post_type' => 'demo_listing', 'post_status' => 'publish', 'posts_per_page' => $posts_per_page, 'paged' => $paged, ); // 如果传入了分类ID,添加tax_query筛选 if (!empty($category_id)) { $args['tax_query'] = array( array( 'taxonomy' => 'demo_8', 'field' => 'term_id', 'terms' => intval($category_id), 'operator' => 'IN' ) ); } $query = new WP_Query($args); $total_pages = $query->max_num_pages; $tablo = "<table>"; $tablo .= "<tr>"; $tablo .= "<th>Başlık</th>"; $tablo .= "<th>Yazar</th>"; $tablo .= "</tr>"; if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); $author_name = get_the_author_meta('display_name', get_the_author_meta('ID')); $tablo .= "<tr>"; $tablo .= "<td><a href='" . get_permalink() . "'>" . get_the_title() . "</a></td>"; $tablo .= "<td>" . $author_name . "</td>"; $tablo .= "</tr>"; } wp_reset_postdata(); // 重置查询 } else { $tablo .= "<tr><td colspan='2'>没有找到相关文章</td></tr>"; } $tablo .= "</table>"; $pagination = ''; if ($total_pages > 1) { $pagination = paginate_links(array( 'base' => get_pagenum_link(1) . '%_%', 'format' => '/page/%#%', 'current' => $paged, 'total' => $total_pages, 'prev_text' => __('« Önceki'), 'next_text' => __('Sonraki »'), )); } $output = '<div class="pagination">' . $pagination . '</div>'; return $tablo . $output; } add_shortcode('kat_post_list', 'kat_post_list_func');
关键修改说明
- 替换为WP_Query:放弃原代码中两次
get_posts的逻辑,改用WP_Query直接查询,通过$query->found_posts获取准确的总文章数,避免因get_posts默认返回数量限制导致的分页错误。 - 完善分类筛选逻辑:仅在传入有效
cat参数时添加tax_query,确保未传参数时不会错误筛选;同时明确设置operator为IN,确保匹配指定的自定义分类法术语ID。 - 简化分页处理:直接使用
WP_Query的paged参数自动处理分页偏移,无需手动计算offset,逻辑更可靠。 - 重置查询状态:循环结束后调用
wp_reset_postdata(),避免干扰页面其他WordPress查询的正常执行。
内容的提问来源于stack exchange,提问作者balabanig
相关产品推荐
相关产品推荐

