Forums

How to truncate get_post_meta / custom fields ? (2 posts)

  1. kReEsTaL
    Member
    Posted 3 years ago #

    Hello guys,

    I'm looking for a way to dynamically truncate the custom fields that appear on my site's homepage.

    I'm using this code:

    <?php $posts = get_posts('numberposts=3&offset=1&category=3'); foreach ($posts as $post): setup_postdata($post); ?>
    
    <a href="<?php the_permalink(); ?>"><?php echo get_post_meta($post->ID, 'titre_propre',true) ?></a>

    "titre_propre" is the personal custom field I'd like to truncate to, let's say, 40 characters.

    Can anybody help me with this, please? That'd be much, much appreciated :)

    Regards,

    kReEsTaL

  2. kReEsTaL
    Member
    Posted 3 years ago #

    Ok, I got it.

    I simply used the fonction spencerp shared in this topic, customizing it by declaring the variable I needed:

    - in functions.php:

    function the_title2($before = '', $after = '', $echo = true, $length = false) {
    global $post;
    $title = get_post_meta($post->ID, 'key_of_your_custom_field',true);
    
    if ( $length && is_numeric($length) ) {
    
    $title = substr( $title, 0, $length );
    }
    
    if ( strlen($title)> 0 ) {
    
    $title = apply_filters('the_title2', $before . $title . $after, $before, $after);
    
    if ( $echo )
    
    echo $title;
    
    else
    
    return $title;
    }
    }

    - in the template where you need to truncate your custom field, simply use:

    <?php the_title2('', '...', true, '40') ?>

    ...where 40 is the number of characters you want to display.

    Yay me! :D

Topic Closed

This topic has been closed to new replies.

About this Topic