简体   繁体   中英

How to insert a PHP CODE inside shortcode?

I would like to insert a php code, but the error when placing

Shortcode generated by theme

[col_grid span="4" span__sm="14" height="1-2" visibility="show-for-medium"]

[ux_banner height="500px" bg="***[banner-picture]***" bg_size="original"]

[text_box width="100" scale="148" position_x="50" position_y="100" bg="rgb(88, 32, 123)"]

[ux_text text_color="rgb(247, 128, 44)" class="uppercase"]

<p><strong>preencha a proposta de adesão</strong></p>
[/ux_text]

[/text_box]

[/ux_banner]

[/col_grid]

My PHP CODE

add_action('foto_banner', 10 );
  
function foto_banner() { ?>
<?php if(get_field('foto_banner')) { ?>


<?php the_field('foto_banner'); ?>

<?php }else{
    echo "Texto não informado";
}
}

add_shortcode( 'banner-picture', 'foto_banner');

You can not put PHP functions inside your shortcode.

However, you do not need to. You can just use your foreach-loop to create the html and store it in a variable, for example $shortcodehtml.

So, afterwards, you can call

echo do_shortcode('[O_U user_name="operator" blocked_message="This page is restricted for guests."]' . $shortcodehtml . '[/O_U]');

The better version of that would be if you would create the output inside the shortcode function - from my point of view it is not necessary to pass the whole html to the shortcode - but this should work fine.

You can write your shortcode like this:

<?php

function bannerPicture(){
    ob_start();

    if( get_field( 'foto_banner' ) ) {
        the_field( 'foto_banner' );
    } else {
        echo "Texto não informado";
    }

    $output = ob_get_contents();
    ob_end_clean();
    return $output;
    
}
add_shortcode( 'banner-picture', 'bannerPicture' );

?>

Make sure to add current page id in get_field() second parameter or option if you are fetching from Theme Options page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM