1

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 subfields is randomly generated. How do I allow for this, so that I’m able to generate a list of pages using this row layout?

0

I posted this on the ACF support forum as well and got great feedback: https://support.advancedcustomfields.com/forums/topic/query-pages-for-use-of-a-flexible-content-layout/

With a bit of tweaking, it worked. Here's what I ended up with:

<?php
    $flex_content_name = 'flexible_content';  // < update with applicable field name
    $layout_name = 'featured-resources';  // < update with applicable subfield name
    $args = array(
        'posts_per_page'    => -1,
        'post_type'     => 'page',
        'meta_query'    => array(
            array(
                'key'       => $flex_content_name,
                'value'     => '"'.$layout_name.'"',
                'compare'   => 'LIKE'
            )
        )
    );

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.