Search code examples
wordpressadvanced-custom-fieldscode-snippets

Advanced Custom Fields code displayed as plaintext when written in Code Snippets plugin. How to fix?


On Wordpress, I’m trying to add a link to single product page using Code Snippets with Advanced Custom Fields. Instead of a link, my code displays as plaintext.

I have tried this code:

function product_datasheet_below_summary() { ?>
    $link = get_field('datasheet');

if( $link ): 
    $link_url = $link['url'];
    $link_title = $link['title'];
    $link_target = $link['target'] ? $link['target'] : '_self';
    ?>
    <a class="button" href="<?php echo esc_url($link_url); ?>" target="<?php echo esc_attr($link_target); ?>"><?php echo esc_html($link_title); ?></a>
<?php
};
add_action( 'ocean_after_single_product_meta', 'product_datasheet_below_summary', 5 );

This doesn’t work. I was hoping for a link to the Datasheet, but it simply prints, in plaintext:

$link = get_field(‘datasheet’); if( $link ): $link_url = 
$link[‘url’]; $link_title = $link[‘title’]; $link_target = 
$link[‘target’] ? $link[‘target’] : ‘_self’; ?>

followed by a generic square button link.

What am I doing wrong here? Thanks very much for your help.


Thanks for your advice. Instead of using Code Snippets I just created a child theme and edited the relevant .php file, adding the following:

`

                if( $link ): 
                    $link_url = $link['url'];
                    $link_title = $link['title'];
                    $link_target = $link['target'] ? $link['target'] : '_self';
                    ?>
            <a class= "button" id="datasheet-button" href="<?php echo esc_url($link_url); ?>" target="<?php echo esc_attr($link_target); ?>"><?php echo esc_html($link_title); ?></a>
            <?php endif; ?>`

Solution

  • You're getting plaintext after the first ?> because that's a php ending tag, and the Code Snippets plugin doesn't allow for multiple php statements and is simply crashing and dumping plain text rather than executing code.

    You need to rewrite the whole function as one php statement and echo all the button html, along with the php variables delimited in the html with .'s. A simple example:

    <?php 
    $var = "Hello World";
    echo "<p>The value of the variable is : " . $var . "</p>";
    ?>
    

    And you may need to use the more standard ACF get field construct, too:

    $value = get_field( "text_field" );

    Search SE for more examples of echoing html in php.