Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Function to add new fields to WP tags
- function custom_tag_fields($term) {
- // Get term meta data
- $term_metas = [
- 'entity_name' => get_term_meta($term->term_id, 'entity_name', true),
- 'google_entity_url' => get_term_meta($term->term_id, 'google_entity_url', true),
- 'wikipedia_url' => get_term_meta($term->term_id, 'wikipedia_url', true),
- 'wikidata_url' => get_term_meta($term->term_id, 'wikidata_url', true)
- ];
- // Fields to add
- $fields = [
- 'entity_name' => 'Entity Name',
- 'google_entity_url' => 'Google Entity URL',
- 'wikipedia_url' => 'Wikipedia URL',
- 'wikidata_url' => 'Wikidata URL'
- ];
- foreach ($fields as $field_id => $label) {
- ?>
- <tr class="form-field">
- <th scope="row" valign="top"><label for="<?php echo $field_id; ?>"><?php _e($label); ?></label></th>
- <td>
- <input type="text" name="<?php echo $field_id; ?>" id="<?php echo $field_id; ?>" value="<?php echo esc_attr($term_metas[$field_id]); ?>">
- </td>
- </tr>
- <?php
- }
- }
- add_action('post_tag_edit_form_fields', 'custom_tag_fields');
- // Function to save the new custom fields data
- function save_custom_tag_fields($term_id) {
- // Fields to save
- $fields = [
- 'entity_name' => 'sanitize_text_field',
- 'google_entity_url' => 'esc_url_raw',
- 'wikipedia_url' => 'esc_url_raw',
- 'wikidata_url' => 'esc_url_raw'
- ];
- foreach ($fields as $field_id => $sanitize_func) {
- if (isset($_POST[$field_id])) {
- update_term_meta($term_id, $field_id, $sanitize_func($_POST[$field_id]));
- }
- }
- }
- add_action('edited_post_tag', 'save_custom_tag_fields');
- // Function to add schema to the posts and tag pages
- function add_sameAs_schema_rank_math( $data, $jsonld ) {
- if(is_single() || is_tag()) {
- global $post;
- $post_tags = wp_get_post_tags($post->ID);
- if (!empty($post_tags)) {
- foreach ($post_tags as $tag) {
- $entity_name = get_term_meta($tag->term_id, 'entity_name', true);
- $sameAs_array = array_filter([
- get_term_meta($tag->term_id, 'google_entity_url', true),
- get_term_meta($tag->term_id, 'wikipedia_url', true),
- get_term_meta($tag->term_id, 'wikidata_url', true)
- ]); // Remove empty elements
- if (!empty($entity_name) && !empty($sameAs_array)) {
- // Create schema array
- $schema = [
- "@type" => "Thing",
- "name" => $entity_name,
- "sameAs" => $sameAs_array
- ];
- // Add to Article schema on single posts
- if(is_single() && isset($data['Article'])) {
- $data['Article']['about'][] = $schema;
- }
- // Add to CollectionPage schema on tag pages
- if(is_tag() && isset($data['CollectionPage'])) {
- $data['CollectionPage']['about'][] = $schema;
- }
- }
- }
- }
- }
- return $data;
- }
- add_filter( 'rank_math/json_ld', 'add_sameAs_schema_rank_math', 10, 2 );
Advertisement
Add Comment
Please, Sign In to add comment