我在 WordPress 中遇到了一个关于短代码的奇怪问题。当我在添加短代码时保存页面时,它会将我重定向到
wp-admin/post.php
并显示一个白色页面,其中包含 html 格式的短代码结果(参见屏幕截图 1)。幸运的是,所有编辑都被保存了。
有趣的是,我已经用完全相同的方法做了十几次了。但有一段时间它不再起作用了。
我确实希望您看到这个问题并知道我们可以采取哪些措施来解决它。
我正在使用的 PHP 代码已添加到
functions.php
我使用的简码是
[showblog cat="planning" number=4]
function showblog_func( $atts ) {
$atts = shortcode_atts([
'number' => '-1',
'cat' => '',
], $atts, 'showblog' );
$numberposts = $atts['number'];
$categorie = $atts['cat'];
//args
$args = array(
'post_type' => 'post',
'posts_per_page' => $numberposts,
'order' => 'ASC',
);
if($categorie != ""){
$args = array(
'post_type' => 'post',
'posts_per_page' => $numberposts,
'category_name' => $categorie,
'order' => 'ASC',
);
}
// The Query
$the_query2 = new WP_Query( $args );
// The Loop
if ( $the_query2->have_posts() ) {
echo '<ul class="blog-list clearfix">';
while ( $the_query2->have_posts() ) {
$the_query2->the_post();
echo '<li class="blog-block">';
echo ' <div class="blog-info">';
echo ' <h4>'.get_the_title().'</h4>';
echo ' <p>'.get_the_excerpt().'</p>';
echo ' <a href="'.get_the_permalink().'" class="blog-button">Read full post</a>';
echo ' </div>';
echo '</li>';
}
echo '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
}
add_shortcode( 'showblog', 'showblog_func' );
通过在第一个
ob_start();
标签后面添加 <?php
即可解决。
我也有同样的情况并找到了解决方法 只需在 html 开始之前添加
ob_start();
并像这样结束ob_get_clean();
function form_creation(){
ob_start();
?>
<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname"><br>
Message: <textarea name="message"> Enter text here...</textarea>
</form>
<?php
return ob_get_clean();
}
add_shortcode('test', 'form_creation');
您无法回显短代码 HTML。
您需要在变量中绑定 HTML,然后从短代码返回此 HTML..
请检查以下代码
function _login_popup() {
$html = '<form id="user-login-form" method="post" action="#" class="js-form-redirect js-form-action" novalidate="">
<div class="floating-label form-group">
<input id="useremail" name="user_name" required="" value="" type="email">
<label for="useremail">Email</label>
</div>
<div class="floating-label form-group">
<input id="userpassword" name="password" required="" value="" type="password">
<label for="userpassword">Password</label>
</div>
<div class="o-form__buttons text-right --small-center">
<button type="submit" id="submit_login" class="a-button-form --save a-no-before" value="edit">Sign in</button>
</div>
</form>';
return $html;
}
add_shortcode('yg-login-popup', '_login_popup');
这不是故意的,非常糟糕,并且发生这种情况是因为向编辑器提供内容的 WordPress REST API 端点在不应该触发时触发了
the_content
钩子。
使用
is_admin()
阻止在管理页面上进行处理。
ServerSideRender
中执行。此外,这意味着发送到客户端的 blob 明显更大,但这是一个小得多的问题。
如您所见,这是一个更大的问题,具有更广泛的后果,包括不必要的计算和网络活动。从剩下的问题来看,我们正在努力。目前还不清楚核心何时会解决这个问题。
解决方法
中提到的,可以通过在管理页面上有条件地阻止处理/渲染来解决这个问题。您可以使用 is_admin()
函数来实现此目的。致谢
echo
,它是
错误,因为这与OP遇到的问题无关,并且不会阻止短代码被呈现。它们只会阻止短路产生输出。 也就是说,您绝对应该返回输出字符串,而不是根据
echo