0

I am creating a Blog in wordpress.

I have a list of categories: Technology, Art, fashion, Home, Lifetime, Education, Business, Religion, Design and home, Marketing

In which some of these categories I am using only in Custom Post Type (Technology, Art, Fashion) and others only in Normal Posts (Home, Life, Education, Business, Religion, Design and home, Marketing).

When I created the custom pos type, I used the CPT UI plugin.

Now I need to get the list of categories that are only being used from normal posts to show them on my blog (). I tried to do the following but it returns all categories including CPTs:

$categories = get_categories();
  foreach($categories as $category) {
    echo '<li class="cat-name"  . '>' . $category->name . '</li>';
}

I just need to show the categories: Home, Life, Education, Business, Religion, Design & Home, Marketing.

And exclude those that are being used in CPT. Please Help!

1
  • 2
    you should use a custom taxonomy for the CPT, what you're asking is going to be very slow and expensive if it's even possible, but importantly it's a problem you don't have to solve if you use a custom taxonomy for the CPT's
    – Tom J Nowell
    May 20, 2021 at 23:30

1 Answer 1

0

As pointed out by Tom, this could end up being an expensive query, though from my anecdotal evidence from trying this on a rather large database (granted, only a handful of post types), I think you could write a decently sufficient query.

If you're using caching to store the categories, that could also alleviate some of the potential performance issues.

Here's the query I used for testing (but with my own post types):

SELECT DISTINCT
    tt.taxonomy
FROM
    wp_term_taxonomy tt
JOIN
    wp_term_relationships tr ON( tr.term_taxonomy_id = tt.term_taxonomy_id )
WHERE
    tr.object_id IN ( SELECT ID FROM wp_posts WHERE post_type IN ( 'list', 'of', 'normal', 'post', 'types' ) );

Converting this to something more portable for WordPress:

<?php
global $wpdb;

$post_types   = [ 'list', 'of', 'normal', 'post', 'types' ];
$placeholders = array_fill( 0, count( $post_types ), '%s' );

$sql = <<<SQL
SELECT
    tt.taxonomy
FROM
    {$wpdb->term_taxonomy} tt
JOIN
    {$wpdb->term_relationships} tr ON( tr.term_taxonomy_id = tt.term_taxonomy_id )
WHERE
    tr.object_id IN ( SELECT ID FROM {$wpdb->posts} WHERE post_type IN ( {$placeholders} ) );
SQL;

$query   = $wpdb->prepare( $sql, $post_types );
$results = $wpdb->get_col( $query );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.