【问题标题】:WordPress Shortcode output is duplicated on pageWordPress 简码输出在页面上重复
【发布时间】:2021-12-29 19:24:57
【问题描述】:

我创建了一个 ACF 图像字段,我想将其添加到我的产品描述中。

然后我通过此代码创建了一个简码:

function imgun_shortcode() {
$imgun = get_field('imgun')['sizes']['thumbnail']; // (thumbnail, medium, large, full or custom size)?>
<div>
    <img src="<?php echo $imgun;?>">
</div> <?php 
}

add_shortcode('imgun', 'imgun_shortcode'); 

然后我在扩展“块”中添加这个短代码:

我通过产品描述中的简码添加此页面,图像字段位于 2 次,而不是在简码的位置,我不明白为什么。我的其他 ACF“文本”字段没有这个问题。

你有什么想法吗?

【问题讨论】:

  • 您无法回显短代码输出。
  • 我刚刚更新了问题中的代码(输入错误)

标签: php wordpress woocommerce advanced-custom-fields


【解决方案1】:

您无法回显短代码的输出。 Note that the function called by the shortcode should never produce output of any kind. Shortcode functions should return the text that is to be used to replace the shortcode.https://codex.wordpress.org/Shortcode_API

你可以这样做......

function imgun_shortcode() {
    ob_start();
    $imgun = get_field( 'imgun' )['sizes']['thumbnail']; // (thumbnail, medium, large, full or custom size)?>
    <div>
        <img src="<?php echo esc_url( $imgun ); ?>">
    </div> <?php
    return ob_get_clean();
}
add_shortcode( 'imgun', 'imgun_shortcode' );

或者你可以这样做......

function imgun_shortcode() {
    $imgun = get_field('imgun')['sizes']['thumbnail']; // (thumbnail, medium, large, full or custom size).
    return '<div><img src="' . esc_url( $imgun ) . '"></div>';
}

add_shortcode('imgun', 'imgun_shortcode'); 

【讨论】:

  • 非常感谢!!
猜你喜欢
  • 2017-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多