How to access custom post meta data from JavaScript

Question

I have created custom meta fields for my WooCommerce products. However, the plugin I am using (Advanced Woo Search) is written in JavaScript and I need to access PHP variables. I have used wp_localize_script() to do this. However, in the front-end, my data is not being shown.

Here is my PHP code:

    function js_enqueue_scripts() {
    global $post;
    $text2 = get_post_meta( $post->ID, '_load_speed_field', true );
    $text3 = get_post_meta( $post->ID, '_tyre_brand_field', true );
    $text4 = get_post_meta( $post->ID, '_brand_model_field', true );
    $text5 = get_post_meta( $post->ID, '_run_flat_field', true );
    //Put your variables inside a array
    $arrayname = array(
        'text1' => $text1,
        'text2' => $text2
    );

    //Register Script
    wp_register_script( "advanced-woo-search-pro", plugin_dir_url( __FILE__ ) . "/assets/js/common.js" );

    //Load the Script on Front-End
    wp_enqueue_script( "advanced-woo-search-pro" );

    //Localize script and pass the Data
    wp_localize_script( "advanced-woo-search-pro", "prefix", $arrayname );
}

//Works function on wp_enqueue_scripts Hook
add_action( "wp_enqueue_scripts", "js_enqueue_scripts" );

And here is my JavaScript to access the data from the plugin:

html += result.title + prefix.text1 + prefix.text2;

I have found this filter in the plugin documentation.

enter image description here

Can someone assist me in concatenating my custom fields to the title search result?

Thanks.

0
NDT-AM 1 month 0 Answers 10 views 0

Leave an answer