In wordpress, the recommended option to use java script is with wp_enqueue_script()
, but what if I want to put some php in that script? for example, look at this code:
$(window).scroll(function () {
if ($(window).scrollTop() > 100) {
<?php if ( !is_front_page() ){ ?>
$('.primary-menu').hide('slow', 'swing');
$('.site-logo').css('height', '60px').css('padding-bottom', '0');
$('#masthead').css('height', '5px');
<?php } ?>
<?php if ( !mida_is_english() ) : ?>
$('.site-header').addClass('shrink');
$("#masthead.site-header.shrink")
.find('.site-logo img')
.attr('src', '<?php echo $upload_dir['baseurl']?>/2015/12/extra-cropped-logo.jpg');
<?php else : ?>
$('.site-header').addClass('shrink');
$("#masthead.site-header.shrink")
.find('.site-logo img')
.attr('src', '<?php echo $upload_dir['baseurl']?>/2015/10/mida-eng-logo.png');
<?php endif; ?>
}
else{ //some more code....
How can I enqueue this code? I can just put it in php file and use wp_enqueue_script()
to enqueue that file?
Hope my question make sense..
If you’re not willing to add that code to the footer.php file of your site, you can use
wp_localize_script()
to pass data to your JavaScriptNote that you may need to hook this later than the
wp_enqueue_scripts
hook, in order for it to work. You can then use it in your JS via:All of that said, I recommend just injecting the code you mentioned into
wp_footer
, instead of messing with localization…