wp_localize_script for inserting an image

爱⌒轻易说出口 提交于 2021-01-28 20:11:52

问题


I'm having some trouble with wp_localize_script . There's plenty of questions about this already but I don't know how to implement them to this specific case. I made a jQuery file that includes an image after every div with a specific class. The jQuery itself is fine as I can change the image tag with a paragraph tag and then it shows up in my browser. Here's what I have in functions.php

function wpa_scripts() {
wp_enqueue_script(
    'divider',
    get_template_directory_uri() . '/js/divider.js',
    array('jquery'),
    null,
    true
);
$script_data = array(
    'image_path' => get_template_directory_uri() . '/images/'
);
wp_localize_script(
    'divider',
    'divider_data',
    $script_data
); } add_action( 'wp_enqueue_scripts', 'wpa_scripts' );

And here's what I have in my .js

jQuery(document).ready(function($){

$('.contentpage').after('<img src=" '$script_data' + divider_placeholder.png">');   });

Can I anyone tell me what I did wrong? Thanks in advance.

Kind regards, Stef


回答1:


You need to have 'divider_data.image_path' instead of $script_data in your jQuery function:

jQuery(document).ready(function($){

    $('.contentpage').after('<img src="' + divider_data.image_path + 'divider_placeholder.png">');

});

Reference : https://codex.wordpress.org/Function_Reference/wp_localize_script




回答2:


Your variable $script_data isn't in the right syntax in your js file as well as you don't access your predefined localized variable divider_data:

Instead of:
$('.contentpage').after('<img src=" '$script_data' + divider_placeholder.png">'); });

It should be:

$('.contentpage').after('<img src="' + divider_data.image_path + 'divider_placeholder.png">');   });


来源:https://stackoverflow.com/questions/37209991/wp-localize-script-for-inserting-an-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!