Better wordpress custom post types using a base php class.

Creating multiple post types in wordpress can be tedious work. Use php classes to handle post type registration and better event handling for saving custom meta data. (Part 2 coming soon.)

  • deryk

    Thanks for the article. Do you use the classes for displaying custom post meta data. For example echo $customer->custom_field() ?

  • amado

    Hi. I don’t access the custom fields directly in the class, what I normally do is in the meta box functions (example: clientInfoBox) is:

    $metainfo = get_post_meta($post->ID, 'courseinfo', true);

    which gives me an array of the ‘courseinfo’ custom field.

    for saving the custom data, it’s a little more advanced, you have to add a hook within the register method for the post_save action:

    add_action('save_post', array($this, 'onSavePost'));

    then you have to add an onSavePost function to your class so that it saves the custom data for you.

    function onSavePost($post_id)
    if(empty($_POST) || $_POST['post_type'] != $this->posttype || wp_is_post_revision($post_id) !== false) return;

    update_post_meta($post_id, 'courseinfo', $_POST['courseinfo']);

    that way you could name your custom field inputs inside the metabox method something like:

    < input type="textbox" name="courseinfo[data1]" value="" / >

    which will display data gathered from get_post_meta.

  • amado

    If you meant accessing the custom field in the front end, then I do have a solution for that using a different class, but it’s a bit more intricate and involves hooking the sql for getting the custom values in one query. I think I should write a post about it one of these days.