Techblog Index

Reader's thoughts on "Smartly resolving your WordPress pages and posts JavaScript and CSS dependences"

5
  1. Very fine article. Using custom fields to store javascript and stylesheet info is very clever.
    Perhaps it could be made better by hooking to wp_head and placing both foreachs in functions.php. This would leave the template file with less kludge.

  2. That’s a nice idea Bruno! Will test it out and update the post! Thanks for the tip!

  3. I have similar code that takes the js file name from the custom field value:
    if ( get_post_meta($post->ID, ‘javascript’, true) ) {
    $script = get_post_meta($post->ID, ‘javascript’, true);

    $script_path = get_bloginfo(‘template_url’) . ‘/scripts/’ . $script . ‘.js’;
    wp_enqueue_script( $script, $script_path );
    }
    The code above is in my header.php and each post that needs custom javascript has a custom field named javascript with a value = to the js file name.

    However, it only works when the post is viewed as a single post or is the first post on the home page. Once another post is added (making the relevant post now the 2nd post on the home page) this code doesn’t work.

    It sounds like the use of “foreach” instead of “if” is the difference but don’t know enough to change the code to a “foreach” statement instead of an “if” statement.

    Would you please advise how I can change this code to work as a “foreach” statement?

Leave a Reply