如何通过短代码获取Co-Author-Plus数据及代码无输出问题排查
故障原因及修复方案
核心问题点
- 多作者逻辑分支变量未定义:当文章有多个作者时,对应逻辑分支中直接调用了
$coauthor->user_email,但该分支没有遍历$coauthors数组,$coauthor属于未定义变量,触发PHP报错导致无输出 - 文件引入路径错误:直接使用相对路径
include('coauthorplus.php'),如果代码文件放在主题目录下,相对路径会基于站点根入口文件而非主题目录,大概率引入失败,短代码未注册自然无返回 - 缺少插件可用性判断:未预先判断Co-Author-Plus的核心函数是否存在,插件未启用时会触发致命错误,导致页面空白无输出
修复后的完整代码
<?php function coauthorplus_function() { // 先判断Co-Author-Plus插件是否启用 if (!function_exists('get_coauthors') || !function_exists('coauthors_posts_links')) { return ''; } ob_start(); $coauthors = get_coauthors(); $len = count($coauthors); if ($len > 1) { ?> <div class="authors-container"> <div class="fdescription fdescriptions">Dieser Artikel wurde in Ko-Produktion durch folgende Autoren erstellt:</div> <?php foreach ($coauthors as $coauthor): ?> <div class="author-item"> <div class="author-image"> <?php echo get_avatar($coauthor->user_email, '80'); ?> </div> <div class="author-data-details"> <div class="authors-name">Von <?php coauthors_posts_links(); ?></div> </div> <div class="clearfix"></div> </div> <?php endforeach; ?> </div> <?php } else { global $post; foreach ($coauthors as $coauthor): ?> <div class="author-container"> <div class="author-image"> <?php echo get_avatar($coauthor->user_email, '80'); ?> </div> <div class="author-data-details"> <div class="author-name">Von <?php coauthors_posts_links(); ?></div> <div class="fdescription"> <?php echo $coauthor->description; ?></div> </div> <div class="clearfix"></div> </div> <?php endforeach; } return ob_get_clean(); } add_shortcode('coauthorplus', 'coauthorplus_function'); ?>
正确的文件引入方式
如果你的coauthorplus.php放在当前激活主题的根目录下,需要在主题的functions.php中使用绝对路径引入:
include get_stylesheet_directory() . '/coauthorplus.php';
内容的提问来源于stack exchange,提问作者johny
相关产品推荐
相关产品推荐

