enqueue script with php decisions

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?

Read More

Hope my question make sense..

Related posts

1 comment

  1. 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 JavaScript

    // Localize the script with new data
    $data = array(
        'is_front_page' => is_front_page(),
        'is_english' => mida_is_english()
    );
    wp_localize_script( 'your-registered-script-handle', 'page_info', $data );
    

    Note 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:

    // This is in a JavaScript file
    if ( !page_info.is_front_page ) {
        // Do stuff
    }
    if ( !page_info.is_english ) {
        // Do some other stuff
    }
    

    All of that said, I recommend just injecting the code you mentioned into wp_footer, instead of messing with localization…

Comments are closed.