WordPress – JS and PHP in a PHP file?

I would like to include the following code in my functions.php file in WordPress, but am stuck getting the correct format, it’s broken at present.

This is the code I have currently –

Read More
<script>
     jQuery(document).ready(function($){
        if (jQuery('body.default, body.alternative').length) {
               twitterFetcher.fetch('<?php echo $redux_demo['divider-twitter-id']; ?>', 'twitter-fetcher-tweet', 1, true, false);
        };
     });
</script>

Many thanks for any tips

Related posts

Leave a Reply

2 comments

  1. Try to use:

    <?php echo $redux_demo["divider-twitter-id"]; ?>
    

    instead of:

    <?php echo $redux_demo['divider-twitter-id']; ?>
    

    You need to wrap divider-twitter-id in double quotes, not single quote here.

  2. To answer the question of ‘adding js into a PHP file’, You need to echo it:

    <?php
     echo "<script>
      jQuery(document).ready(function($){
         if (jQuery('body.default, body.alternative').length) {
            twitterFetcher.fetch('" . $redux_demo['divider-twitter-id'] . "', 'twitter-fetcher-tweet', 1, true, false);
        };
      });
     </script>";
    ?>
    

    But to accomplish what you’re trying to do, put in functions.php:

    add_action('wp_enqueue_scripts', 'theme_scripts');
    
    function theme_scripts() {
      if (!is_admin()) {  
        wp_enqueue_script( 'twitter-fetcher',  THEME_URL . '/js/twitter-fetcher.php?twitterId=' . $redux_demo['divider-twitter-id']);
      }
    }
    

    Then in in wp-content/theme/js/twitter-fetcher.php,

    <?php
    // Sets the proper content type for javascript
    header("Content-type: application/javascript");
    ?>
    jQuery(document).ready(function($){
         if (jQuery('body.default, body.alternative').length) {
            twitterFetcher.fetch('<?php $_GET['twitterId']; ?>', 'twitter-fetcher-tweet', 1, true, false);
       };
    });