Home > OS >  how to apply following snippet to mobile only
how to apply following snippet to mobile only

Time:11-09

the code:

add_filter( 'the_title', 'shorten_woo_product_title', 10, 2 );
function shorten_woo_product_title( $title, $id ) {
    if ( ! is_singular( array( 'product' ) ) && get_post_type( $id ) === 'product' && strlen( $title ) > 30 ) {
        return substr( $title, 0, 30) . '…'; // change last number to the number of characters you want
    } else {
        return $title;
    }
}

I know I should add wp_is_mobile() somewhere but don't know where should I add it exactly.

CodePudding user response:

If you want to use wp_is_mobile() then it just returns a boolean, so you could use it anywhere that wraps the output:

add_filter( 'the_title', 'shorten_woo_product_title', 10, 2 );

function shorten_woo_product_title( $title, $id ) {

    if ( wp_is_mobile() ) {
        if ( ! is_singular( array( 'product' ) ) && get_post_type( $id ) === 'product' && strlen( $title ) > 30 ) {
            return substr( $title, 0, 30) . '…'; // change last number to the number of characters you want
        } else {
            return $title;
        }
    }

    return $title;
}

But remember that if you use page caching a mobile user may be the one to generate the cache, and thus your cache will include the change and display everywhere. Given that this specific context is WooCommerce and therefore that maybe you're not caching the product pages if you need them to be dynamic somehow, this may work anyway, but @markus-ao's comment above would be a better solution if caching is an issue.

  • Related