简体   繁体   中英

ACF - Using relationship field to select page

I am currently trying to use the ACF relationship field to select which pages I would like a certain piece of code to run on, for example, if I select Page A, Page B and Page C, I would like the work "hello" to be added.

So far, I have the below Relationship field.

        <?php
$posts = get_field('which_venue', options);

if( $posts ): ?>
    <ul>
    <?php foreach( $posts as $post): // variable must be called $post (IMPORTANT) ?>
        <?php setup_postdata($post); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
          <?php
          $thisurl = the_permalink(); 
          // echo $thisurl;             

            $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
            if($url == $thisurl) {
    echo "match";
}
?>
        </li>
    <?php endforeach; ?>
    </ul>
    <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
<?php endif; ?> 

My idea was to try and matchthe URL with the url selected, meaning if my URL was http://www.example.com/pagea and I had selected Page A, it would display hello, but unfortunately no luck so far.

Does anyone have an idea of another way around this?

Thanks!

From your question, it looks like this would do the trick:

  1. Change your relationship field to save Post IDs instead of Post Object.
  2. Once changed, go to your options page, and re-save your field data.
  3. Place this code in your page.php file, or wherever you want your code to run:

     <?php //Check if this page is selected in which_venue //Get the selected fields $selectedPages = get_field('which_venue', options); //Get the current page's ID $myID = get_the_ID(); //Check if the current page's ID exists inside the selected fields array. if(in_array($myID, $selectedPages)){ //Run your code echo 'This Page was selected in "which_venue".'; }else{ //Run other code echo 'This Page was NOT selected in "which_venue".'; } ?> 

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