Skip to content

Instantly share code, notes, and snippets.

@nicholasohrn
Created March 4, 2014 18:17
Show Gist options
  • Save nicholasohrn/9352332 to your computer and use it in GitHub Desktop.
Save nicholasohrn/9352332 to your computer and use it in GitHub Desktop.
Automatically title a post based on its type and category
<?php
/*
Plugin Name: Automatically Title Post
Description: Automatically title post based on post type and taxonomy.
Version: 1.0.0.RC.1
Author: Nick Ohrn of Plugin-Developer.com
Author URI: http://plugin-developer.com/
*/
function automatically_title_post($post_id, $post, $update) {
$desired_taxonomy = 'category';
$desired_type = 'post';
if($desired_type === $post->post_type) {
$post_type_object = get_post_type_object($post->post_type);
$terms = wp_get_object_terms($post_id, array($desired_taxonomy));
$post_title_parts = array();
$post_title_parts[] = $post_type_object->labels->singular_name;
$post_title_parts[] = empty($terms) ? '' : array_shift($terms)->name;
$post_title = implode(' - ', array_filter(array_map('trim', $post_title_parts)));
$post_name = sanitize_title($post_title, $post_id);
global $wpdb;
$wpdb->update($wpdb->posts, array('post_name' => $post_name, 'post_title' => $post_title), array('ID' => $post_id));
}
}
add_action('wp_insert_post', 'automatically_title_post', 11, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment