MartynJH MartynJH - 1 year ago 69
Javascript Question

Using a PHP variable as a variable in jQuery

I'm having a hard time understanding how to import a specific variable for use with jQuery.

Some links on a Wordpress theme are using

<?php if( get_post_meta($post->ID, "portfolio_link", true) ): ?>
<h1 class="portfolio-title">
<a target="_blank" href="<?php the_field('portfolio_link'); ?>">
<?php the_field('portfolio_title'); ?> <span class="sosa-icon">p</span>
<!--get PDF if not empty-->
<?php else: ?>
<h1 class="portfolio-title"><?php the_field('portfolio_title'); ?></h1>
<?php endif; ?>

As you can see the href is set as

href="<?php the_field('portfolio_link'); ?>"

Now I have a jQuery script as follows

<?php if( get_post_meta($post->ID, "portfolio_link", true) ): ?>

$phpVar = '';
echo "var phpVariable = '{$phpVar}';";

jQuery(".box").click(function() {;

<?php endif; ?>

This script currently works. It opens google in a new tab as a placeholder until I know how to make it open the same result as the href.

Now what I can't understand is how to set '$phpVar' to have the same effect as the 'href' I showed before instead of '';

Answer Source

Not sure just how the WordPress handling of this is, but given that the_field('portfolio_title'); returns a valid URL, you can simply assign the JavaScript variable the output of this variable.

var phpVariable = "<?php the_field('portfolio_link'); ?>";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download