Advertisement
verygoodplugins

Untitled

Jun 30th, 2025
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.82 KB | None | 0 0
  1. /**
  2.  * Parses shortcodes in email content with the correct user context.
  3.  *
  4.  * @param string $email_content The email content with shortcodes.
  5.  * @param string $user_email    The email address of the user to simulate context.
  6.  * @return string The parsed and sanitized email content.
  7.  */
  8. function parse_email_shortcodes_with_user_context( $email_content, $user_email ) {
  9.  
  10.     // Look up the user by email.
  11.     $user = get_user_by( 'email', $user_email );
  12.  
  13.     if ( ! $user ) {
  14.         return $email_content; // No user found, return unparsed.
  15.     }
  16.  
  17.     // Backup the current user globals.
  18.     $original_user_id = get_current_user_id();
  19.     $original_user    = $GLOBALS['current_user'] ?? null;
  20.  
  21.     // Override current user globals.
  22.     wp_set_current_user( $user->ID );
  23.     $GLOBALS['current_user'] = $user;
  24.  
  25.     // Allow shortcodes to reference current user context.
  26.     $content = do_shortcode( $email_content );
  27.  
  28.     // Restore original current user.
  29.     wp_set_current_user( $original_user_id );
  30.     $GLOBALS['current_user'] = $original_user;
  31.  
  32.     // Ensure output is safe for email.
  33.     return wp_kses_post( $content );
  34. }
  35.  
  36. /**
  37.  * Parses shortcodes in all outgoing emails using user context.
  38.  *
  39.  * @param array $args The email parameters.
  40.  * @return array Modified email parameters.
  41.  */
  42. function myplugin_parse_shortcodes_in_emails( $args ) {
  43.  
  44.     // Bail if no valid recipient.
  45.     if ( empty( $args['to'] ) || ! is_email( $args['to'] ) ) {
  46.         return $args;
  47.     }
  48.  
  49.     // Allow multiple recipients (take first only, or enhance for looping).
  50.     $recipient_email = is_array( $args['to'] ) ? $args['to'][0] : $args['to'];
  51.  
  52.     // Parse the message content using the recipient's user context.
  53.     $args['message'] = parse_email_shortcodes_with_user_context( $args['message'], $recipient_email );
  54.  
  55.     return $args;
  56. }
  57. add_filter( 'wp_mail', 'myplugin_parse_shortcodes_in_emails' );
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement