• Resolved Stef

    (@stef78)


    I have a lot of posts filled under catetory A and category B.
    I’m trying to get all these posts only filled under category A.
    Is there some kind of hack for that? To auto-remove category B from all these posts?
    Thank you.

Viewing 3 replies - 1 through 3 (of 3 total)
  • You could run a couple of custom queries to do it.

    Something like..

    Grab the posts that have both those categories first. (MySQL query for use in PhpMyAdmin or similar, can convert to a query that will run in your theme or plugin if you prefer).

    SELECT ID from wp_posts p
     JOIN wp_term_relationships tr1 ON tr1.object_id = p.ID
     JOIN wp_term_taxonomy t1 ON t1.term_taxonomy_id = tr1.term_taxonomy_id
     JOIN wp_term_relationships tr2 ON tr2.object_id = p.ID
     JOIN wp_term_taxonomy t2 ON t2.term_taxonomy_id = tr2.term_taxonomy_id
    WHERE
     t1.term_id = 3
    AND
     t2.term_id = 4
    AND
     p.post_type = 'post'
    AND
     p.post_status = 'publish'

    3 and 4 are example category IDs.

    Confirm the IDs in the result match the correct posts(check 3 or 4 of the IDs, just to make sure you’re getting accurate data back, should be fine, it worked correctly in my very limited testing).

    If they do, take a copy of the IDs.

    Run another query to remove the necessary relationships from the DB, using the IDs procured earlier.

    DELETE tr.* FROM wp_term_relationships tr
    JOIN wp_term_taxonomy tt ON tt.term_taxonomy_id = tr.term_taxonomy_id
    WHERE tt.term_id = 4 AND tr.object_id IN( 300,301,302 )

    In the above 4 is the ID of the category we’re removing from posts.
    300,301,302 is a comma seperated list of post IDs (the IDs obtained earlier should go here though – comma seperated).

    I can convert the above into $wpdb queries if you want to run it from one of your WordPress pages, else PhpMyAdmin or similar should do.

    NOTE: I assumed a default db table prefix in the above examples. I also gave example IDs, so be sure to update them. And of course… BACKUP your data first before attempting to run any of the queries (if something gets messed up you’ll need to know how to restore the database, and have a backup ready).

    Additional note: It might actually be smart to make a copy of your existing database, give the new copied database any name you like (it’s a copy it won’t matter), then run the queries on the copy (that way, if any damage done, it’s not on your live database).

    If you go to your posts screen (wp-admin/edit.php) you can specify which categories to show: https://img.skitch.com/20100714-1x6yiqfygyiwamx2fb7yr4w7gb.jpg

    You can then bulk edit them all and change the category to category A.

    If that makes sense ??

    If we’re talking about a handful of posts, then certainly yes, bulk edit would be easier and safer.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Auto-remove category from posts.’ is closed to new replies.