• Hi,

    what I need is a way (button, dropdown list) for the admin to exclude posts with categories set from the posts admin view. The purpose of this is the admin needs to add categories to all new posts which don’t have them.

    Anyone? Any ideas?

    Thanks!

Viewing 4 replies - 1 through 4 (of 4 total)
  • Are these traditional Categories ( built-in Posts ) or a Custom Taxonomy? By default, Posts get set to Uncategorized whenever a category is not set but this is not the case with a Custom Taxonomy.

    Thread Starter waaaaat

    (@waaaaat)

    They are custom posts, so no Uncategorized.

    If I had the Uncategorized auto set on new posts, the user would have to un-set it manually, right? Or not?

    Here’s a little function you may add which will add a default term if the user hasn’t set terms when publishing the post:

    /** Add Default Terms to Taxonomy **/
    function set_default_object_terms( $post_id, $post ) {
    
    	// Only run this if the user is publishing their post
    	if ( 'publish' === $post->post_status ) {
    
    		// An array of taxonomies and their default terms, you can add as many taxonomies as you like.
    		$defaults = array(
    			'TAXONOMY_SLUG_HERE' => array( 'DEFAULT_CATEGORY_SLUG_HERE' ),
    		);
    
    		// Get all taxonomies of the post type
    		$taxonomies = get_object_taxonomies( $post->post_type );
    
    		// Loop through each taxonomy
    		foreach ( (array) $taxonomies as $taxonomy ) {
    
    			// Get all the post terms
    			$terms = wp_get_post_terms( $post_id, $taxonomy );
    
    			// IF there are no terms and our taxonomy exists for this post type, set a default term(s)
    			if ( empty( $terms ) && array_key_exists( $taxonomy, $defaults ) ) {
    				wp_set_object_terms( $post_id, $defaults[$taxonomy], $taxonomy );
    			}
    		}
    	}
    }
    add_action( 'save_post', 'set_default_object_terms', 100, 2 );

    So, if the user publishes a post without any terms assigned, it will assign one. This will ensure that every post has a category set. Let me know if you have any questions on it.

    Thread Starter waaaaat

    (@waaaaat)

    Thanks for this, actually in the meantime I’ve just added post_category to my wp_insert_post().

    $post = array(
    	'post_status'	=> 'pending',
    	'post_type'		=> 'my_post_type',
      'post_category' => array( 1 ),
    );
Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Excluding categories from admin’ is closed to new replies.