Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Parses shortcodes in email content with the correct user context.
- *
- * @param string $email_content The email content with shortcodes.
- * @param string $user_email The email address of the user to simulate context.
- * @return string The parsed and sanitized email content.
- */
- function parse_email_shortcodes_with_user_context( $email_content, $user_email ) {
- // Look up the user by email.
- $user = get_user_by( 'email', $user_email );
- if ( ! $user ) {
- return $email_content; // No user found, return unparsed.
- }
- // Backup the current user globals.
- $original_user_id = get_current_user_id();
- $original_user = $GLOBALS['current_user'] ?? null;
- // Override current user globals.
- wp_set_current_user( $user->ID );
- $GLOBALS['current_user'] = $user;
- // Allow shortcodes to reference current user context.
- $content = do_shortcode( $email_content );
- // Restore original current user.
- wp_set_current_user( $original_user_id );
- $GLOBALS['current_user'] = $original_user;
- // Ensure output is safe for email.
- return wp_kses_post( $content );
- }
- /**
- * Parses shortcodes in all outgoing emails using user context.
- *
- * @param array $args The email parameters.
- * @return array Modified email parameters.
- */
- function myplugin_parse_shortcodes_in_emails( $args ) {
- // Bail if no valid recipient.
- if ( empty( $args['to'] ) || ! is_email( $args['to'] ) ) {
- return $args;
- }
- // Allow multiple recipients (take first only, or enhance for looping).
- $recipient_email = is_array( $args['to'] ) ? $args['to'][0] : $args['to'];
- // Parse the message content using the recipient's user context.
- $args['message'] = parse_email_shortcodes_with_user_context( $args['message'], $recipient_email );
- return $args;
- }
- add_filter( 'wp_mail', 'myplugin_parse_shortcodes_in_emails' );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement