Accessing Advanced Custom Fields by Page Name

I am trying to retrieve all advanced custom fields tied to a particular page. This is different than iterating through posts, I am familiar with the following:

$posts = get_posts(array(
    'post_type'     => 'post_name',
    'meta_key'      => 'color',
    'meta_value'    => 'red'
));

However this method is specific to posts and does not allow me to retrieve all ACF by page name.

Read More

I appreciate any suggestions on how to accomplish this.

Related posts

2 comments

  1. The are too ways to do this that come to mind…

    1. Using the Loop

    Using WP_Query you can do something like this…

    <?php
    
    // WP_Query arguments
    $args = array (
        'pagename'               => 'homepage',
    );
    
    // The Query
    $query = new WP_Query( $args );
    
    // The Loop
    if ( $query->have_posts() ) {
        while ( $query->have_posts() ) {
            $query->the_post();
            the_field( "field_name" ); 
        }
    } else {
        // no posts found
    }
    
    // Restore original Post Data
    wp_reset_postdata();
    
    ?>
    

    In place of the ‘homepage’ in 'pagename' => 'homepage', you want to put the page slug of your page. And of course in place of the_field( "text_field" ); you want to add your fields/content.

    You can also query by Page ID and some other parameters. You can find all other parameters that you can use here:
    https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters

    2. Adding second parameter to the_field() function

    More simple way, without custom loop, is just to use ACF’s built-in the_field() function with the $post->ID parameter added as a second parameter.

    <?php the_field('field_name', 123);
    

    This might be the way to go since you want to show the content of only one page, and therefore don’t really need to loop.

    Reference: http://www.advancedcustomfields.com/resources/how-to-get-values-from-another-post/

Comments are closed.