0

So I'm trying to figure out how to properly use the get_current_screen. For learning sake, I'm just popping an alert for a specific page. I've looked at http://www.deluxeblogtips.com/2012/01/get-admin-screen-information.html and the codex on WP_Screen and get_current_screen (hit my max links cause my rep isn't 10 yet)

I thought I was doing this right...but not getting it to work. What I'm hoping for is that when I go to /wp-admin/post-new.php?post_type=product I can do stuff (will be enqueueing a script). Did pretty much a straight copy and changed the post type...but, what am I missing here?

add_action( 'wp_enqueue_scripts', 'rw_enqueue_scripts' );
/**
* Enqueue scripts for 'post' page of 'product' post type only
*
* @return void
*/

function rw_enqueue_scripts()

{

$screen = get_current_screen();

// Check screen base and current post type
if ( 'post' === $screen->base && 'product' === $screen->post_type )
{
    echo "<script type='text/javascript'>alert('worked');</script>

    ";
}
}

Thanx in advance,

Brian

0

2 Answers 2

3

wp_enqueue_scripts is only fired on the front end, and not on admin screens. For loading scripts admin side, you'll want the hook admin_enqueue_scripts.

Passed as an optional argument is the page hook. (Examples include edit.php, for the admin edit page (which lists pages/posts/ cpt posts), post.php when editing a post/ custom post type and post-new.php when creating a new one).

$screen = get_current_screen(); is also available to you, so you can restrict by post type. E.g.:

add_action( 'admin_enqueue_scripts', 'rw_enqueue_scripts' ,10,1);

function rw_enqueue_scripts($hook){

    $screen = get_current_screen();

    // Check screen hook and current post type
    if ( 'post.php' == $hook && 'product' == $screen->post_type ){
        //Load scripts
    }
}
1
  • bloody hell...I knew that, "admin_enqueue_scripts" grrr it's always the little things...but I didn't know about passing the hook...awesome! Working now! Thanks Stephen. Commented Apr 22, 2012 at 20:32
0

I used this code to make one of the fields on the product page required. But it includes the condition to check the current page is product page before insert the script in the header.

add_action( 'admin_head', 'dcwd_require_weight_field' );
function dcwd_require_weight_field() {
    $screen         = get_current_screen();
    $screen_id      = $screen ? $screen->id : ''; 
    if ( $screen_id == 'product' ) {
?>
<script>
  //Load scripts
</script>
<?php
    }
}

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.