如何将WordPress的the_category()输出转为PHP字符串存入变量
问题原因
WordPress 中所有 the_ 前缀的模板函数默认都是直接打印输出内容,不会返回字符串,所以你直接用 $the_category = the_category(); 是拿不到HTML内容的,内容会直接提前输出到页面,变量最终是空值。
解决方法
1. 分类输出转字符串
你可以用 get_the_category_list() 函数替换 the_category(),这个函数会直接返回分类的HTML结构,而不是直接输出:
// 三个参数分别是:分隔符、是否显示父级分类、当前文章ID(循环内可以留空) $the_category = get_the_category_list( ', ' );
如果你需要和原the_category()完全一致的输出效果,也可以用输出缓冲捕获内容:
ob_start(); the_category(); $the_category = ob_get_clean();
2. 特色图片输出转字符串
你现在用的get_the_post_thumbnail()本身就是返回HTML字符串的版本,但是你代码里的写法有两个问题:
- 图片尺寸参数要加引号,
medium是字符串不是常量 - 这个函数返回的是完整的
<img>标签,不是图片URL,你原来的代码里把它放到img的src属性里是错误的,直接输出返回值就行。
修改后的完整代码
function more_post_ajax(){ $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3; $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0; header("Content-Type: text/html"); $args = array( 'suppress_filters' => true, 'post_type' => 'post', 'posts_per_page' => $ppp, 'paged' => $page, ); $loop = new WP_Query($args); $out = ''; if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post(); $the_permalink = get_the_permalink(); // 获取特色图片完整img标签 $the_post_thumbnail = get_the_post_thumbnail( 'medium' ); // 获取分类HTML字符串 $the_category = get_the_category_list(); $the_title = get_the_title(); $the_excerpt = get_the_excerpt(); if ( has_post_thumbnail() ) : // 直接用返回的img标签,不用自己写img标签 $thumbnail = '<div class="card-img-wrap"><a href="'.$the_permalink.'" title="'.$the_title.'" class="stretched-link">'.$the_post_thumbnail.'</a></div>'; endif; $out .= '<div class="col-md-4 col-sm-2"> <article itemscope="" itemtype="http://schema.org/Article"> <div class="card shadow mb-3">'.$thumbnail.' <div class="card-body"> <div class="postcat text-muted text-center">'.$the_category.'</div> <h4 class="posttitle text-center" itemprop="headline" title="'.$the_permalink.'" rel="bookmark"><a href="'.$the_permalink.'">'.$the_title.'</a></h4> <div class="postexcerpt text-center mb-3">'.$the_excerpt.'</div> <div class="card-footer"> <div class="social-icons"> <ul class="unstyled"> <li class="social-facebook"><a href="//www.facebook.com/sharer.php?u='.$the_permalink.'" title="Share to Facebook" target="_blank"><i class="fab fa-facebook" aria-hidden="true"></i></a></li> <li class="social-twitter"><a href="//twitter.com/home?status='.$the_permalink.'" title="Share to Twitter" target="_blank"><i class="fab fa-twitter" aria-hidden="true"></i></a></li> <li class="social-pinterest"><a href="//pinterest.com/pin/create/link/?url='.$the_permalink.'" title="Share to Pinterest" target="_blank"><i class="fab fa-pinterest-p" aria-hidden="true"></i></a></li> </ul> </div> </div> </div> </div> </article> </div> '; endwhile; endif; wp_reset_postdata(); die($out); }
额外说明
get_the_category_list()可以传参数自定义分类之间的分隔符,比如传' / '就会用斜杠分隔多个分类- 如果需要自定义分类HTML结构,也可以用
get_the_category()拿到分类数组,自己循环拼接HTML,灵活度更高
内容的提问来源于stack exchange,提问作者MSquaredSTL
相关产品推荐
相关产品推荐

