问题描述
我需要隐藏一段代码,使其不显示在某些页面中。这些页面都是 ID 为 8194 的父页面的子页面和兄弟页面。
为了隐藏子页面中的代码,我使用了 if ( get_post_field( 'post_parent' ) != 8194 )
,但问题是有多个兄弟页面,并且该代码对它们不起作用,它只能在子页面中起作用。
这是我的页面层次结构:
Parent page 1
- Child page 1
-- Sibling page 1
-- Sibling page 2
...
-- Sibling page 10
谢谢
解决方法
如果我理解正确,您想找到最顶层的父级。
为此,我将使用 get_post_ancestors()
检索帖子祖先的 ID(并返回一个父数组):https://developer.wordpress.org/reference/functions/get_post_ancestors/
尝试这样的事情:
global $post;
$parents = get_post_ancestors($post->ID);
// Get the 'top most' parent page ID,or return 0 if there is no parent:
$top_parent_id = ($parents) ? $parents[count($parents)-1]: 0;
if ($top_parent_id != 8194) {
...
}
,
** OP 的第二个问题的更新代码来自评论:**
global $post;
// Don't show the code by default:
$show_code = false;
// This is an array of post ids where you want to show the code regardless of the parents id
$always_show_the_code_on_these_posts = array(111,222,333);
// Check if current post id is on the list:
if ( in_array($post->ID,$always_show_the_code_on_these_posts) ) {
$show_code = true;
} else {
// ...and only if it's not on the list run the previous test:
$parents = get_post_ancestors($post->ID);
// Get the 'top most' parent page ID,or return 0 if there is no parent:
$top_parent_id = ($parents) ? $parents[count($parents)-1]: 0;
if ($top_parent_id != 8194) {
$show_code = true;
}
}
if ($show_code) {
...
}
,
您可以使用 wp_get_post_parent_id()
函数通过与 get_the_ID()
函数进行比较来检查当前页面是父页面还是子页面。 is_page()
在这里,只是一个冗余。
<?php
/**
* wp_get_post_parent_id
* Returns the ID of the post’s parent.
* @link https://developer.wordpress.org/reference/functions/wp_get_post_parent_id/
*
* get_the_ID
* Retrieve the ID of the current item in the WordPress Loop.
* @link https://developer.wordpress.org/reference/functions/get_the_ID/
*/
if( is_page() && wp_get_post_parent_id( get_the_ID() ) ):
//child
echo 'This is THE Child,Grogu';
else:
//parent
echo 'This is THE Mandalorian,Mando';
endif; ?>