Căutați o modalitate de a afla dacă o pagină de pe site-ul dvs. WordPress este o pagină copil sau nu? Deși probabil există un plugin pentru asta, am creat o scurtă secțiune de cod pe care o puteți utiliza pentru a verifica dacă o pagină este o pagină copil în WordPress.
Instrucțiuni:
Tot ce trebuie să faceți este să adăugați acest cod în fișierul functions.php al temei dvs. sau într-un plugin specific site-ului:
/*
* 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">
*/
Notă: Dacă aceasta este prima dată când adăugați fragmente de cod în WordPress, consultați ghidul nostru despre cum să adăugați corect fragmente de cod în WordPress, pentru a nu vă defecta accidental site-ul.
Dacă v-a plăcut această secțiune de cod, vă rugăm să luați în considerare să consultați celelalte articole de pe site, cum ar fi: Cele mai bune 7 plugin-uri de sondaje WordPress pentru a crește implicarea pe site și Cum să configurați urmărirea descărcărilor în WordPress cu Google Analytics.
Bună, există o eroare de sintaxă la #39