How To Modify Show UI of a Registered Taxonomy On Demand - wordpress

As you you know the 'show_ui' Boolean option in taking care of rendering or not rending the Taxonomy Menu on UI on registering ataxonomy.
function custom_taxonomy() {
$labels = array(
'name' => 'Taxonomies',
'singular_name' => 'Taxonomy',
'menu_name' => 'Taxonomy',
'all_items' => 'All Items',
'parent_item' => 'Parent Item',
'parent_item_colon' => 'Parent Item:',
'new_item_name' => 'New Item Name',
'add_new_item' => 'Add New Item',
'edit_item' => 'Edit Item',
'update_item' => 'Update Item',
'view_item' => 'View Item',
'separate_items_with_commas' => 'Separate items with commas',
'add_or_remove_items' => 'Add or remove items',
'choose_from_most_used' => 'Choose from the most used',
'popular_items' => 'Popular Items',
'search_items' => 'Search Items',
'not_found' => 'Not Found',
'no_terms' => 'No items',
'items_list' => 'Items list',
'items_list_navigation' => 'Items list navigation',
);
$args = array(
'labels' => $labels,
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
);
register_taxonomy( 'taxonomy', array( 'post' ), $args );
}
add_action( 'init', 'custom_taxonomy', 0 );
Is there any way to modify this option after registering the taxonomy? like any hook or filter to toggle the Boolean in functions.php

You can use register_taxonomy_args to filter the taxonomy options before the taxonomy is registered, or while it's being registered.
Example code:
/*
* #param array $args The taxonomy args such as show_ui.
* #param string $taxonomy The taxonomy name.
*/
add_filter( 'register_taxonomy_args', function ( $args, $taxonomy ) {
if ( 'my_taxonomy' === $taxonomy ) {
$args['show_ui'] = false;
}
return $args;
}, 10, 2 );
There is also an "action" you can "hook" into, where this filter is fired just after a taxonomy is registered. Here, you can, for example, assign other post/object type(s) to the taxonomy.
Example code:
/*
* #param string $taxonomy The taxonomy name.
*/
add_action( 'registered_taxonomy', function ( $taxonomy ) {
if ( 'my_taxonomy' === $taxonomy ) {
register_taxonomy_for_object_type( $taxonomy, 'post' );
}
} );
And if you must (or need to) modify the show_ui (or any other options) of a taxonomy after it's registered, then you can use the global $wp_taxonomies, which is an array of all registered taxonomies.
Example code:
/*
* #param string $taxonomy The taxonomy name.
*/
add_action( 'registered_taxonomy', function ( $taxonomy ) {
if ( 'my_taxonomy' === $taxonomy ) {
global $wp_taxonomies;
if ( ! is_array( $wp_taxonomies )
|| ! isset( $wp_taxonomies[ $taxonomy ] ) ) {
return;
}
$wp_taxonomies[ $taxonomy ]->show_ui = false;
}
} );

Related

In Wordpress display custom post type single page display previous and next links for custom category

