
I have a site that originally used a repeater field for selecting layout options. I now use the flexible content field. I need to be able to query the site for pages that use “featured-resources” as a row layout.
In the past, I could query sub-fields of the repeater field using this within a custom template:
function query_subfields( $where ) {
$where = str_replace("meta_key = 'mods_$", "meta_key LIKE 'mods_%", $where);
return $where;
}
add_filter('posts_where', 'query_subfields');
<?php
$args = array(
'posts_per_page' => -1,
'post_type' => 'page',
'meta_query' => array( array(
'key' => 'mods_$_choose_module', // WHAT REPLACES choose_module ??
'value' => 'Featured Resources',
'compare' => '='
))
);
$the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>
<ul>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
<?php else : ?>
<p>No matches.</p>
<?php endif; ?>
<?php wp_reset_query(); ?>
Now that I’m using flexible content, I don’t know how to define the 2nd part of the key. Content templates use get_row_layout(); to add field contents to pages, but this is not a key. From what I’ve read, I believe the key for these sub-fields is randomly generated. How do I allow for this, so that I’m able to generate a list of pages using this row layout?
In the DB the flex field is stored as an array of layout names.
$flex_field_name = 'name of your flex field here';
$layout_name = "name of your layout here";
$args = array(
'post_type' => 'page',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => flex_field_name,
'value' => '"'.$layout_name.'"'
'compare' => 'LIKE'
)
}
);
Very close! We just need a $ sign in front of that key variable, and it works!
'key' => $flex_field_name,
Thanks much! Mean it!