Question

I am using a ACF select field to enable the page admin to select a category of posts to display under the page content. For example, if he selects "Televisions" in the ACF select field, all posts in that category will display after the page content. Here is the code for that bottom part of the page (after the main content), from the page template:

<h2>Learn more about <?php the_field('main_page'); ?></h2>
<ul>

<?php 
$main_page=get_field('main_page');

$related_systems = new WP_Query( 'category_name='.$main_page );
while( $related_systems->have_posts() ) : $related_systems->the_post();

if($post->post_type == 'post'):

?>
<li><a href="#"><?php the_title();?></a></li>
<?php 
endif;
endwhile; ?>
</ul>

Here is the ACF settings screenshot

The select field shows up fine on the admin side in all four pages that have the Main four page template, but both get_field('main_page') or the_field('main_page') end up blank (I tested get_field with echo and nothing shows up). How To get the field value in the page template?

I'm using WordPress 3.8.1 and ACF Version 4.3.5

Was it helpful?

Solution

Inside the main content, add $page_id = get_the_ID();.

And in the custom loop, call the fields:

the_field( 'main_page', $page_id );

get_field( 'main_page', $page_id );

Those functions work without an ID if used inside the loop, otherwise we need to specify what post we are requesting.

Also, you can filter the post type when calling WP_Query:

WP_Query ( 'post_type=post&category_name=' . $main_page );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top