I have created a custom post type that has the ability to have custom taxonomies.
On the Single of the custom post type, I would like to be able to include "previous post" and "next post" buttons which display only if there are previous and next posts.
Set up for the custom post type in functions.php:
function the_custom_post_types() {
$types = array(
// Gallery
array(
'the_type' => 'gallery', // becomes the archive url and used in archive template name (archive-{the_type}.php)
'single' => 'single',
'plural' => 'plural',
'display' => 'Gallery',
'icon' => 'dashicons-art',
'show_in_rest' => false,
'supports' => array( 'title', 'editor', 'custom-fields', 'post_tag', 'collection', 'thumbnail' ),
'taxonomies' => array( 'collection' ),
),
// ... other CPTs ...
);
foreach ($types as $type) {
$the_type = $type['the_type'];
$single = $type['single'];
$plural = $type['plural'];
$display = $type['display'];
$icon = $type['icon'];
$gutenburg = $type['show_in_rest'];
$supports = $type['supports'];
$taxonomies = $type['taxonomies'];
$labels = array(
'name' => _x($display, 'post type general name'),
'singular_name' => _x($single, 'post type singular name'),
'add_new' => _x('Add New', $single),
'add_new_item' => __('Add New '. $single),
'edit_item' => __('Edit '.$single),
'new_item' => __('New '.$single),
'view_item' => __('View all '.$single),
'search_items' => __('Search all'.$plural),
'not_found'. => __('No '.$plural.' found'),
'not_found_in_trash' => __('No '.$plural.' found in Trash'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'rewrite' => true,
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => true,
'show_in_rest' => $gutenburg,
'menu_position' => 21,
'supports' => $supports,
'menu_icon' => $icon,
'taxonomies' => $taxonomies
);
register_post_type($the_type, $args);
flush_rewrite_rules();
}
}
add_action('init', 'the_custom_post_types');
And the taxonomy is created in a similar fashion like so:
function scaffolding_custom_taxonomies() {
$types = array(
array(
'the_type' => 'collection',
'single' => 'Collection',
'plural' => 'Collections',
'display' => 'Collections',
'post_types' => array( 'gallery' )
)
);
foreach ($types as $type) {
$the_type = $type['the_type'];
$single = $type['single'];
$plural = $type['plural'];
$display = $type['display'];
$post_types = $type['post_types'];
$labels = array(
'name' => _x( $display, 'taxonomy general name' ),
'singular_name' => _x( $single, 'taxonomy singular name' ),
'search_items' => __( 'Search ' . $plural ),
'all_items' => __( 'All ' . $plural ),
'parent_item' => __( 'Parent ' . $single ),
'parent_item_colon' => __( 'Parent ' . $single . ':' ),
'edit_item' => __( 'Edit ' . $single ),
'update_item' => __( 'Update ' . $single ),
'add_new_item' => __( 'Add New ' . $single ),
'new_item_name' => __( 'New ' . $single . ' Name' ),
'menu_name' => __( $plural ),
);
$rewrite = array(
'slug' => $the_type
);
$args = array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => $rewrite
);
register_taxonomy( $the_type, $post_types, $args);
flush_rewrite_rules();
}
}
add_action( 'init', 'scaffolding_custom_taxonomies', 0 );
Currently, I have used the code below for the single page.
<nav class="artwork__pagination">
<div class="artwork__prev"><?php previous_post_link( '%link', 'previous' ); ?></div>
<div class="artwork__next"><?php next_post_link( '%link', 'next' ); ?></div>
</nav>
This cycles through all the posts in the CPT rather than just those in the current category.
If I include 'true' to the array like so:
<nav class="artwork__pagination">
<div class="artwork__prev"><?php previous_post_link( '%link', 'previous', true ); ?></div>
<div class="artwork__next"><?php next_post_link( '%link', 'next', true ); ?></div>
</nav>
It returns nothing.
How can I get the links to display and limit them to only those within the same custom category?
The next and prev post link function includes a param for taxonomy, where the default is category. Since your taxonomy is named collection this should work.
/*
* The parameters for next/previous post as defined in the function.
* #param string $format Optional. Link anchor format. Default '« %link'.
* #param string $link Optional. Link permalink format. Default '%title'.
* #param bool $in_same_term Optional. Whether link should be in a same taxonomy term. Default false.
* #param int[]|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs. Default empty.
* #param string $taxonomy Optional. Taxonomy, if $in_same_term is true. Default 'category'.
*/
?>
<nav class="artwork__pagination">
<div class="artwork__prev"><?php previous_post_link( '%link', 'previous', true, '', 'collection' ); ?></div>
<div class="artwork__next"><?php next_post_link( '%link', 'next', true, '', 'collection' ); ?></div>
</nav>

Add custom taxonomy term in woocommerce REST API

