0

I'm trying to allow authors to add TV charts in the articles. For this reason, I added the following shortcode:

function cikkek_shortcode($atts) {
$option = shortcode_atts(
    array(
        'url'     => '',
        'options' => '',
    
    ),
    $atts
);
?>  

    
<script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
<script type="text/javascript">
var tradingview_embed_options = {};
tradingview_embed_options.width = '640';
tradingview_embed_options.height = '400';
tradingview_embed_options.chart = '<?php echo $option['options']; ?>';
new TradingView.chart(tradingview_embed_options);
</script>
<p><a href="<?php echo $option['url']; ?>">
<?php
}
add_shortcode( 'cikkekembed', 'cikkek_shortcode' );

I created an article and input the following as a test:

[cikkekembed url='https://www.tradingview.com/chart/PLTR/MRrFdJON-PLTR-diamond-hands/ options='MRrFdJON']

1 -> Boom, I got an invalid json response. I read a bit online and if I understood correctly, a shortcode inside a HTML tag is not possible?

2 -> Anyway, I tried taking some stuff out, but it didn't help, so I thought it might not be related to that

3 -> Installed classic editor, the shortcode works like a charm.

How can I get this working in Gutenberg?

Thanks!

1

A shortcode should only ever return content, never echo it. The bits between the ?> and <?php tags -- the <script> tags and the rest -- are effectively being echoed to the browser, which means that the JSON content that Gutenberg expects is no longer valid.

From the add_shortcode() docs:

Note that the function called by the shortcode should never produce an output of any kind. Shortcode functions should return the text that is to be used to replace the shortcode. Producing the output directly will lead to unexpected results.

Also, instead of sending those <script> tags directly, you should enqueue them. See wp_enqueue_script(). Since you are passing data from PHP to at least one of your scripts, see also wp_localize_script().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.