John Davidson

wordpress - Use PHP variable in Vuejs component

0 comments
Message:


I work on some custom code for Wordpress, and I need to access some PHP variables with Vuejs.
Right now I can't access PHP variables, also I get an error, and I am not sure what is wrong (error on data).


<?php
function nrc_new_modalities(){
$user_id = get_current_user_id();

$multipleSelect2 = get_user_meta( $user_id, 'multipleSelect2', true );
$multipleSelect2 = isset( $multipleSelect2 ) ? $multipleSelect2 : array();

$modality_list = get_terms([
'taxonomy' => 'product_cat',
'hide_empty' => false,
'parent' => 92
]);
?>

<div id="app">
<p>{{modality_list}}</p> //Here I get plain text
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.8/vue.js"></script>
<script>
new Vue({
el: '#app',
data() { // Here I get "Uncaught SyntaxError: Unexpected token '}'"
return {
modality_list: <?php json_encode($modality_list) ?>,
}
},
created(){
var new_val = <?php json_encode($modality_list) ?>
console.log('Val:', new_val) //here I get NULL
}
});
</script>

<?php
}
?>


My Answer:
To access PHP variables in a Vue.js component in WordPress, you can use the `wp_localize_script` function to pass the PHP variables to your JavaScript code. Here's how you can do it:

1. In your WordPress theme or plugin file, enqueue your script and localize the PHP variables:

php
function my_custom_script() {
wp_enqueue_script('my-script', get_template_directory_uri() . '/js/my-script.js', array('jquery'), null, true);

$php_variable = 'Hello from PHP';
wp_localize_script('my-script', 'php_vars', array(
'variable' => $php_variable
));
}
add_action('wp_enqueue_scripts', 'my_custom_script');


2. In your Vue.js component, you can access the PHP variable like this:

javascript
export default {
data() {
return {
phpVariable: php_vars.variable
};
},
mounted() {
console.log(this.phpVariable); // Output: Hello from PHP
}
}


Make sure to replace `my-script` with the handle of your script, and `get_template_directory_uri() . '/js/my-script.js'` with the path to your JavaScript file.

By localizing the PHP variable, you can access it in your Vue.js component and use it as needed.

Rate this post

3 of 5 based on 1732 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us