Home Forums Front-end Issues Passing get_sub_field() to JS script


Passing get_sub_field() to JS script

  • I’m trying to pass the sub_field image url into my functions.php using wp_localize_script, then pass it over as a var in my js. I’ve successfully passed image urls using get_field onto my functions.php and then into my js but for some reason I cannot use the same technique with get_sub_field(), returns nothing. Any thoughts?


    <?php if( have_rows('section_content') ): ?>
        <?php while( have_rows('section_content') ): the_row();   		
            $sectionBG = get_sub_field('background_image');
            $sectionContent = get_sub_field('section_text');
            $mobileBG = get_sub_field('mobile_background_image');


    wp_localize_script('main-js', 'php_vars', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'root_dir'	=>	get_template_directory_uri(),	
        'mobile_bg'	=>	get_sub_field('background_image')
  • In functions.php you need to supply the post ID to get the values from and you also need a have_rows() loop to get the sub field. Basically you need all the looping you have in the page with the addition of the post ID to get values from, this is the second optional parameter in most ACF functions like get_field('my_field', $post_id) and have_rows('my_field', $post_id)

  • John,

    Thanks for the reply. After much tinkering I figured out that I need to include the have_rows loop in the functions.php to obtain the desired sub_field data. But the issue is that when I pass that data over to my variable as an array, I get all the urls concatenated as one string. This only happens when a page has multiple rows not when there is only 1.

    Since this is more of a general PHP question and not ACF specific, I’ll mark your replay as the solution.

  • Check what you are returning from the field. It sounds like you are returning an array or object instead of the URL, although I’m not sure by your comment exactly what you mean.

Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Passing get_sub_field() to JS script’ is closed to new replies.