0

please help me,
i have title like this
'1-nen A-gumi no Monster Chapter 2'
'1-nen A-gumi no Monster Chapter 10'
'1-nen A-gumi no Monster Chapter 2'
'1-nen A-gumi no Monster Chapter 1'
'1-nen A-gumi no Monster Chapter 30'
'1-nen A-gumi no Monster Chapter 3'

i want to sort like this
'1-nen A-gumi no Monster Chapter 1'
'1-nen A-gumi no Monster Chapter 2'
'1-nen A-gumi no Monster Chapter 3'
'1-nen A-gumi no Monster Chapter 10'
'1-nen A-gumi no Monster Chapter 20'
'1-nen A-gumi no Monster Chapter 30'

but the result like this
'1-nen A-gumi no Monster Chapter 1'
'1-nen A-gumi no Monster Chapter 10'
'1-nen A-gumi no Monster Chapter 2'
'1-nen A-gumi no Monster Chapter 20'
'1-nen A-gumi no Monster Chapter 3'
'1-nen A-gumi no Monster Chapter 30'

this my function :

add_filter( 'posts_clauses', function ( $pieces, $query ) {
    if ( $query->get( 'orderby' ) != 'title_number' ) return $pieces;
    global $wpdb;
    $field = $wpdb->posts . '.post_title';
    $pieces[ 'fields' ] .= $wpdb->prepare(
        ', LEAST(' . implode( ',', array_fill( 0, 10, 'IFNULL(NULLIF(LOCATE(%s, ' . $field . '), 0), ~0)' ) )
        . ') AS first_int',
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
    );
    $pieces[ 'orderby' ] = $wpdb->prepare(
        'IF(first_int = ~0, ' . $field . ', CONCAT('
            . 'SUBSTR(' . $field . ', 1, first_int - 1),'
            . 'LPAD(CAST(SUBSTR(' . $field . ', first_int) AS UNSIGNED), LENGTH(~0), %s),'
            . 'SUBSTR(' . $field . ', first_int + LENGTH(CAST(SUBSTR(' . $field . ', first_int) AS UNSIGNED)))'
        . ')) ' . $query->get( 'order' )
        , 0
    );
    return $pieces;
}, 10, 2 );

but if the first character of title is letter the sort is normal.

please help thank you

  • You'll have to sort by another field. PHP sorts alphanumerically, and so 10 comes before 2, 20 comes before 3, etc. – WebElaine Jun 4 at 17:59
  • Agree that you should sort by another field, or - if you only have a relatively small number of posts - load them all into PHP and sort from there. – vancoder Jun 4 at 21:32
  • but i have 3.024 post bro :( – Bayu Fajar Rizki Jun 5 at 16:32

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.