Search code examples
wordpressadvanced-custom-fields

WordPress : display page if have special template and custom field


I would like to display, in a page,, a list of page which has:

  • a custom template
  • AND a custom field

I know how to display page with custom template, it works:

<?php $args = array(
        'post_type' => 'page',
    'posts_per_page' => 1,
    'orderby' => 'rand',
    'meta_query' => array(
        array(
            'key' => '_wp_page_template',
            'value' => 'custom-template.php'
        )
    )
);
$the_pages = new WP_Query( $args );
if( $the_pages->have_posts() ){
    while( $the_pages->have_posts() ){
        $the_pages->the_post(); ?>
        <h2><?php the_title; ?></h2>
    <?php }
} wp_reset_postdata(); ?>
<?php } ?>

But I would like to add a condition: display only if they have the custom field "hello".

Probably I should add something like this but I don't know where, I tried different things and it doesn't work.

array(
'key' => 'hello'
)

Do you have an idea? Thanks in advance for your help!


Solution

  • You need to add the custom field key and value to your meat query like you have done for page template:

    'meta_query' => array(
        array(
            'relation' => 'AND',
            array(
                'key'     => '_wp_page_template',
                'value'   => 'custom-template.php',
                'compare' => '='
            ),
            array(
                'key'     => 'hello',
                'value'   => '',
                'compare' => '!='
            ),
        )
    );