PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 10, 2022

[FIXED] how to apply following snippet to mobile only

 November 10, 2022     code-snippets, html, php, wordpress     No comments   

Issue

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.


Solution

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.



Answered By - Shoelaced
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing