add html in wp_mail function wordpress

2019-08-05 01:34发布

问题:

i have created a register form in wordpress but i have a problem with the email confirmation, i'm trying to add some html in the body but i made something wrong, can you help me? this is part of my code in functions.php, is the code that send the email to user:

if ( $user_id && !is_wp_error( $user_id ) ) {
        $code = sha1( $user_id . time() );
        $activation_link = add_query_arg( array( 'key' => $code, 'user' => $user_id ),          get_permalink(168));
        add_user_meta( $user_id, 'has_to_be_activated', $code, true );

        wp_mail( $email, 'BLOOOGERS Activación cuenta', '<img src="..."> <br /> <br />Bienvenido a nuestra comunidad, este es el link para que actives tu cuenta:<br /> <br />' . $activation_link );

        add_filter( 'wp_mail_content_type', 'set_html_content_type' );
        function set_html_content_type() {
            return 'text/html';
        }

    }

回答1:

if ( $user_id && !is_wp_error( $user_id ) ) {
  $code = sha1( $user_id . time() );
  $activation_link = add_query_arg( array( 'key' => $code, 'user' => $user_id ),          get_permalink(168));
  add_user_meta( $user_id, 'has_to_be_activated', $code, true );
  add_filter('wp_mail_content_type',create_function('', 'return "text/html"; '));

  wp_mail( $email, 'BLOOOGERS Activación cuenta', '<img src="..."> <br /> <br />Bienvenido a nuestra comunidad, este es el link para que actives tu cuenta:<br /> <br />' . $activation_link );
}

You need to call the wp_mail_content_type filter hook before using wp_mail function

Hope that helped!



回答2:

This is very easy but add filter code before call wp_mail()

    add_filter('wp_mail_content_type', function( $content_type ) {
                return 'text/html';
    });

    wp_mail( 'me@example.net', 'The subject', '<div>The message</div>' );