# List Posts by an ACF Field Value

> Adds an [acf_posts field="featured" value="1"] shortcode that lists posts whose ACF field matches a value, such as featured items or posts for a region.

- Type: PHP
- Runs: Run everywhere
- Category: [Custom Post Types & Fields](https://wpide.com/library/category/post-types/)
- Tags: acf, query, shortcode
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/acf-posts-by-field-shortcode/

## Code

```php
add_shortcode( 'acf_posts', function ( $atts ) {
    $atts = shortcode_atts( array( 'field' => '', 'value' => '', 'post_type' => 'post', 'limit' => 5 ), $atts, 'acf_posts' );
    $atts['field'] = sanitize_key( $atts['field'] );

    if ( '' === $atts['field'] || ! post_type_exists( $atts['post_type'] ) ) {
        return '';
    }

    $cache_key = 'wpide_acf_posts_' . md5( wp_json_encode( $atts ) . get_option( 'wpide_acf_posts_ver_' . $atts['post_type'], '1' ) );
    $ids       = get_transient( $cache_key );

    if ( false === $ids ) {
        $ids = get_posts( array(
            'post_type'      => $atts['post_type'],
            'posts_per_page' => min( 50, absint( $atts['limit'] ) ),
            'meta_key'       => $atts['field'],
            'meta_value'     => sanitize_text_field( $atts['value'] ),
            'fields'         => 'ids',
            'no_found_rows'  => true,
        ) );
        set_transient( $cache_key, $ids, HOUR_IN_SECONDS );
    }

    if ( ! $ids ) {
        return '';
    }

    $html = '<ul class="acf-posts">';

    foreach ( $ids as $id ) {
        $html .= '<li><a href="' . esc_url( get_permalink( $id ) ) . '">' . esc_html( get_the_title( $id ) ) . '</a></li>';
    }

    return $html . '</ul>';
} );

// Refresh cached lists when content of that type changes.
add_action( 'clean_post_cache', function ( $post_id, $post ) {
    if ( $post && ! wp_is_post_revision( $post ) ) {
        update_option( 'wpide_acf_posts_ver_' . $post->post_type, (string) microtime( true ), false );
    }
}, 10, 2 );
```

## Notes

Add post_type="..." and limit="..." as needed. Results are cached and refresh automatically when content changes.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "List Posts by an ACF Field Value" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
