Support

Account

Home Forums General Issues Adding Custom Field to Custom Post Type Excerpt Reply To: Adding Custom Field to Custom Post Type Excerpt

  • Hi @avahidesign

    I guess you can approach it in different ways.

    If you’re looping through your CPT, you can simply echo out the custom field if it exists:

    <?php
    global $wp_query;
    $paged = get_query_var('paged') ? get_query_var('paged') : 1;
    $args = array(
    	'posts_per_page' => 10,
    	'post_type'		=> 'your-cpt',
    	'paged' 		=> $paged
    );
    $wp_query = new WP_Query($args); ?>
    <?php if ($wp_query->have_posts()) : ?>
    <?php while ($wp_query->have_posts()) : $wp_query->the_post(); 
    $position = get_field('position');
    ?>
    
    Your loop content
    <?php 
    if($position):
    	echo $position;
    endif;
    ?>
    
    <?php endwhile;  ?> 
    <?php endif; wp_reset_query(); ?>

    Or you can add ACF fields to a custom excerpt:

    // Custom Excerpt function for Advanced Custom Fields
    function custom_field_excerpt() {
    	global $post;
    	$text = get_field('position'); //Replace 'your_field_name'
    	if ( '' != $text ) {
    		$text = strip_shortcodes( $text );
    		$text = apply_filters('the_content', $text);
    		$text = str_replace(']]>', ']]>', $text);
    		$excerpt_length = 20; // 20 words
    		$excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
    		$text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
    	}
    	return apply_filters('the_excerpt', $text);
    }

    Then in your loop, display the custom excerpt:
    echo custom_field_excerpt();