¿Estás buscando una forma de saber si una página en tu sitio de WordPress es una página hija o no? Si bien probablemente haya un plugin para esto, hemos creado un fragmento de código rápido que puedes usar para verificar si una página es una página hija en WordPress.
Instrucciones:
Todo lo que tienes que hacer es agregar este código al archivo functions.php de tu tema o a un plugin específico del sitio:
/*
* Checks if the page is the parent or a child of the page matching the $pid param
* $pid can be the page slug or the page ID #
*
* This function is best used to display menus when the parent/top level menu item needs
* a rollover state or special treatment.
*
* @param $pid (string or int)
* returns true if current page ID matches , else return false
*/
function is_child( $pid ) { // = The ID of the page we're looking for pages underneath
global $post; // load details about this page
// if $pid is an ID
if (is_int($pid)) {
if ( is_page($pid) )
return true;
// get the page's children if the ID of a child matches the return true
$anc = get_post_ancestors( $post->ID );
foreach ( $anc as $ancestor ) {
if( is_page() && $ancestor == $pid ) {
return true;
}
}
}
// if is a page slug
elseif (is_string($pid)) {
// Get page by 'SLUG'
$page = get_page_by_path( $pid );
if ($post->ID == $page->ID) {
return true;
}
$anc = get_post_ancestors( $post->ID );
foreach ( $anc as $ancestor ) {
if( is_page() && == $page->ID ) {
return true;
}
}
}
return false; // we arn't at the page, and the page is not an ancestor
}
/*
Used in a template:
<img src="home<?php if (is_child(0)){?>-ro<?php } ?>.jpg">
or
<img src="home<?php if (is_child('home')){?>-ro<?php } ?>.jpg">
if true equals
<img src="home-ro.jpg">
*/
Nota: Si es la primera vez que agregas fragmentos de código en WordPress, consulta nuestra guía sobre cómo agregar fragmentos de código correctamente en WordPress, para que no rompas accidentalmente tu sitio.
Si te gustó este fragmento de código, considera echar un vistazo a nuestros otros artículos en el sitio como: Los 7 mejores plugins de encuestas de WordPress para aumentar la participación en el sitio y cómo configurar el seguimiento de descargas en WordPress con Google Analytics.
Hola, hay un error de sintaxis en la línea #39