Fork me on GitHub

Synchronizing Models With Posts

To be able to use all of WordPress's native post-related functionality with an MVC model, you can tell WP MVC to create a post for every object of a given model, and WP MVC will automatically update that post if the object is updated.

This allows you to more easily add model objects to Navigation Menus (by adding the object's associated post to the menu; it will link to the object), set up commenting for that object (by setting up commenting on the object's associated post), etc.

There are three ways to configure this:

View alone

No Associated Custom Post Type

Setting $wp_post = true; will automatically create and update a post for each venue; the posts will have a post_type value of 'mvc_venue', but there won't be a Custom Post Type for venues.

<?php
class Venue extends MvcModel {

  var $wp_post = true;

}
?>

The post of each venue can then be accessed using $venue->post, and this will have all of the columns of wp_posts as attributes (e.g. $venue->post->post_title returns the post's title).

View alone

Default Custom Post Type

Setting $wp_post = array('post_type' => true); behaves the same as above, but now a Custom Post Type will be created. By default, this post type is kept fairly private (e.g. it doesn't show up in Navigation Menus), but this can be changed by customizing it (see the next section).

<?php
class Venue extends MvcModel {

  var $wp_post = array('post_type' => true);

}
?>
View alone

Customized Custom Post Type

Setting 'post_type' to an array lets you customize the custom type and how it behaves. Accepted properties are:

  • 'args' - Same as the $args settings in register_post_type
  • 'fields' - How the fields of the post should be set whenever the object is updated (see below)

Types of values for 'fields'

  • 'generate_post_title()' would use the value returned by generate_post_title($object) in the model
  • '$description' would use the value of $object->description (i.e. the description column in the table)
  • 'draft' would always use the string 'draft'
<?php
class Venue extends MvcModel {

  var $wp_post = array(
    'post_type' => array(
      'args' => array(
        'show_in_menu' => true,
        'supports' => array('title')
      ),
      'fields' => array(
        'post_title' => 'generate_post_title()',
        'post_content' => '$description',
        'post_status' => 'draft'
      )
    )
  );
  
  function generate_post_title($object) {
    return 'The '.$object->name;
  }

}
?>