wp get custom post category code example
Example 1: wordpress get post category name
<?php
$categories = get_the_category();
if ( ! empty( $categories ) ) {
echo esc_html( $categories[0]->name );
}
?>
Example 2: create custom post type with category in wordpress functions.php
function create_posttype() {
register_post_type( 'wpll_product',
array(
'labels' => array(
'name' => __( 'Products' ),
'singular_name' => __( 'Product' )
),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'products'),
)
);
}
add_action( 'init', 'create_posttype' );
Example 3: get primary category of post wordpress
This is not a native wordpress feature, but a feature of Yoast SEO (see here).
You can check for primary status the following way:
<?php
$term_list = wp_get_post_terms($post->ID, 'category', ['fields' => 'all']);
foreach($term_list as $term) {
if( get_post_meta($post->ID, '_yoast_wpseo_primary_category',true) == $term->term_id ) {
}
}
?>
If you are using custom taxonomies, use the meta_key
_yoast_wpseo_primary_CUSTOM_TAXONOMY
instead