1

What I am trying to achieve is to load a .js file on an edit.php page, however the code is not working specifically for this page. I've applied the same code type of code to other CPT pages, but for some reason this CPT page is not registering the script.

Here is the code I am using:

add_action( 'admin_menu', 'contacts_table_add_pages', 99 );
function contacts_table_add_pages(){
    $menu = add_menu_page( 'Contacts', 'Contacts', 'publish_posts', 'edit.php?post_type=contact' );
    $submenu = add_submenu_page('contacts', 'Add Contact', 'Add Contact', 'publish_posts', 'post-new.php?post_type=contact');

    add_action( 'load-' . $menu, 'contacts_table_add_custom_css_js', 11 );
}

function contacts_table_add_custom_css_js() {
    add_action( 'admin_enqueue_scripts', 'contacts_table_css_js', 11 );
}

function contacts_table_css_js() {
    wp_enqueue_script( 'contacts', PLUGIN_URL . 'contacts/includes/contacts.js' );
}

The reason why I am creating a new CPT menu item is because it was once part of another plugin's submenu list - so I removed it from there and created its own menu item.

I've done the same for another plugin's CPT - and that one worked fine. It's just this CPT from another plugin that is not working.

Any clue on what may be going on?

Thanks, Roc.

1
  • You can also check this article for enqueue script into specific admin page. hope it will help
    – Meathanjay
    Commented May 25, 2014 at 20:37

1 Answer 1

3

I think you're using the wrong approach. Rather than removing the submenu item, alter how the post type was registered, and change the show_in_menu argument. Hook into init way late and change the argument.

<?php
add_action('init', 'wpse99123_post_type_switcher', 999);
function wpse99123_post_type_switcher()
{
    global $wp_post_types;
    $wp_post_types['contact']->show_in_menu = true; // put it back in the menu
}

Then, to load the CSS/JS/whatever, you need to hook into load-edit.php and check the current screen's post type and add enqueue functions from there.

<?php
add_action('load-edit.php', 'wpse99123_load_edit');
function wpse99123_load_edit()
{
    $screen = get_current_screen();

    if (!isset($screen->post_type) || 'contact' !== $screen->post_type) {
        return; // not where we want to be, bail
    }

    // add enqueues here.
    add_action('admin_enqueue_scripts', 'wpse99123_enqueue');
}

function wpse99123_enqueue()
{
    // ...
}

You have to do load-edit.php because $screen->post_type will be contact on your contacts edit (post.php) and add new (post-new.php) pages.

1
  • Hi Chris. This worked wonderfully. Thanks! The first part of your answer helped me out tremendously, as now I can apply that to the other CPTs I did this for.
    – Roc
    Commented May 11, 2013 at 18:02

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.