Sanitizing post content for use in an email

I’m sending the content of a custom post type in a plain text email (it’s to send competition entries to a panel of judges), so I need to make sure that $post->post_content is correctly sanitized first.

Is there a filter I can use for this, or if not, what sanitization do I need to do?

Read More

Update: I’ve just found wp_strip_all_tags in wp-includes/formatting.php, is this what I need?

Related posts

Leave a Reply

2 comments

  1. I’m not sure why the accepted answer here was accepted since it is not actually going to work.

    The OP was how to sanitize the email content. sanitize_email() sanitizes an email address. Sure, it won’t throw an error, but it doesn’t actually do anything.

    To sanitize the content, it depends on what is actually intended to be in the content to determine what would be appropriate.

    One generic possibility would be sanitize_textarea_field. This is for the HTML text area field, but it will maintain line breaks. It will strip out all tags.

    However, if the email is intended to be HTML formatted, then you don’t want to strip all tags. In that case, you’d want to use something that allows the tags you want, but strips out the tags you don’t. For that, use wp_kses().

    To use wp_kses() to sanitize your HTML email content, pass the content and an array including allowed tags to the function:

    $allowed_tags = array(
      'p' => array(
        'id' => array(),
        'class' => array(),
      ),
      'a' => array(
        'href' => array(),
        'title' => array()
      ),
      'br' => array(),
      'em' => array(),
      'strong' => array(),
    );
    
    $sanitized_content = wp_kses( $post->post_content, $allowed_tags );
    

    A simplified variation on that above method would be to use wp_kses_post(). This function has preset the allowed tags, which makes it easier since you don’t have to define what tags and attributes are allowed. It’s primarily whatever is allowed for post content.

    $sanitized_content = wp_kses_post( $post->post_content );
    

    If it’s regular post content, then it probably already went through this. If it’s a custom post type, then it depends.

    So which should you use? As I mentioned in the beginning, it depends on the content and how it will be used. If it’s plain text, use something that strips all tags. If it’s HTML, use wp_kses() or a variant.

    See related information on sanitizing in the WP Codex.