skip to Main Content

I have a following code and it is so annoying that post_name is automatically converted to lowercase.

$post = array(
    'post_name'    => 'SampleWord',
    ),
);
// assume $post have other necessary fields as well
$post_id = wp_insert_post( $post, true );

When I check the post_name after above code it returns 'sampleword'.
I’ve checked the documentation of wp_insert_post and it mentioned 'post_name' field would be sanitized.
But converting to lowercase characters is not about sanitization.
And how to prevent it?

2

Answers


  1.  $arg = array(
        'post_name'    => 'SampleWord',
        'post_title' => 'I Have CAPS',
        );
    // assume $post have other necessary fields as well
    $post_id = wp_insert_post( $arg, true );
    

    That’s an easy one to confuse because of the names but post_name is really the slug and the documentation warns you it’ll sanitize it (as you noted) but sanitize does also lowercase things.

    Try the post_title addition above and see if it works out for you.

    Login or Signup to reply.
  2. By default the post name is formatted and converted to lower-cased by the filter sanitize_title which hooks into sanitize_title_with_dashes(). As a solution you can replace the filter and omit the lower-case component.

    add_filter( 'sanitize_title', 'custom_sanitize_title', 10, 3 );
    function custom_sanitize_title( $title ) {
    
        $title = strip_tags($title);
        // Preserve escaped octets.
        $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
        // Remove percent signs that are not part of an octet.
        $title = str_replace('%', '', $title);
        // Restore octets.
        $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
    
        $title = remove_accents($title);
        if (seems_utf8($title)) {
                if (function_exists('mb_strtolower')) {
                        $title = mb_strtolower($title, 'UTF-8');
                }
                $title = utf8_uri_encode($title, 200);
        }
    
        // Prevent lower case 
        // $title = strtolower($title);
        $title = preg_replace('/&.+?;/', '', $title); // kill entities
        $title = str_replace('.', '-', $title);
        $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
        $title = preg_replace('/s+/', '-', $title);
        $title = preg_replace('|-+|', '-', $title);
        $title = trim($title, '-');
    
        return $title;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search