Using WordPress ‘print_late_styles’ PHP filter

‘print_late_styles’ is a WordPress PHP filter that controls whether to print styles that were queued too late for the HTML head.

Usage

Here’s a code example for using this filter:

add_filter( 'print_late_styles', 'my_custom_function', 10, 1 );

function my_custom_function( $print ) {
  // Your custom code here
  return $print;
}

Parameters

  • $print (bool): Determines whether to print the ‘late’ styles. Default is true.

Examples

Prevent Late Styles from Printing

function prevent_late_styles( $print ) {
  return false;
}
add_filter( 'print_late_styles', 'prevent_late_styles' );

This code prevents any late styles from being printed.

function print_late_styles_for_logged_in( $print ) {
  return is_user_logged_in();
}
add_filter( 'print_late_styles', 'print_late_styles_for_logged_in' );

This code allows late styles to be printed only for logged-in users.

function print_late_styles_on_specific_pages( $print ) {
  if ( is_page( 'contact' ) || is_page( 'about' ) ) {
    return true;
  }
  return false;
}
add_filter( 'print_late_styles', 'print_late_styles_on_specific_pages' );

This code prints late styles only on the Contact and About pages.

function print_late_styles_for_user_role( $print ) {
  $user = wp_get_current_user();
  if ( in_array( 'administrator', $user->roles ) ) {
    return true;
  }
  return false;
}
add_filter( 'print_late_styles', 'print_late_styles_for_user_role' );

This code prints late styles only for users with the ‘administrator’ role.

Print Late Styles on Custom Post Types

function print_late_styles_on_custom_post_types( $print ) {
  if ( is_singular( 'my_custom_post_type' ) ) {
    return true;
  }
  return false;
}
add_filter( 'print_late_styles', 'print_late_styles_on_custom_post_types' );

This code prints late styles only on single pages of the ‘my_custom_post_type’ custom post type.