Attach Category to Custom Post type

Marko Krstić
13 Mar 2021

By the default if you create Custom Post Type attaching Category to it is not possible.

On the line: array( ‘post’, ‘resource_libraries’ ), replace “resource_libraries” slug to your custom post type slug.

Code Snippet

<?php 

function my_cptui_add_post_types_to_archives( $query ) {
	// We do not want unintended consequences.
	if ( is_admin() || ! $query->is_main_query() ) {
		return;    
	}

	if ( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
		$cptui_post_types = cptui_get_post_type_slugs();

		$query->set(
			'post_type',
			array_merge(
				array( 'post', 'resource_libraries' ),
				$cptui_post_types
			)
		);
	}
}
add_filter( 'pre_get_posts', 'my_cptui_add_post_types_to_archives' );

?>

Add Code Snippet

Open Scripts Organizer

Hit Add new.

screenshot 2021 04 15 at 21.25.39

Scripts Organizer Settings

Trigger Location: Everywhere
Script Location: PHP

screenshot 2021 04 15 at 21.29.12 1

Was this article helpful?

Tags

Categories

Never miss new post again

Subscribe and get list of new posts in your inbox

Click to Copy