ACF - 使用关系字段选择页面

时间:2016-07-20 16:52:25

标签: php html wordpress loops advanced-custom-fields

我目前正在尝试使用ACF关系字段来选择我想要运行某段代码的页面,例如,如果我选择页面A,页面B和页面C,我希望工作和#34;你好"待补充。

到目前为止,我有以下关系字段。

        <?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; ?> 

我的想法是尝试将网址与所选网址相匹配,这意味着如果我的网址为http://www.example.com/pagea并且我选择了网页A,则会显示问号,但遗憾的是到目前为止没有运气。

有没有人知道另一种解决方法?

谢谢!

1 个答案:

答案 0 :(得分:0)

从你的问题来看,看起来这样可以解决问题:

  1. 更改关系字段以保存帖子ID而不是帖子对象。
  2. 更改后,转到您的选项页面,然后重新保存您的现场数据。
  3. 将此代码放在page.php文件中,或者您希望代码运行的位置:

    <?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".';
    } ?>
    
相关问题