I have created custom taxonomy "Brands" and attached to woocommerce products. Unfortunately, It is not available in woocommerce REST API response.
How to attach custom taxonomy term to woocommerce rest API. Currently there is no documentation about attachment of custom taxonomy. Is there any hook or filter ?
I solved by using this code.You will be able to GET and Update custom taxonomy by using this method. Basically. You can add this code in functions.php file or in plugin.
Step:1
Replace brands with your taxonomy_name.
Step:2
If your taxonomy have custom fields, replace custom_field_name with yours.
Taxonomy Code:
add_action( 'init', 'create_brands_hierarchical_taxonomy', 0 );
//create a custom taxonomy name it topics for your posts
function create_brands_hierarchical_taxonomy() {
// Add new taxonomy, make it hierarchical like categories
//first do the translations part for GUI
$labels = array(
'name' => _x( 'Brands', 'taxonomy general name' ),
'singular_name' => _x( 'Brand', 'taxonomy singular name' ),
'search_items' => __( 'Search Brands' ),
'all_items' => __( 'All Brands' ),
'parent_item' => __( 'Parent Brand' ),
'parent_item_colon' => __( 'Parent Brand:' ),
'edit_item' => __( 'Edit Brand' ),
'update_item' => __( 'Update Brand' ),
'add_new_item' => __( 'Add New Brand' ),
'new_item_name' => __( 'New Brand Name' ),
'menu_name' => __( 'Brands' ),
);
$capabilities = array(
'manage_terms' => 'manage_woocommerce',
'edit_terms' => 'manage_woocommerce',
'delete_terms' => 'manage_woocommerce',
'assign_terms' => 'manage_woocommerce',
);
// Now register the taxonomy
$args = array(
'labels' => $labels,
'show_in_rest' => true,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => false,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
'capabilities' => $capabilities,
);
register_taxonomy( 'brands', array( 'product' ), $args );
register_taxonomy_for_object_type( 'brands', 'product' );
}
Register Taxonomy API for WC
//Register taxonomy API for WC
add_action( 'rest_api_init', 'register_rest_field_for_custom_taxonomy_brands' );
function register_rest_field_for_custom_taxonomy_brands() {
register_rest_field('product', "brands", array(
'get_callback' => 'product_get_callback',
'update_callback' => 'product_update_callback',
'schema' => null,
));
}
//Get Taxonomy record in wc REST API
function product_get_callback($post, $attr, $request, $object_type)
{
$terms = array();
// Get terms
foreach (wp_get_post_terms( $post[ 'id' ],'brands') as $term) {
$terms[] = array(
'id' => $term->term_id,
'name' => $term->name,
'slug' => $term->slug,
'custom_field_name' => get_term_meta($term->term_id, 'custom_field_name', true)
);
}
return $terms;
}
//Update Taxonomy record in wc REST API
function product_update_callback($values, $post, $attr, $request, $object_type)
{
// Post ID
$postId = $post->get_id();
//Example: $values = [2,4,3];
// Set terms
wp_set_object_terms( $postId, $values , 'brands');
}
Solution above is working but you have to change the
$postId = $post->get_id();
with
$postId = $post->ID;
Took me ages to find out why update_callback did not work : $values contains the taxonomy-structure and is therefore too complex to pass as integer to wp_set_object_terms. You have to strip it to the numeric ID's only otherwise [null] is assigned
//Update Taxonomy record in wc REST API
function product_update_callback_Leerjaar($values, $post, $attr, $request, $object_type)
{
// Post ID
$postId = $post->id;
//Example: $values = [2,4,3];
error_log("debug on values");
error_log(json_encode($values));
$numarray = [];
foreach($values as $value){
$numarray[] = (int)$value['id'];
}
wp_set_object_terms( $postId, $numarray , 'brands');
}
If anyone has tested all the above and can't get it to work, I found a simplest and working solution, based on Taha Farooqui's answer and the wordpress register_rest_field documentation :
add_action( 'rest_api_init', 'register_rest_field_for_custom_taxonomy_brands');
function register_rest_field_for_custom_taxonomy_brands() {
register_rest_field('product', "field_rest_name",
array("get_callback" => function ($post) {
$taxonomy = wp_get_post_terms( $post['id'], 'your_taxonomy_name');
return $taxonomy;
}
)
);
}
After months of testing trying to prove why the product_update_callback() function returned a null value, he got a version that loads the taxonomy values ​​from the woocommerce Rest Api v3 only with the name and slug..
<?php
//Prevent a malicious user from executing php code from the browser bar
defined('ABSPATH') or die( "Bye bye" );
add_action( 'init', 'create_brands_hierarchical_taxonomy', 0 );
//create a custom taxonomy name it topics for your posts
function create_brands_hierarchical_taxonomy() {
// Add new taxonomy, make it hierarchical like categories
$labels = array(
'name' => _x( 'Marcas', 'taxonomy general name' ),
'singular_name' => _x( 'Marca', 'taxonomy singular name' ),
'search_items' => __( 'Buscar Marcas' ),
'all_items' => __( 'Todas las Marcas' ),
'parent_item' => __( 'Marca Relacionada' ),
'parent_item_colon' => __( 'Marca Relacionada:' ),
'edit_item' => __( 'Editar Marca' ),
'update_item' => __( 'Subir Marca' ),
'add_new_item' => __( 'Añadir Nueva Marca' ),
'new_item_name' => __( 'Nuevo Nombre de Marca' ),
'menu_name' => __( 'Marcas' ),
);
$capabilities = array(
'manage_terms' => 'manage_woocommerce',
'edit_terms' => 'manage_woocommerce',
'delete_terms' => 'manage_woocommerce',
'assign_terms' => 'manage_woocommerce',
);
// Now register the taxonomy
$args = array(
'labels' => $labels,
'show_in_rest' => true,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => false,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
'capabilities' => $capabilities,
);
register_taxonomy( 'pwb-brand', array( 'product' ), $args );
register_taxonomy_for_object_type( 'pwb-brand', 'product' );
}
//Register taxonomy API for WC
add_action( 'rest_api_init', 'register_rest_field_for_custom_taxonomy_brands' );
function register_rest_field_for_custom_taxonomy_brands() {
register_rest_field('product', "pwb-brand", array(
'get_callback' => 'product_get_callback_brand',
'update_callback' => 'product_update_callback_brand',
'schema' => null,
));
}
//Get Taxonomy record in wc REST API
function product_get_callback_brand($post, $attr, $request, $object_type){
$terms = array();
// Get terms
foreach (wp_get_post_terms( $post[ 'id' ],'pwb-brand') as $term) {
$terms[] = array(
'id' => $term->term_id,
'name' => $term->name,
'slug' => $term->slug,
);
}
return $terms;
}
//Update Taxonomy record in wc REST API
function product_update_callback_brand($values, $post, $attr, $request, $object_type){
// Post ID
$postId = $post->id;
$terms = $values;
$termName = $terms[0]['name'];
$termSlug = $terms[0]['slug'];
wp_insert_term( $termName, 'pwb-brand', array( 'slug' => $termSlug ) );
error_log("debug on values");
error_log(json_encode($values));
$newTermId = get_term_by('slug',$termSlug,'pwb-brand')->term_id;
array_push($values, array('id' => (int)$newTermId));
$numarray = [];
foreach($values as $value){
if(is_numeric($value['id'])){
$numarray[] = (int)$value['id'];
}
}
wp_set_object_terms( $postId, $numarray , 'pwb-brand');
}
After so much testing he understood that the values ​​that pass through the product_get_callback_brand function are mandatory to register a taxonomy so if you add a custom field like in the first example then they must be loaded so that the taxonomy can be retrieved.
It is worth noting that it is not a valid field for image fields or galleries that will not have the permissions to be loaded by the Rest Api v3 of woocommerce

