Come assegnare un id a ciascuna pagina di WP, oltre alle canoniche classi è possibile aggiungere un ID a ciascuna pagina WordPress per rendere ancora più univoca la pagina stessa.
WordPress mette a disposizione una serie di classi che vengono inserite nel tag body.
Ma se volessi creare un identificativo per ciascuna pagina?
Googlelando qua e là ho trovato questo codice PHP molto semplice (anche se un po’ lunghetto 🙂 ).
Come assegnare un id a ciascuna pagina di WP
La procedura è la seguente:
1. header.php
aggiungere al tag body body_id(); il tag body diverrà, da
<body <?php body_class(); ?>>
a
<body <?php body_id(); ?> <?php body_class(); ?>>
2. functions.php
aggiungere la funzione sottostante:
/** Create a dynamic id on body elements **/ function get_body_id( $id = '' ) { global $wp_query; // If it's an Archive Page if ( is_archive() ) { if ( is_author() ) { $author = $wp_query->get_queried_object(); $id = 'page-archive-author-' . sanitize_html_class( $author->user_nicename , $author->ID ); } elseif ( is_category() ) { $cat = $wp_query->get_queried_object(); $id = 'page-archive-category-' . sanitize_html_class( $cat->slug, $cat->cat_ID ); } elseif ( is_date() ) { if ( is_day() ) { $date = get_the_time('F jS Y'); $id = 'page-archive-day-' . str_replace(' ', '-', strtolower($date) ); } elseif ( is_month() ) { $date = get_the_time('F Y'); $id = 'page-date-' . str_replace(' ', '-', strtolower($date) ); } elseif ( is_year() ) { $date = get_the_time('Y'); $id = 'page-date-' . strtolower($date); } else { $id = 'page-archive-date'; } } elseif ( is_tag() ) { $tags = $wp_query->get_queried_object(); $id = 'page-archive-tag-' . sanitize_html_class( $tags->slug, $tags->term_id ); } else { $id = 'page-archive'; } } // If it's a Single Post if ( is_single() ) { if ( is_attachment() ) { $id = 'page-attachment-'.$wp_query->queried_object->post_name; } else { $id = 'page-single-'.$wp_query->queried_object->post_name; } } // If it's a Page if ( is_page() ) { $id = 'page-'.$wp_query->queried_object->post_name; if ('' == $id ) { $id = 'page-'; } } // Fallbacks if ( is_front_page() ) $id = 'page-front-page'; if ( is_home() ) $id = 'page-blog'; if ( is_front_page() && is_home() ) $id = 'page-front-page'; if ( is_search() ) $id = 'page-search'; if ( is_404() ) $id = 'page-error404'; // If $id still doesn't have a value, attempt to assign it the Page's name if ('' == $id ) { $id = $wp_query->queried_object->post_name; } $id = preg_replace("#\s+#", " ", $id); $id = str_replace(' ', '-', strtolower($id) ); // Let other plugins modify the function return apply_filters( 'body_id', $id ); }; // Print id on body elements function body_id( $id = '' ) { if ( '' == $id ) { $id = get_body_id(); } $id = preg_replace("#\s+#", " ", $id); $id = str_replace(' ', '-', strtolower($id) ); echo ( '' != $id ) ? 'id="'.$id. '"': '' ; };
Se ti è piaciuto, Come assegnare un id a ciascuna pagina di WP, allora potrebbe anche piacerti Aggiungere categorie e tag alle pagine di wordpress