Home Forums General Issues Adding Custom Field to Custom Post Type Excerpt


Adding Custom Field to Custom Post Type Excerpt

  • I have a custom post type for staff members. On the about page I have a post grid that pulls those custom posts to show each staff member. For the design I need to be able to update the post excerpt using one of the custom field types I already have set up. The field type is a text field with the id “position”. Can anybody point me in the right direction? Found some other similar topics but they weren’t working.

  • 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:

    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
    	echo $position;
    <?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();

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.