WordPress: Remove "Parent" dropdown from category form

Hi I've downloaded a plugin "Simple Staff List" and it does what I need but I don't want editors to create a sub-category. How can I remove/hide the "Parent" selectbox on the form?
Add bellow code in your current theme function.php file.
add_action( 'admin_head-edit-tags.php', 'wpse_58799_remove_parent_category' );
function wpse_58799_remove_parent_category()
{
if ( 'category' != $_GET['taxonomy'] )
return;
$parent = 'parent()';
if ( isset( $_GET['action'] ) )
$parent = 'parent().parent()';
?>
<script type="text/javascript">
jQuery(document).ready(function($)
{
$('label[for=parent]').<?php echo $parent; ?>.remove();
});
</script>
<?php
}
You can use set these options in
register_taxonomy() func
'hierarchical' => false,
'parent_item' => null,
'parent_item_colon' => null,
This would remove the parent field.
This will remove the parent dropdown from both the taxonomy and post new/edit screens.
<?php
function remove_tax_parent_dropdown() {
$screen = get_current_screen();
if ( 'category' == $screen->taxonomy ) {
if ( 'edit-tags' == $screen->base ) {
$parent = "$('label[for=parent]').parent()";
} elseif ( 'term' == $screen->base ) {
$parent = "$('label[for=parent]').parent().parent()";
}
} elseif ( 'post' == $screen->post_type ) {
$parent = "$('#newcategory_parent')";
} else {
return;
}
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
<?php echo $parent; ?>.remove();
});
</script>
<?php
}
add_action( 'admin_head-edit-tags.php', 'remove_tax_parent_dropdown' );
add_action( 'admin_head-term.php', 'remove_tax_parent_dropdown' );
add_action( 'admin_head-post.php', 'remove_tax_parent_dropdown' );
add_action( 'admin_head-post-new.php', 'remove_tax_parent_dropdown' );
If you want to disable "hierarchical" itself from category taxonomy, add this code in your function.php.
add_action('init', function(){
global $wp_taxonomies;
$wp_taxonomies['category']->hierarchical = false;
});
Add bellow code in your current theme function.php file.
function custom_taxonomy() {
$labels = array(
'name' => _x( 'Brands', 'Taxonomy General Name', 'text_domain' ),
'singular_name' => _x( 'Brand', 'Taxonomy Singular Name', 'text_domain' ),
'menu_name' => __( 'Taxonomy', 'text_domain' ),
'all_items' => __( 'All Items', 'text_domain' ),
'parent_item' => __( 'Parent Item', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'new_item_name' => __( 'New Item Name', 'text_domain' ),
'add_new_item' => __( 'Add New Item', 'text_domain' ),
'edit_item' => __( 'Edit Item', 'text_domain' ),
'update_item' => __( 'Update Item', 'text_domain' ),
'view_item' => __( 'View Item', 'text_domain' ),
'separate_items_with_commas' => __( 'Separate items with commas', 'text_domain' ),
'add_or_remove_items' => __( 'Add or remove items', 'text_domain' ),
'choose_from_most_used' => __( 'Choose from the most used', 'text_domain' ),
'popular_items' => __( 'Popular Items', 'text_domain' ),
'search_items' => __( 'Search Items', 'text_domain' ),
'not_found' => __( 'Not Found', 'text_domain' ),
'no_terms' => __( 'No items', 'text_domain' ),
'items_list' => __( 'Items list', 'text_domain' ),
'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
'parent_item' => null,
'parent_item_colon' => null,
);
register_taxonomy( 'brands', array( 'product' ), $args );
}
add_action( 'init', 'custom_taxonomy', 0 );
Reference: https://codex.wordpress.org/Function_Reference/register_taxonomy
This will work with WordPress 5.4.2. For me all other solutions show the fields as long as jQuery removes them. My quick and dirty solution hides via CSS and remove them with jQuery. Unfortunately only hiding (not removing) seems to work with Gutenberg Editor. Maybe someone else has another solution.
function remove_tax_parent_dropdown() {
$screen = get_current_screen();
if ( 'category' == $screen->taxonomy ) {
if ( 'edit-tags' == $screen->base ) {
$parent = "$('label[for=parent]').parent().remove(); ";
$css = ".term-parent-wrap{display:none;}";
} elseif ( 'term' == $screen->base ) {
$parent = "$('label[for=parent]').parent().parent().remove(); ";
$css = ".term-parent-wrap{display:none;}";
}
} elseif ( 'post' == $screen->post_type ) {
$parent = "$('#newcategory_parent').remove();";
$css = "div.components-base-control:nth-child(3){display:none;}";
} else {
return;
}
if(!empty($css)) {
echo '<style type="text/css">';
echo $css;
echo '</style>';
}
if(!empty($parent)) {
echo '<script type="text/javascript">';
echo 'jQuery(document).ready(function($) {';
echo $parent;
echo '});';
echo '</script>';
}
}
add_action( 'admin_head-edit-tags.php', 'remove_tax_parent_dropdown' );
add_action( 'admin_head-term.php', 'remove_tax_parent_dropdown' );
add_action( 'admin_head-post.php', 'remove_tax_parent_dropdown' );
add_action( 'admin_head-post-new.php', 'remove_tax_parent_dropdown' );
Ah by the way - DON'T use the following code because you get bad issues with it. When you are saving a post without changing category, all categories of this post will be deleted and the category IDs will be created as new categories and added to your post.
global $wp_taxonomies;
$wp_taxonomies['category']->hierarchical = false;

Wordpress: pre_get_posts and order by taxonomy term

I have a category archive with a custom taxonomy "client". Now I want to order the category archive by the term of the custom taxonomy (the client name). I tried to query it by meta_value and a advanced custom taxonomy query, but I could not get it to be ordered by the name of the taxonomy term. Any suggestions to get a Wordpress loop ordered by taxonomy term name? See line $query->set( 'orderby', 'how_to_order_by_taxonomy_name' );
Registering the taxonomy
add_action( 'init', 'jp_register_project_taxonomies', 0 );
function jp_register_project_taxonomies() {
// register taxonomy to hold our clients
register_taxonomy(
'client',
array( 'post' ),
array(
'hierarchical' => false,
'public' => true,
'query_var' => true,
'rewrite' => true,
'labels' => array(
'name' => _x( 'Clients', 'taxonomy general name' ),
'singular_name' => _x( 'Client', 'taxonomy singular name' ),
'search_items' => __( 'Search Clients' ),
'all_items' => __( 'All Clients' ),
'edit_item' => __( 'Edit Client' ),
'update_item' => __( 'Update Client' ),
'add_new_item' => __( 'Add New Client' ),
'new_item_name' => __( 'New Client Name' ),
'menu_name' => __( 'Client' )
),
)
);
}
pre_get_posts Query
add_action( 'pre_get_posts', 'jp_project_taxonomy_queries' );
function jp_project_taxonomy_queries( $query ) {
if(!is_admin() && $query->is_main_query() && is_category() ):
if (get_query_var('poby') == 'client'):
$taxonomies = array();
$tax_order = (get_query_var('po') == 'DESC' ? 'DESC' : 'ASC' );
foreach (get_terms('client', array('order' => $tax_order)) as $tax ) {
$taxonomies[] = $tax->name;
}
$taxquery = array(
array(
'taxonomy' => 'client',
'terms' => $taxonomies,
'field' => 'slug',
)
);
$query->set( 'tax_query', $taxquery );
$query->set( 'orderby', 'how_to_order_by_taxonomy_name' );
endif;
endif;
}
As far as I know, there is no parameter to order a WP_Query by term.
My solution to this problem usually is to create a meta field that contains the term name or the term slug. This field is created when the post is saved using the hook save_post or save_post_{post_type}.
For instance, to order a list of books (post type book) by year of publication (taxonomy date) we can use this function to create the meta field:
add_action( 'save_post_book', 'prefix_save_date_as_meta', 10 );
function prefix_save_date_as_meta ($post_id) {
$years = get_the_terms($post_id,'date');
if( empty($years) )
return;
$years_list = wp_list_pluck($years,'name');
update_post_meta($post_id,'_book_date',$years_list[0]);
return;
}
And this other function to order the query:
add_filter( 'pre_get_posts', 'prefix_custom_args_for_loops' );
function prefix_custom_args_for_loops( $query ) {
if ( !is_admin() && is_post_type_archive('book') && $query->is_main_query() ) {
$query->set( 'orderby','meta_value_num');
$query->set( 'meta_key','_book_date');
}
return $query;
}

Trying to get both custom post type and posts to show up in tag and category pages

I've built a custom post type, that is set to use the out-of-the-box tags and categories that posts use. However, if I click on a tag or category link, the archive only shows posts with that tag, not my custom post type. I've tried a few ways to fix it but they don't seem to be working. My code is:
// Add Resource Post Type
add_action('init', 'hallam_init');
function hallam_init() {
// set up the labels
$labels = array(
'name' => _x('Resources', 'post type general name'),
'singular_name' => _x('Resource', 'post type singular name'),
'add_new' => _x('Add New', 'resource'),
'add_new_item' => __( 'Add New Resource' ),
'edit_item' => __( 'Edit Resource' ),
'new_item' => __( 'New Resource' ),
'view_item' => __( 'View Resource' ),
'search_items' => __( 'Search Resources' ),
'not_found' => __( 'No resources found' ),
'not_found_in_trash' => __( 'No respources found in Trash' ),
'parent_item_colon' => ''
);
// set up the args
$args = array (
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'rewrite' => array (
'slug' => 'resources'
),
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => 5,
'supports' => array(
'title',
'editor',
'author',
'thumbnail',
'excerpt',
'comments'
),
'taxonomies' => array(
'collection',
'category',
'post_tag'
),
'has_archive' => true
);
register_post_type('ht_resource', $args);
}
// Add Taxonomy
register_taxonomy('collection', 'ht_resource', array(
'hierarchical' => true,
'label' => 'Collections',
'query_var' => true,
'rewrite' => true
));
// Fix the archives
add_filter( 'pre_get_posts', 'add_to_query' );
function add_to_query( $query ) {
// if ( is_home() ) {
if( $query->query_vars['suppress_filters'] ) // TODO check if necessary
return $query;
$supported = $query->get( 'post_type' );
if ( !$supported || $supported == 'post' )
$supported = array( 'post', 'ht_resource' );
elseif ( is_array( $supported ) )
array_push( $supported, 'ht_resource' );
$query->set( 'post_type', $supported );
return $query;
//}
}
Am I missing something obvious?
Can you plz try this by adding on your theme's functions.php? Hope it will work
function query_post_type($query) {
if(is_tag()) {
$query->set('post_type',$post_types=get_post_types('','names'));
return $query;
}
}
add_filter('pre_get_posts', 'query_post_type');
thnx

Resources