Need advice > converting category assignments to custom post meta values

Before I found out about the ability to add a meta box (with custom post meta selections) to the page and post editor, I was (and still am to a degree) using categories to define custom post meta.

For example, to make a post nofollow, or noindex, I created a category called nofollow and another called noindex and assigned one or both of those categories to a post or page.

Read More

Then in my header.php file, I’d do an in_category test in order to write the appropriate meta tags to the page.

Example:

<?php
if (in_category('noindex') && in_category('nofollow')){?>
<meta name="robots" content="noindex, nofollow">
<?php}?>

I also have custom categories for things like “Disable Adsense for this page”, “Don’t Show Image Attachments for this Page”, “Hide this page from menus”, etc…

So now that I’ve decided to move away from using categories where I should be using custom post meta, The above code in header.php instead becomes…

<?php 
    if (get_post_meta( $post->ID, '_noindex', true ) && get_post_meta( $post->ID, '_nofollow', true )){>?
    <meta name="robots" content="noindex, nofollow">
<?php } ?>

So that’s my plan, but now I have the problem of upgrading sites that use the old means of defining custom post options via the category assignments.

So I need a routing that goes about reassigning the category values to custom post meta values for each post and page in the site I’m upgrading.

I’m just looking for some quick advice on how to go about this and possibly some code hints on the neccessary routine.

Since this is a theme that can be updated, as part of the update process, I’d like to run a script one time, when the theme is first installed, (or the user clicks my upgrader utility) that runs through the options table and for every instance of one of my custom category assignments, it creates the requisite custom meta assignment for that post or page.

For example, if a post currently belongs to the “Hidden” category, it would be assigned to the “_hidden” post meta.

Hopefully I’ve explained this well enough. I appreciate any insights you can provide.

Perhaps its as simple as a series of custom SQL statements that run for each possible category assignment?

Related posts

Leave a Reply

1 comment

  1. Basic idea would be to loop through posts and their categories, assigning meta on matches.

    Something like this (be sure to check on test copy of data, etc, etc):

    $posts = get_posts( array(
        'numberposts' => -1
    ) );
    
    foreach( $posts as $post ) {
    
        $categories = get_the_category( $post->ID );
    
        foreach( $categories as $category ) {
    
            if( 'Hidden' ==  $category->name )
                add_post_meta( $post->ID, '_hidden', 'yes', true );
        }
    
    }
    

    Forgot to add deleting when done:

    $category = get_category_by_slug( 'hidden' );
    wp_delete_category( $category->term_id );