I am struggling with appending a variable created using my Advanced Custom Fields into an OnClick attribute within a link I am creating. I simply wish to create a link that also triggers an OnClick. The OnClick's purpose is going to be to trigger a script which tracks where users have engaged with the page (this doesn't need too much depth).

I am convinced it is a syntax error which I am sure one of you wizards will have a work around for.

Here is the snippet:

$has_header_contact_details = get_field('has_header_contact_details', 'options'); ?>
<div class="site-contacts">
    get_field('contact_method', 'options');
    while( have_rows('contact_method', 'options') ): the_row();
    $contact_color = get_sub_field('contact_color');
    $contact_text = get_sub_field('contact_text');
    $contact_link = get_sub_field('contact_link');
    $contact_icon = get_sub_field('contact_icon'); ?>
        <div class="site-contact">
            <a class="box-link" href="<?php echo $contact_link; ?>" target="_blank" onclick="<?php echo "track_load('https://example.com/" . echo $contact_link . "')"; ?>, <?php echo "'" . $contact_text . "'"; ?>"></a>
            <?php if($contact_icon != ''):?><img src="<?php echo $contact_icon; ?>" class="contact-icon" alt="contact icon"><?php endif; ?>
            <p<?php if($contact_color != ''):?> style="color:<?php echo $contact_color; ?>"<?php endif; ?>><?php echo $contact_text; ?></p>
    <?php endwhile; ?>

The difficulty is coming from this line:

<a class="box-link" href="<?php echo $contact_link; ?>" target="_blank" onclick="<?php echo "track_load('https://example.com/" . echo $contact_link . "')"; ?>, <?php echo "'" . $contact_text . "'"; ?>"></a>

Using the variables created in php $contact_link & $contact_text. Can you help me figure out why this code above doesn’t create the output:

<a class="box-link" href="tel:0123456789" target="_blank" onclick="track_load('https://example.com/tel:0123456789', '0123 456 789')"></a>

At this point we can trust that the variables are correct as I have previously had this link working without the OnClick, massive thank you to all contributors.

Thanks, Jason.


Your problem might be the extra echo in this part of that line:

<?php echo "track_load('https://example.com/" . echo $contact_link . "')"; ?>

You're using . to join the string parts together, so you don't also want the echo:

<?php echo "track_load('https://example.com/" . $contact_link . "')"; ?>

Hope that helps

  • I am going to try this now buddy and will feedback, thanks for taking a look – Jason Is My Name Feb 14 at 9:56

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.