1

I am trying to display all the pages that have custom fields of a certain value. What I would like to do is use the current page title as the value for the custom field and get all pages that have that value defined.

For example:

  • Current Page is "Surgery".
  • Custom Field Name is "Section".
  • Custom Field Value is "Surgery".

I have been able to do it with post using the following code but I cant seem to work out how to do it with pages.

<?php woo_loop_before(); ?>

<?php
    if ( get_query_var( 'paged') ) { 
        $paged = get_query_var( 'paged' ); 
    } elseif ( get_query_var( 'page') ) { 
        $paged = get_query_var( 'page' ); 
    } else { 
        $paged = 1; 
    }

    $query_args = array(
                        'post_type' => 'post', 
                        'paged' => $paged
                    );

    // Do not remove. Used to exclude categories from displaying here.
    $query_args = apply_filters( '', $query_args ); 

    remove_filter( 'pre_get_posts', 'woo_exclude_categories_homepage' );

    query_posts( $query_args );
query_posts('category_name='.get_the_title().'&post_status=publish,future');    
    if ( have_posts() ) {
        $count = 0;
        while ( have_posts() ) { the_post(); $count++;

            /* Include the Post-Format-specific template for the content.
             * If you want to overload this in a child theme then include a file
             * called content-___.php (where ___ is the Post Format name) 
             * and that will be used instead.
             */
            get_template_part( 'content', get_post_format() );

        } // End WHILE Loop

    } else {
?>
    <article <?php post_class(); ?>>
        <p><?php _e( 'Sorry, no posts matched your criteria.', 'woothemes' ); ?></p>
    </article><!-- /.post -->
<?php } // End IF Statement ?> 

<?php woo_loop_after(); ?>

1 Answer 1

1

You can get pages with get_pages(), in the arguments you can provide a search query for post_meta, like for example:

$args = array(
    'post_type'  => 'page',
    'meta_key'   => 'section',
    'meta_query' => array( array(
        'key'     => 'section'
        'value'   => 'surgery' // here you could place get_the_title()
        'compare' => '='
    ) )
);

$pages = get_pages( $args );

This will return all pages (or any other post types in post_type) with meta_key section and meta_value surgery.

You have to alter the loop if you use this way, build your loop as follow:

foreach( $pages as $page ) : setup_postdata( $page );
...
endforeach; wp_reset_postdata();

Hope this will help you.

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.