我试图将html和在自定义函数输出中运行短代码结合起来,但遇到了一个解析错误。请看下面我正在努力实现的目标。这种方法是正确的还是有更好的方法来实现这一点?
function gshar_text_shortcode() {
return \'<span class="kalia">Share with friends</span><div class="kalisha">\' . echo do_shortcode(\'[share facebook="true" twitter="true" linkedin="true" email="true"]\') . \'</div>\';
}
add_shortcode(\'globeshare\', \'gshar_text_shortcode\');
我的
[share]
函数中的短代码。php
function x_portfolio_item_social_v2() {
$share_project_title = x_get_option( \'x_portfolio_share_project_title\' );
$enable_facebook = x_get_option( \'x_portfolio_enable_facebook_sharing\' );
$enable_twitter = x_get_option( \'x_portfolio_enable_twitter_sharing\' );
$enable_google_plus = x_get_option( \'x_portfolio_enable_google_plus_sharing\' );
$enable_linkedin = x_get_option( \'x_portfolio_enable_linkedin_sharing\' );
$enable_pinterest = x_get_option( \'x_portfolio_enable_pinterest_sharing\' );
$enable_reddit = x_get_option( \'x_portfolio_enable_reddit_sharing\' );
$enable_email = x_get_option( \'x_portfolio_enable_email_sharing\' );
$share_url = urlencode( get_permalink() );
$share_title = urlencode( get_the_title() );
$share_source = urlencode( get_bloginfo( \'name\' ) );
$share_content = urlencode( get_the_excerpt() );
$share_image = urlencode( x_get_featured_image_with_fallback_url() );
[truncated...]
if ( $enable_facebook == \'1\' || $enable_twitter == \'1\' || $enable_google_plus == \'1\' || $enable_linkedin == \'1\' || $enable_pinterest == \'1\' || $enable_reddit == \'1\' || $enable_email == \'1\' ) :
?>
<div class="x-entry-share">
<div class="x-share-options">
<?php echo $facebook . $twitter . $google_plus . $linkedin . $pinterest . $reddit . urldecode( $email ); ?>
</div>
</div>
<?php
endif;
}
add_action(\'wp_head\', \'change_item_social_v2\');
function change_item_social_v2() {
remove_shortcode( \'share\' );
add_shortcode( \'share\', \'x_portfolio_item_social_v2\' );
}
最合适的回答,由SO网友:Z. Zlatev 整理而成
更新似乎您试图使用的短代码没有得到很好的编码。如果他们在模板的某个地方单独使用它,比如echo do_shortcode(\'[share]\');
这并不重要,因为\'[share]\'
是传递给的唯一内容do_shortcode()
. 在您的情况下,您试图在将短代码放在其他内容中的上下文中重用它,这就是短代码的首要用途。尝试以下代码:
add_action(\'wp_head\', function() {
// bail if shortcode doesn\'t exists
if ( ! shortcode_exists( \'share\' ) ) {
return;
}
remove_shortcode( \'share\' ); // remove what is defined before in change_item_social_v2()
add_shortcode( \'share\', function( $args = [], $content = \'\' ) {
ob_start();
x_portfolio_item_social_v2( $args, $content );
return ob_get_clean();
} );
}, 100 ); // high hook order 100 > 10 (default), ensure this is called after original change_item_social_v2()
通过调用
ob_start()
之前
x_portfolio_item_social_v2()
我们只是阻止任何输出,从那一刻起,“显示”,相反,我们将其存储到一个缓冲区中,该缓冲区被刷新,其内容由
ob_get_clean()
, 就像一个合适的短代码处理程序。
我在这里没有看到解析问题,但明显的错误是在应该返回的函数中出现了回声。你看到你的echo do_shortcode(...)
实际上,它在运行时立即发出回声。echo
将输出,但不会有回报,它永远不会在你期望的地方(内部<div class="kalis"></div>
). 首次尝试删除echo