0

I have the following in functions.php. Is it possible to load them only on certain custom post types? (I have a few custom post types which all use a certain template part -> would it be possible to add the functions in there?) Or can add_action only be used with functions.php?

add_action( 'get_header', 'tsm_do_logged_in_author_checks' );
function tsm_do_logged_in_author_checks() {
// Get current user info
global $post,$current_user;
get_currentuserinfo();
// Bail if user is not logged in and not post author
if (// ! ( is_user_logged_in() && $current_user->ID == $post->post_author )
is_admin()) {
    return;
}

add_action( 'wp_enqueue_scripts', 'tsm_acf_form_edit_post_enqueue_scripts' );

add_action( 'get_header', 'tsm_do_acf_form_head', 1 );

add_action( 'wp_print_styles', 'tsm_deregister_admin_styles', 999 );

add_action( 'loop_start', 'tsm_do_acf_form_edit_toggle', 5 );

add_action( 'loop_end', 'tsm_do_acf_form_content' );

add_filter( 'acf/load_value/key=field_54dfc93e35ec4', 'tsm_load_post_title', 10, 3 );

function tsm_acf_form_edit_post_enqueue_scripts() {
wp_enqueue_script( 'sidr',  get_stylesheet_directory_uri() . '/assets/js/jquery.sidr.min.js', array( 'jquery' ), '1.2.1', true );
wp_enqueue_script( 'edit-post', get_stylesheet_directory_uri() . '/assets/js/edit-post.js', array( 'sidr' ), '1.0.0', true );
}
function tsm_do_acf_form_head() {
acf_form_head();
}
function tsm_deregister_admin_styles() {
wp_deregister_style( 'wp-admin' );
}

etc etc...

1 Answer 1

1

There is no limitation to using add_action(), except that core must have it loaded already. Practically this means pretty much anywhere, but wp-config.php.

While it is possible to do it in template, it's not a common practice because of:

  1. Timing issues (your template part might be loaded after the hooks you need).
  2. Code base clarity (it would be hard for someone else to find and make sense of it spread all around).

The typical practice is to:

  1. Create intermediary function.
  2. Hook it to appropriate hook (late enough for things to work, not too late), this is often init, admin_init, or template_redirect.
  3. Check the current context with conditional functions and on match hooks the other functions as you need.

This approach keeps things compact and easy for developers to both study and modify the behavior. 3.

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.