php – How to output the taxonomies that are assigned to each custom post?

Question

I’m trying to loop through all custom posts and output the taxonomies that are assigned to each post. The code below is currently just outputting every taxonomy available to the post, even if it isn’t assigned to it.. No clue why, maybe someone can help?


  function create_custom_xml_sitemap($post_ID, $post_after, $post_before)
  {
      $post_type = get_post_type($post_ID);
      if ($post_type == 'expertise_posts') {
          $sitemap = '<?xml version="1.0" encoding="UTF-8"?>';
          $sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    
          $args = array(
            'post_type' => 'expertise_posts',
            'posts_per_page' => -1,

        );

          $the_query = new WP_Query($args);

          if ($the_query->have_posts()) :
          while ($the_query->have_posts()) : $the_query->the_post();

          $home_url = get_home_url();
          $url = get_permalink();

          $taxonomy_objects = get_object_taxonomies('expertise_posts', 'objects');
          foreach ($taxonomy_objects as $taxonomy_slug => $taxonomy) {
              $terms = get_terms($taxonomy_slug, 'hide_empty=0');
              if (!empty($terms)) {
                  foreach ($terms as $term) {
                      $sitemap .= $term->name;
                  }
              }
          }
          
          endwhile;
          endif;

          $sitemap .= '</urlset>';
      }

      $fp = fopen(ABSPATH . "test.xml", 'w');
      fwrite($fp, $sitemap);
      fclose($fp);
  }
add_action('post_updated', 'create_custom_xml_sitemap', 21, 3);

0
user205498 3 weeks 2021-04-26T18:25:08-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse