Your cart is currently empty!
How To Use PHP Variables in jQuery
โ
by
You can extend the use of jQuery in WordPress by using PHP within your jQuery code. In this case, we’ll use a PHP variable with a jQuery variable like this :
$content = $product->get_meta('content');
var content = <?php echo json_encode($content); ?>;
This code enables us to use the value for a custom field content as the value for a jQuery variable named content
Now you can use your jQuery variable in your jQuery without hard coding values which is much less flexible.
PHP jQuery json_encode
Here’s a working example you can test in your child themes functions file
add_action( 'woocommerce_before_single_product_summary', 'php_jquery_json', 22 );
function php_jquery_json() {
if ( is_product() ) {
global $product;
$content = get_post_meta( $product->get_id(), 'content', true );
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
var content = <?php echo json_encode($content); ?>;
$('.wc-block-components-product-price').append('<div>' + content + '</div>');
});
</script>
<?php
}
}
This targets the block element using the wc-block-components-product-price class. Swap out that class to target some other.
PHP jQuery Data Attribute
You can also use PHP in jQuery using a data attribute like this
add_action( 'woocommerce_single_product_summary', 'php_jquery_data_attribute', 20 );
function php_jquery_data_attribute() {
if ( is_product() ) {
global $product;
$custom_field_value = get_post_meta( $product->get_id(), 'content', true );
if ( ! empty( $custom_field_value ) ) {
echo '<div id="my-custom-field" data-value="' . esc_attr( $custom_field_value ) . '">' . esc_html( $custom_field_value ) . '</div>';
}
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
var customFieldValue = $('#my-custom-field').data('value');
$('#your-html-element').text(customFieldValue);
});
</script>
<?php
}
}
This method is used in the following WordPress tutorials and WooCommerce extensions :
Free
$0
Access only to all free tutorials per month.
Tutorial Request
Includes code guarantee and coding support.
Monthly
$75
Access to 10 premium tutorials per month.
Tutorial Request
Includes code guarantee and coding support.
Yearly
$500
Access to 15 premium tutorials per month.
Monthly Tutorial Request
Includes code guarantee and priority coding support.
Was This Tutorial Helpful?