I have a site with a few custom post types, each with their own custom data, meta boxes & assets (stylesheets, images, JavaScript).

Typically I'd hook onto add_meta_boxes to register all my meta boxes and save_post to handle the data, but in this case I'd like to wrap all the functionality for each post type in a class & abstract out the process of instantiation.

My proposal is as follows;

function my_prefix_admin_load_post()
    /* Grab current post type - can't use global $post_type since it isn't set yet! */
    if ( isset( $_GET['post'] ) )
        $post_type = get_post_type( $_GET['post'] );
    elseif ( isset( $_REQUEST['post_type'] ) )
        $post_type = basename( $_REQUEST['post_type'] );
        $post_type = 'post';

    /* Construct classname & filename from post type. */
    $post_type_file = dirname( __FILE__ ) . "/inc/class-post-$post_type.php";
    $post_type_class = 'Class_Prefix_' . ucfirst( $post_type );

    if ( is_file( $post_type_file ) )
        require $post_type_file;

    if ( class_exists( $post_type_class ) )
        new $post_type_class;
add_action( 'load-post.php', 'my_prefix_admin_load_post' );
add_action( 'lost-post-new.php', 'my_prefix_admin_load_post' );

This way, I can drop in enhancements for a new or existing post type at anytime (without tinkering with my base functions), and without code for different post types intermingling with another.

However, I can't help but feel the loading process is just a little... icky. I'd really love to hear of suggestions, whether improvements or alternate approaches!


Not really a complete answer, but since this question's become a ghost town I thought it was worth adding.

$post_type = get_current_screen()->id; // when on post.php or post-new.php

It's been around for a while, but with 3.3's much improved screen API I can see this opening a new world of easier, on-demand loading.

  • Will un-accept this answer if the discussion ever gets re-booted. Jan 16 '12 at 11:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.