开发WP主题时Slick Slider左右箭头图片路径无法获取的问题
Let's break down why your current approach isn't working and walk through the correct fixes:
The Core Issue
When you wrote var templateUrl = '<?= get_bloginfo("template_url"); ?>'; in your main.js file, WordPress doesn't parse PHP inside standalone JavaScript files. That means your variable ends up holding the literal string <?= get_bloginfo("template_url"); ?> instead of your actual theme's URL—so the image path is totally invalid.
Solution 1: Inject Theme URL Globally (WordPress Standard Method)
This is the most reliable way to pass PHP values to your JS code.
- Add this to your theme's
functions.php:
function my_theme_load_scripts() { // Enqueue your main JS file first wp_enqueue_script('main-script', get_template_directory_uri() . '/js/main.js', array('jquery'), '1.0', true); // Pass theme URL to JavaScript as a global variable wp_localize_script('main-script', 'ThemeSettings', array( 'templateUrl' => get_template_directory_uri() )); } add_action('wp_enqueue_scripts', 'my_theme_load_scripts');
- Update your
main.jsto use the global variable:
$('.your-slider-class').slick({ // Your other Slick settings... prevArrow: '<img class="a-left control-c prev slick-prev" src="' + ThemeSettings.templateUrl + '/img/left-arrow.png">', nextArrow: '<img class="a-right control-c next slick-next" src="' + ThemeSettings.templateUrl + '/img/right-arrow.png">' });
Side note: I fixed the class on your next arrow to slick-next instead of repeating slick-prev—that was likely a typo causing extra issues!
Solution 2: Pre-Render Arrow Elements in Your Template
If you'd rather avoid PHP-to-JS injection, you can build the arrow elements directly in your WordPress template (where PHP works) and tell Slick to use them:
- Add this to your template file (e.g.,
page.php,single.php, or a theme part):
<!-- Place this near your slider --> <div class="slider-controls"> <img class="a-left control-c prev slick-prev" src="<?= get_template_directory_uri(); ?>/img/left-arrow.png" alt="Previous Slide"> <img class="a-right control-c next slick-next" src="<?= get_template_directory_uri(); ?>/img/right-arrow.png" alt="Next Slide"> </div>
- Modify your
main.jsto reference these existing elements:
$('.your-slider-class').slick({ // Your other Slick settings... prevArrow: $('.slick-prev'), nextArrow: $('.slick-next') });
Quick Troubleshooting Checks
- Confirm your
imgfolder is directly in your theme's root (e.g.,wp-content/themes/your-theme/img/). - Double-check image filenames match exactly (server file systems are often case-sensitive!).
- Clear your browser cache after making changes—old cached JS files might override your updates.
内容的提问来源于stack exchange,提问作者Rexhep Rexhepi

