Custom trim my post title item combine two if

127 Views Asked by At

based on this example

add_filter( 'facetwp_builder_item_value', function( $value, $item ) {
    if ( 'post_excerpt' == $item['source'] ) {
        $value = substr( $value, 0, 120 );
    }
    return $value;
}, 10, 2 );

I would like to trim post_title to a maximum limit of 120 with the (...) at the end.

This objective was not achieved with my modification and I failed several times with several combinations

   // my actual attemp to trim post_title item

   add_filter( 'facetwp_builder_item_value', function( $value, $item ) {
    if ( 'post_title' == $item['source'] ) {
          $raw_value = $item['source'];
      if ( 120 < strlen( $raw_value ) ) {
            $value['source'] = substr( $raw_value, 0, 120 ) . "...";
        }
    }
    return $value;
}, 10, 2 );

following the logic of the things based on this exemple mentioned here

// Add the following to your theme's functions.php
add_filter( 'facetwp_index_row', function( $params, $class ) {
    if ( 'aufsichtsbehoerden' == $params['facet_name'] ) {
        $raw_value = $params['facet_value'];
        if ( 50 < strlen( $raw_value ) ) {
            $params['facet_value'] = substr( $raw_value, 0, 50 ); // cut off some of the value
        }
    }
    return $params;
}, 10, 2 );

Experts in PHP and use filters are requested to join me to tell me what I missed as a modification ..

2

There are 2 best solutions below

3
BiOS On BEST ANSWER

Nest your if statements, and add some way of tracking the bug.

add_filter( 'facetwp_builder_item_value', function( $value, $item ) {
    if ( 'post_title' == $item['source']) {
        $maxLength = 120;
        echo "POST TITLE == ITEM SOURCE";
        if (strlen($value) > $maxLength) {
            echo "POST TITLE EXCEEDED MAX LENGTH";
            $value = substr( $value, 0, $maxLength) . '…';
        }
    }
return $value;
}, 10, 2 );

I have added two echo functions to allow you to understand where and when the conditions are met.

1
Enrico Dias On

Your first if is doing nothing in the first code. Notice that there are nothing between its brackets { }.

Your second code is combining both conditions correctly. If it doesn't work, 'post_title' is probably not equal to $item['source'].