WordPress Plugin that allows publishers/users to designate a primary category for posts/custom post types and query posts/custom post types based on their primary categories
- Copy the
primary-category
folder into yourwp-content/plugins
folder - Activate the
Primary Category
plugin via the plugin admin page
- Open the settings page from your dashboard Settings > Primary Category.
- Select the taxonomies what you want to enable the feature.
- After selecting taxonomies, click in the save changes button.
After enabling a taxonomy from settings, select primary categories from post-edit or post-new screen.
Name | Argument(s) |
---|---|
the_primary_category | $taxonomy required support mixed ( int, WP_Term, object, string ) ----- $post_id required support mixed ( int, WP_Post, NULL ) default value: NULL ----- string $output optional default value: "link" others values: "name" ----- $echo optional default value: true |
Basic example
$args = array(
'post_type' => 'product',
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
echo the_title();
echo "<br/>"
the_primary_category( 'product_cat', get_the_ID(), 'link' );
}
}
Note:
-- $taxonomy and $post_id are required parameters and must be used when using the function
-- $output can be link or name
-- Function can be used with or without echo
Filter | Argument(s) |
---|---|
primary_category_html | string $html mixed ( int, WP_Term, object, string ) $taxonomy required mixed ( int, WP_Post, NULL ) $post_id required string $output |
Tag | Attribute(s) |
---|---|
primary_category | mixed ( int, WP_Term, object, string ) taxonomy required -- mixed ( int, WP_Post, NULL ) post-id default value: NULL required -- string output default value: "link" others values: "name" optional |
[primary_category taxonomy="category"]
[primary_category taxonomy="category" post-id="12"]
[primary_category taxonomy="category" post-id="12" output="link"]
See below how get posts with product_cat taxonomy selected primary category of with terms-ids 18 & 21
$taxonomy = 'product_cat';
$args = array(
'post_type' => 'product',
'meta_query' => array(
array(
'key' => '_primary_category_' . $taxonomy,
'value' => array( 18,21 ), // terms id
'compare' => 'IN',
)
),
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
the_title();
}
}
https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters
In order to make this plugin compatible with gutenberg, there was an issue with post-edit/post-new panels. I was unable to find a class to target the panels and display ‘set as primary’ button ahead terms. The reason was all panels were having the same class and gutenberg still doesn’t provide any method to add custom class/id.