我目前正在尝试使用ACF关系字段来选择我希望某段代码在哪些页面上运行,例如,如果我选择页面a、页面B和页面C,我希望添加工作"hello"。
到目前为止,我有以下关系字段。
<?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; ?>
我的想法是尝试将URL与所选的URL进行匹配,这意味着如果我的URLhttp://www.example.com/pagea我选择了页面A,它会显示你好,但不幸的是,到目前为止没有运气。
有人有别的办法吗?
谢谢!
从你的问题来看,这似乎可以做到:
- 更改关系字段以保存Post ID而不是Post Object
- 更改后,转到选项页面,然后重新保存字段数据
-
将此代码放在您的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".'; } ?>