0

I want to add a little code snippet to the edit page if the current user is of a specific user role.

I do know how to check for the userrole in php, but I have no clue how to find out if the page is an edit post or edit pages page and how to add the snippet with php. Please note that jQuery must be available at this point.

I don't want to user wp_enqueue_scripts because it really only is a little snippet and I don't want to create a new file for this. The code should happily live inside my functions.php

Edit

According to Greg McMullen's answer I wrote the following which works well.

function function_to_run() {
  if ($_GET['action'] != "edit"){
    return;
  }

  $user_roles = array('role1', 'role2');

  foreach ($user_roles as $user_role) {
    if( current_user_can($user_role) ) {
      wp_enqueue_script( 'pending_post', get_template_directory_uri() . '/js/script1.js' );
    }
    else {
      wp_enqueue_script( 'pending_post', get_template_directory_uri() . '/js/script2.js' );
    }
  }
}
add_action( 'admin_enqueue_scripts', 'function_to_run' );

However, I think that it's very dirty to include 2 different files that contain 2 lines of code each.

Even if it's not best practice, I would like to add the js code to the php file. How is that possible?

0

You should be able to use the admin_enqueue_scripts hook to load your snippet on the edit page as seen in this example from the codex

function my_enqueue($hook) {
    if ( 'edit.php' != $hook ) {
        return;
    }

    wp_enqueue_script( 'my_custom_script', get_template_directory_uri() . '/myscript.js' );
}
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
| improve this answer | |
  • Thanks for your answer, but is there a possibility to NOT use wp_enqueue_script? – Sam Oct 10 '16 at 14:54
  • I'm sure there is, but I cannot recommend it. Why wouldn't you want to use it? You should really separate form/function. And if it's a small file, does it really matter if it exists independently or not? – Greg McMullen Oct 10 '16 at 14:56
  • Well I have to alter the code depending on the current user role. If it's a specific one the first snipped should be added, if it's any other role, an other snipped should be added. I find that it's a dirty way to wp_enqueue_script two different files of 3 lines... – Sam Oct 10 '16 at 15:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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