How to limit character on $post_title?

Discussion in 'WordPress' started by Divvy, Oct 10, 2015.

  1. #1
    Hello guys,

    Can someone please help me?
    I need to limit character on title using the variable $post_title, how can I do it?

    This is my code:

    <a target="_blank" href="<?php echo get_post_meta($ID,'mr_freeGalleryUrl',true); ?>" rel="nofollow"><?php echo $post_title; ?></a>
    PHP:
    Waiting for your precious help, thanks :)

    Kind regards
     
    Divvy, Oct 10, 2015 IP
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #2
    just change the
    
    <?php echo $post_title; ?>
    
    PHP:
    to
    
    <?php echo substr($post_title,0,20).'&#8230;'; ?>
    
    PHP:
    which will output something like this:
    
    <?php
    $post_title = 'This is a post-title with more than 20 characters which will end up like';
    echo substr($post_title,0,20).'&#8230;';
    ?>
    //output: This is a post-title…
    
    PHP:
    If you don't want the horisontal ellipsis when the post title is below the amount set, you can just do something like this:
    
    <?php
    
    $length = 20;
    
    $post_title = 'This is a post';
    echo substr($post_title,0,$length).((strlen($post_title) > $length) ? '&#8230;' : '');
    
    //output: This is a post
    
    $post_title = 'This is a post-title with more than 20 characters which will end up like';
    echo substr($post_title,0,$length).((strlen($post_title) > $length) ? '&#8230;' : '');
    
    //output: This is a post-title...
    
    ?>
    
    PHP:
     
    PoPSiCLe, Oct 10, 2015 IP
  3. Divvy

    Divvy Well-Known Member

    Messages:
    785
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    128
    #3
    Fixed!! Thank you my friend :D
    You're my savior again :)
     
    Divvy, Oct 11, 2015 IP
  4. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #4
    I'd appreciate a click on the "Best answer" button ;)
     
    PoPSiCLe, Oct 11, 2015 IP
  5. Divvy

    Divvy Well-Known Member

    Messages:
    785
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    128
    #5
    Sure :)
    But I cant see this button here, only in php forum...
     
    Divvy, Oct 12, 2015 IP