WordPress add custom column

I need to add a column to the WordPress posts table. The column will contain numeric values so that I can make very simple queries with rows ordered by that field. By now the values are saved as post meta but I need to have them in the post table so that I can order the posts by that field.

I know that I could just call the query on the post_meta table and order the rows by the value, then get the post through the post_ID. However, this way anytime I do a search, the posts with the same value wouldn’t be ordered alphabetically but only by post_meta_ID.

Read More

So my question is: if I add a column to the wp_posts table, will it be removed/edited on the next WordPress update? There’s a way to make it permanent or to update it with WordPress?

Related posts

1 comment

  1. No, your custom column will remain the same even when you update the core. Updates will only affect default tables and columns, not custom ones.

    To add your custom column you could use the below code, which only adds it if it’s not already present.

    $myPosts = $wpdb->get_row("SELECT * FROM wp_posts");
    //Add column if not present.
    if(!isset($myPosts->my_custom_posts_column)){
        $wpdb->query("ALTER TABLE wp_posts ADD my_custom_posts_column INT(1)");
    }
    

    (Source)

Comments are closed.