Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am loading some scripts conditionally for the admin section with :

if (is_admin()) {
    wp_register_style('admin_js', get_bloginfo('template_directory') . '/admin.js');
    wp_enqueue_script('admin_js');
}

The script gets elements with:

theID = document.getElementById('bar').value; 

The missing element exists on custom meta boxes

<?php function my_meta() {
  global $post;
  $custom = get_post_custom($post->ID);
  $uniqueInput = $custom["uniqueInput "][0];
  ?>
  <p><label for="foo">Input:</label><br />
  <input id="bar"  name="bar" value="<?php echo $uniqueInput; ?>"></input></p>
 <?php } ?>

I am generating the custom meta boxes only in my custom post type :

register_post_type( 'customType' , $args );

I tried to add another condition in the enqueue :

if (is_admin()) {
    if(get_post_meta($post->ID, 'uniqueInput', true)):
        wp_register_style('admin_js', get_bloginfo('template_directory') . '/admin.js');
        wp_enqueue_script('admin_js');
    endif;

and this :

if (is_admin()) {
    $foo = get_post_meta($post->ID, 'uniqueInput', true);
    if ($foo) {
       wp_register_style('admin_js', get_bloginfo('template_directory') . '/admin.js');
       wp_enqueue_script('admin_js');
}

But this doesnt work for me. The script is suppressed so I no longer get a missing element error... however this condition is never met, the js never loaded. Now I realize it is because I was making the wrong checks, looking to see if that input has a value entered, not for the input field itself which is what I need. What would be the best way to do this check? Would I look for the custom post type?

share|improve this question
add comment

1 Answer

Yes, you are doing it wrong. You are checking for the posts' custom field value which the new post page will does not have, and editing older posts might also does not have the custom field set or may be set to an empty value.

Yes, you need to check for the custom post type:

if ( is_admin() && ( $post->post_type == "customType" ) {
     wp_register_style('admin_js', get_bloginfo('template_directory') . '/admin.js');
       wp_enqueue_script('admin_js');
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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