PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 9, 2022

[FIXED] Wordpress - How can I get_categories from additional custom post?

 January 09, 2022     categories, html, php, wordpress     No comments   

Issue

My goal is to get the Categories from the additional custom post I've registered in functions.php. How can I get its categories and echo it on my page? here are my code so far: from page:

 <?php
   $args = array(
   'post_type' => 'pdf',
   'orderby' => 'slug',
   'order' => 'ASC',
   'parent' => 0,
   'hide_empty' => false
   );
   $categories = get_categories($args);
   foreach( $categories as $category ){
   echo '<option><a class="ctg" href="'. get_category_link( $category->term_id ) .' ">' . $category->name . '</a></option>';
   }
  ?>      

from functions.php

  $args = array(
   'label' => 'category',
   'public' => true,
   'show_ui' => true,
   'show_in_nav_menus' => true,
   'show_admin_column' => true,
   'hierarchical' => true,
   'query_var' => true
  );
    register_taxonomy('pdf_cat','pdf',$args);
   

Echo the existing post when hit the specific category:

                    <?php
                  $cat = get_the_category();
                  $cat = $cat[0]; 
                  $catname = get_cat_name($cat->term_id); 
                  $catid = get_cat_ID($catname);  
                ?>
                  
                <?php
                      $paged = get_query_var('paged', 1);
                      $args = array(  
                          'post_type' => 'pdf',
                          'paged' => $paged,
                          'post_type' => 'post',
                          'cat' => $catid,
                      );
                      $query = new WP_Query($args);         
             
                  global $query_string; 
                  query_posts( $query_string . "&posts_per_page=15&paged=".$paged );
                  while ( have_posts() ) : the_post()
                ?>

Solution

Categories on custom post types in wordpress are use the taxonomy functions. You can use get_terms to fetch the "categories" in this case.

Example

$categories = get_terms([
    'taxonomy' => 'pdf_cat',
    'hide_empty' => false,
]);


Answered By - infamoustrey
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing