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.
Opens WPIDE on
Code
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 add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.