0

I have pages and posts on a WordPress site.

The pages have various layouts. Parent pages are following a 2-column (maincontent + right sidebar) layout while child pages have a one-column layout (no sidebar).

I want to display a JavaScript code on one-column layout, and a different JavaScript code on 2-column layout.

Must also add that one-colum has a custom field "one-col" and 2-column is the default layout. Not sure if it's possible to add codes based on custom fields.

Theme: WooThemes, Canvas.

Really appreciate your help.

1 Answer 1

1
function add_js_one_col_wpse_107240() {
  if (is_page()) {
    $pobj = get_queried_object();
    if(!empty(get_post_meta($pobj->ID,'one-col',true)) {
      wp_enqueue_script(/* ... */);
    } else {
       wp_enqueue_script(/* ... a different script ... */);
    }
  }
}
add_action('wp_enqueue_scripts','add_js_one_col_wpse_107240');
  1. get_queried_object will get you the page information. It will be a WP_Post object on a "Page". global $post should probably work too, but this is cleaner.
  2. Use the WP_Post object information to check for the custom meta field. enqueue scripts accordingly. You don't say what the value of one-col is so I checked for any value at all.
  3. Hook the whole thing to wp_enqueue_scripts.
3
  • +1, as usual, but one sidenote: !empty(get_post_meta($pobj->ID,'one-col',true)) requires PHP 5.5+ while WP's current requirement is 5.2.4 Commented Jul 20, 2013 at 15:39
  • @JohannesPille : hmmm... why does that require PHP 5.5? What have I missed? Do I need to save the get_post_meta output to a variable first?
    – s_ha_dum
    Commented Jul 21, 2013 at 18:50
  • Yep. Before 5.5 empty() would only accept variables. Since 5.5 it supports any expression. Hence caching the return of get_post_meta() in a variable before checking for emptiness would support PHP versions below 5.5... (That's my understanding anyhow. Not saying I couldn't be wrong.) Commented Jul 21, 2013 at 19:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.