I created an ACF image field that I want to add in my product description.
I then created a shortcode via this code:
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');
I then add this shortcode in the extension "block":
I add this page via a shortcode in my product description, the image field is positioned in 2 times and not at the place of the shortcode I do not understand why. My other ACF "text" fields do not have this problem.
Do you have an idea?
CodePudding user response:
You can't echo the output from a shortcode. 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
You could either do this...
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' );
Or you could do this...
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');