1

I have a function that trims my post title and I escape the final output using wp_kses.

Is this the right approach?

function theTrimmedPostTitle( $length = BIG_INT, $delimiter = '' )
{
    $title = get_the_title();
    $url = esc_url( get_permalink() );

    if( $length > 0 ) {
        $trimmed_title = mb_strimwidth( $title, 0, $length, '' );
        $title = $trimmed_title . ( strlen( $title ) > strlen( $trimmed_title ) ? $delimiter : '' );
    }

    $title_string = sprintf(
        '<a href="%s" rel="bookmark">%s</a>',
        $url,
        $title
    );

    $escaped_title = wp_kses(
        $title_string,
        $allowed_html = [
            'a' => [
                'href' => [],
                'rel' => [],
            ]
        ]
    );

    return $escaped_title;
}

Another thought would be that since I'm building my string with $title_string where I specifically say what my output must be, doesn't it make more sense to have it there instead of after?

Additionally, if my post title contains <div>, it doesn't get output, but this could be problematic for plugins that do insert HTML on the title and also for say, programming bloggers - that <div> that was meant as a string is now not displayed.

So I was thinking, how about I esc_html the title itself?

$title_string = sprintf(
    '<a href="%s" rel="bookmark">%s</a>',
    esc_url( $url ),
    esc_html( $title )
);

$escaped_title = wp_kses(
    $title_string,
    $allowed_html = [
        'a' => [
            'href' => [],
            'rel' => [],
        ]
    ]
);

Of course, I understand that I'm pulling the title which is already sanitized by WordPress itself, but cough a few markets have certain requirements which make no sense, so I have to do this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.