简体   繁体   中英

Filter a page by a field name (Advanced Custom Fields & Wordpress)

I am using Wordpress and Advanced Custom Fields.

I want to be able to create pages that display excerpts of different pages or filters them.

Example: I have 10 different pages, each one about a hotel, they have various information stored in fields (Advanced Custom Fields) about the hotel, hotel name, location, facilities etc..

The 10 hotels are child pages of a main page, the main page displays all of the hotels on it, but only certain details about the hotel, such as an excerpt of the description and an image.

I created another Advanced Custom Field called Category, to try and test if I could get it to work I have only filled in the field with "Hotel" for a few of the actual hotel related pages.

What I am struggling to do is write some code, so that page only displays the hotels that are under the category of "Hotel", I am writing the code in a template file, so the main Hotel page that lists all hotels is using this template.

All are using pages and not posts, all information is stored in fields via Advanced Custom Fields plugin.

I presume the code should be using if and else functions to work.

If anyone can help me with this problem It would be much appreciated.

It seems you would like to query for pages with a certain custom field set to a specific value. To do this you can use a meta query in your page template, like this:

<?php
$args = array(
    'post_type' => 'page',
    'meta_query' => array(
        array(
            'key' => 'Category',
            'value' => 'Hotel',
            'compare' => 'LIKE'
        )
    ),
        'posts_per_page' => get_option('posts_per_page')
 );
$hotel_query = new WP_Query( $args );
?>

For more advanced queries with custom fields, check the documentation on custom field parameters in WP_Query .

Once you have fetched your custom query, you could loop through the results almost like normal:

<ul>
<?php if ( $hotel_query->have_posts() ) : while ( $hotel_query->have_posts() ) : $hotel_query->the_post(); ?>
    <li><?php the_title(); ?></li>

<?php endwhile; endif; ?>
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM