+ $wp_post_statuses[$post_status] = $args;
+
+ return $args;
+}
+
+/**
+ * Retrieve a post status object by name
+ *
+ * @package WordPress
+ * @subpackage Post
+ * @since 3.0.0
+ * @uses $wp_post_statuses
+ * @see register_post_status
+ * @see get_post_statuses
+ *
+ * @param string $post_status The name of a registered post status
+ * @return object A post status object
+ */
+function get_post_status_object( $post_status ) {
+ global $wp_post_statuses;
+
+ if ( empty($wp_post_statuses[$post_status]) )
+ return null;
+
+ return $wp_post_statuses[$post_status];
+}
+
+/**
+ * Get a list of all registered post status objects.
+ *
+ * @package WordPress
+ * @subpackage Post
+ * @since 3.0.0
+ * @uses $wp_post_statuses
+ * @see register_post_status
+ * @see get_post_status_object
+ *
+ * @param array|string $args An array of key => value arguments to match against the post status objects.
+ * @param string $output The type of output to return, either post status 'names' or 'objects'. 'names' is the default.
+ * @param string $operator The logical operation to perform. 'or' means only one element
+ * from the array needs to match; 'and' means all elements must match. The default is 'and'.
+ * @return array A list of post status names or objects
+ */
+function get_post_stati( $args = array(), $output = 'names', $operator = 'and' ) {
+ global $wp_post_statuses;
+
+ $field = ('names' == $output) ? 'name' : false;
+
+ return wp_filter_object_list($wp_post_statuses, $args, $operator, $field);
+}
+
+/**
+ * Whether the post type is hierarchical.
+ *
+ * A false return value might also mean that the post type does not exist.
+ *
+ * @since 3.0.0
+ * @see get_post_type_object
+ *
+ * @param string $post_type Post type name
+ * @return bool Whether post type is hierarchical.
+ */
+function is_post_type_hierarchical( $post_type ) {
+ if ( ! post_type_exists( $post_type ) )
+ return false;
+
+ $post_type = get_post_type_object( $post_type );
+ return $post_type->hierarchical;
+}
+
+/**
+ * Checks if a post type is registered.
+ *
+ * @since 3.0.0
+ * @uses get_post_type_object()
+ *
+ * @param string $post_type Post type name
+ * @return bool Whether post type is registered.
+ */
+function post_type_exists( $post_type ) {
+ return (bool) get_post_type_object( $post_type );
+}
+
+/**
+ * Retrieve the post type of the current post or of a given post.
+ *
+ * @since 2.1.0
+ *
+ * @param int|object $post Optional. Post ID or post object. Default is the current post from the loop.
+ * @return string|bool Post type on success, false on failure.
+ */
+function get_post_type( $post = null ) {
+ if ( $post = get_post( $post ) )
+ return $post->post_type;
+
+ return false;
+}
+
+/**
+ * Retrieve a post type object by name
+ *
+ * @package WordPress
+ * @subpackage Post
+ * @since 3.0.0
+ * @uses $wp_post_types
+ * @see register_post_type
+ * @see get_post_types
+ *
+ * @param string $post_type The name of a registered post type
+ * @return object A post type object
+ */
+function get_post_type_object( $post_type ) {
+ global $wp_post_types;
+
+ if ( empty($wp_post_types[$post_type]) )
+ return null;
+
+ return $wp_post_types[$post_type];
+}
+
+/**
+ * Get a list of all registered post type objects.
+ *
+ * @package WordPress
+ * @subpackage Post
+ * @since 2.9.0
+ * @uses $wp_post_types
+ * @see register_post_type
+ *
+ * @param array|string $args An array of key => value arguments to match against the post type objects.
+ * @param string $output The type of output to return, either post type 'names' or 'objects'. 'names' is the default.
+ * @param string $operator The logical operation to perform. 'or' means only one element
+ * from the array needs to match; 'and' means all elements must match. The default is 'and'.
+ * @return array A list of post type names or objects
+ */
+function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) {
+ global $wp_post_types;
+
+ $field = ('names' == $output) ? 'name' : false;
+
+ return wp_filter_object_list($wp_post_types, $args, $operator, $field);
+}
+
+/**
+ * Register a post type. Do not use before init.
+ *
+ * A function for creating or modifying a post type based on the
+ * parameters given. The function will accept an array (second optional
+ * parameter), along with a string for the post type name.
+ *
+ * Optional $args contents:
+ *
+ * - label - Name of the post type shown in the menu. Usually plural. If not set, labels['name'] will be used.
+ * - labels - An array of labels for this post type.
+ * * If not set, post labels are inherited for non-hierarchical types and page labels for hierarchical ones.
+ * * You can see accepted values in {@link get_post_type_labels()}.
+ * - description - A short descriptive summary of what the post type is. Defaults to blank.
+ * - public - Whether a post type is intended for use publicly either via the admin interface or by front-end users.
+ * * Defaults to false.
+ * * While the default settings of exclude_from_search, publicly_queryable, show_ui, and show_in_nav_menus are
+ * inherited from public, each does not rely on this relationship and controls a very specific intention.
+ * - hierarchical - Whether the post type is hierarchical (e.g. page). Defaults to false.
+ * - exclude_from_search - Whether to exclude posts with this post type from front end search results.
+ * * If not set, the opposite of public's current value is used.
+ * - publicly_queryable - Whether queries can be performed on the front end for the post type as part of parse_request().
+ * * ?post_type={post_type_key}
+ * * ?{post_type_key}={single_post_slug}
+ * * ?{post_type_query_var}={single_post_slug}
+ * * If not set, the default is inherited from public.
+ * - show_ui - Whether to generate a default UI for managing this post type in the admin.
+ * * If not set, the default is inherited from public.
+ * - show_in_menu - Where to show the post type in the admin menu.
+ * * If true, the post type is shown in its own top level menu.
+ * * If false, no menu is shown
+ * * If a string of an existing top level menu (eg. 'tools.php' or 'edit.php?post_type=page'), the post type will
+ * be placed as a sub menu of that.
+ * * show_ui must be true.
+ * * If not set, the default is inherited from show_ui
+ * - show_in_nav_menus - Makes this post type available for selection in navigation menus.
+ * * If not set, the default is inherited from public.
+ * - show_in_admin_bar - Makes this post type available via the admin bar.
+ * * If not set, the default is inherited from show_in_menu
+ * - menu_position - The position in the menu order the post type should appear.
+ * * show_in_menu must be true
+ * * Defaults to null, which places it at the bottom of its area.
+ * - menu_icon - The url to the icon to be used for this menu. Defaults to use the posts icon.
+ * - capability_type - The string to use to build the read, edit, and delete capabilities. Defaults to 'post'.
+ * * May be passed as an array to allow for alternative plurals when using this argument as a base to construct the
+ * capabilities, e.g. array('story', 'stories').
+ * - capabilities - Array of capabilities for this post type.
+ * * By default the capability_type is used as a base to construct capabilities.
+ * * You can see accepted values in {@link get_post_type_capabilities()}.
+ * - map_meta_cap - Whether to use the internal default meta capability handling. Defaults to false.
+ * - supports - An alias for calling add_post_type_support() directly. Defaults to title and editor.
+ * * See {@link add_post_type_support()} for documentation.
+ * - register_meta_box_cb - Provide a callback function that sets up the meta boxes
+ * for the edit form. Do remove_meta_box() and add_meta_box() calls in the callback.
+ * - taxonomies - An array of taxonomy identifiers that will be registered for the post type.
+ * * Default is no taxonomies.
+ * * Taxonomies can be registered later with register_taxonomy() or register_taxonomy_for_object_type().
+ * - has_archive - True to enable post type archives. Default is false.
+ * * Will generate the proper rewrite rules if rewrite is enabled.
+ * - rewrite - Triggers the handling of rewrites for this post type. Defaults to true, using $post_type as slug.
+ * * To prevent rewrite, set to false.
+ * * To specify rewrite rules, an array can be passed with any of these keys
+ * * 'slug' => string Customize the permastruct slug. Defaults to $post_type key
+ * * 'with_front' => bool Should the permastruct be prepended with WP_Rewrite::$front. Defaults to true.
+ * * 'feeds' => bool Should a feed permastruct be built for this post type. Inherits default from has_archive.
+ * * 'pages' => bool Should the permastruct provide for pagination. Defaults to true.
+ * * 'ep_mask' => const Assign an endpoint mask.
+ * * If not specified and permalink_epmask is set, inherits from permalink_epmask.
+ * * If not specified and permalink_epmask is not set, defaults to EP_PERMALINK
+ * - query_var - Sets the query_var key for this post type. Defaults to $post_type key
+ * * If false, a post type cannot be loaded at ?{query_var}={post_slug}
+ * * If specified as a string, the query ?{query_var_string}={post_slug} will be valid.
+ * - can_export - Allows this post type to be exported. Defaults to true.
+ * - delete_with_user - Whether to delete posts of this type when deleting a user.
+ * * If true, posts of this type belonging to the user will be moved to trash when then user is deleted.
+ * * If false, posts of this type belonging to the user will *not* be trashed or deleted.
+ * * If not set (the default), posts are trashed if post_type_supports('author'). Otherwise posts are not trashed or deleted.
+ * - _builtin - true if this post type is a native or "built-in" post_type. THIS IS FOR INTERNAL USE ONLY!
+ * - _edit_link - URL segement to use for edit link of this post type. THIS IS FOR INTERNAL USE ONLY!
+ *
+ * @since 2.9.0
+ * @uses $wp_post_types Inserts new post type object into the list
+ * @uses $wp_rewrite Gets default feeds
+ * @uses $wp Adds query vars
+ *
+ * @param string $post_type Post type key, must not exceed 20 characters.
+ * @param array|string $args See optional args description above.
+ * @return object|WP_Error the registered post type object, or an error object.
+ */
+function register_post_type( $post_type, $args = array() ) {
+ global $wp_post_types, $wp_rewrite, $wp;
+
+ if ( ! is_array( $wp_post_types ) )
+ $wp_post_types = array();
+
+ // Args prefixed with an underscore are reserved for internal use.
+ $defaults = array(
+ 'labels' => array(),
+ 'description' => '',
+ 'public' => false,
+ 'hierarchical' => false,
+ 'exclude_from_search' => null,
+ 'publicly_queryable' => null,
+ 'show_ui' => null,
+ 'show_in_menu' => null,
+ 'show_in_nav_menus' => null,
+ 'show_in_admin_bar' => null,
+ 'menu_position' => null,
+ 'menu_icon' => null,
+ 'capability_type' => 'post',
+ 'capabilities' => array(),
+ 'map_meta_cap' => null,
+ 'supports' => array(),
+ 'register_meta_box_cb' => null,
+ 'taxonomies' => array(),
+ 'has_archive' => false,
+ 'rewrite' => true,
+ 'query_var' => true,
+ 'can_export' => true,
+ 'delete_with_user' => null,
+ '_builtin' => false,
+ '_edit_link' => 'post.php?post=%d',
+ );
+ $args = wp_parse_args( $args, $defaults );
+ $args = (object) $args;
+
+ $post_type = sanitize_key( $post_type );
+ $args->name = $post_type;
+
+ if ( strlen( $post_type ) > 20 )
+ return new WP_Error( 'post_type_too_long', __( 'Post types cannot exceed 20 characters in length' ) );
+
+ // If not set, default to the setting for public.
+ if ( null === $args->publicly_queryable )
+ $args->publicly_queryable = $args->public;
+
+ // If not set, default to the setting for public.
+ if ( null === $args->show_ui )
+ $args->show_ui = $args->public;
+
+ // If not set, default to the setting for show_ui.
+ if ( null === $args->show_in_menu || ! $args->show_ui )
+ $args->show_in_menu = $args->show_ui;
+
+ // If not set, default to the whether the full UI is shown.
+ if ( null === $args->show_in_admin_bar )
+ $args->show_in_admin_bar = true === $args->show_in_menu;
+
+ // If not set, default to the setting for public.
+ if ( null === $args->show_in_nav_menus )
+ $args->show_in_nav_menus = $args->public;
+
+ // If not set, default to true if not public, false if public.
+ if ( null === $args->exclude_from_search )
+ $args->exclude_from_search = !$args->public;
+
+ // Back compat with quirky handling in version 3.0. #14122
+ if ( empty( $args->capabilities ) && null === $args->map_meta_cap && in_array( $args->capability_type, array( 'post', 'page' ) ) )
+ $args->map_meta_cap = true;
+
+ // If not set, default to false.
+ if ( null === $args->map_meta_cap )
+ $args->map_meta_cap = false;
+
+ $args->cap = get_post_type_capabilities( $args );
+ unset( $args->capabilities );
+
+ if ( is_array( $args->capability_type ) )
+ $args->capability_type = $args->capability_type[0];
+
+ if ( ! empty( $args->supports ) ) {
+ add_post_type_support( $post_type, $args->supports );
+ unset( $args->supports );
+ } elseif ( false !== $args->supports ) {
+ // Add default features
+ add_post_type_support( $post_type, array( 'title', 'editor' ) );
+ }
+
+ if ( false !== $args->query_var && ! empty( $wp ) ) {
+ if ( true === $args->query_var )
+ $args->query_var = $post_type;
+ else
+ $args->query_var = sanitize_title_with_dashes( $args->query_var );
+ $wp->add_query_var( $args->query_var );
+ }
+
+ if ( false !== $args->rewrite && ( is_admin() || '' != get_option( 'permalink_structure' ) ) ) {
+ if ( ! is_array( $args->rewrite ) )
+ $args->rewrite = array();
+ if ( empty( $args->rewrite['slug'] ) )
+ $args->rewrite['slug'] = $post_type;
+ if ( ! isset( $args->rewrite['with_front'] ) )
+ $args->rewrite['with_front'] = true;
+ if ( ! isset( $args->rewrite['pages'] ) )
+ $args->rewrite['pages'] = true;
+ if ( ! isset( $args->rewrite['feeds'] ) || ! $args->has_archive )
+ $args->rewrite['feeds'] = (bool) $args->has_archive;
+ if ( ! isset( $args->rewrite['ep_mask'] ) ) {
+ if ( isset( $args->permalink_epmask ) )
+ $args->rewrite['ep_mask'] = $args->permalink_epmask;
+ else
+ $args->rewrite['ep_mask'] = EP_PERMALINK;
+ }
+
+ if ( $args->hierarchical )
+ add_rewrite_tag( "%$post_type%", '(.+?)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&pagename=" );
+ else
+ add_rewrite_tag( "%$post_type%", '([^/]+)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name=" );
+
+ if ( $args->has_archive ) {
+ $archive_slug = $args->has_archive === true ? $args->rewrite['slug'] : $args->has_archive;
+ if ( $args->rewrite['with_front'] )
+ $archive_slug = substr( $wp_rewrite->front, 1 ) . $archive_slug;
+ else
+ $archive_slug = $wp_rewrite->root . $archive_slug;
+
+ add_rewrite_rule( "{$archive_slug}/?$", "index.php?post_type=$post_type", 'top' );
+ if ( $args->rewrite['feeds'] && $wp_rewrite->feeds ) {
+ $feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')';
+ add_rewrite_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
+ add_rewrite_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
+ }
+ if ( $args->rewrite['pages'] )
+ add_rewrite_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$post_type" . '&paged=$matches[1]', 'top' );
+ }
+
+ $permastruct_args = $args->rewrite;
+ $permastruct_args['feed'] = $permastruct_args['feeds'];
+ add_permastruct( $post_type, "{$args->rewrite['slug']}/%$post_type%", $permastruct_args );
+ }
+
+ if ( $args->register_meta_box_cb )
+ add_action( 'add_meta_boxes_' . $post_type, $args->register_meta_box_cb, 10, 1 );
+
+ $args->labels = get_post_type_labels( $args );
+ $args->label = $args->labels->name;
+
+ $wp_post_types[ $post_type ] = $args;
+
+ add_action( 'future_' . $post_type, '_future_post_hook', 5, 2 );
+
+ foreach ( $args->taxonomies as $taxonomy ) {
+ register_taxonomy_for_object_type( $taxonomy, $post_type );
+ }
+
+ do_action( 'registered_post_type', $post_type, $args );
+
+ return $args;
+}
+
+/**
+ * Builds an object with all post type capabilities out of a post type object
+ *
+ * Post type capabilities use the 'capability_type' argument as a base, if the
+ * capability is not set in the 'capabilities' argument array or if the
+ * 'capabilities' argument is not supplied.
+ *
+ * The capability_type argument can optionally be registered as an array, with
+ * the first value being singular and the second plural, e.g. array('story, 'stories')
+ * Otherwise, an 's' will be added to the value for the plural form. After
+ * registration, capability_type will always be a string of the singular value.
+ *
+ * By default, seven keys are accepted as part of the capabilities array:
+ *
+ * - edit_post, read_post, and delete_post are meta capabilities, which are then
+ * generally mapped to corresponding primitive capabilities depending on the
+ * context, which would be the post being edited/read/deleted and the user or
+ * role being checked. Thus these capabilities would generally not be granted
+ * directly to users or roles.
+ *
+ * - edit_posts - Controls whether objects of this post type can be edited.
+ * - edit_others_posts - Controls whether objects of this type owned by other users
+ * can be edited. If the post type does not support an author, then this will
+ * behave like edit_posts.
+ * - publish_posts - Controls publishing objects of this post type.
+ * - read_private_posts - Controls whether private objects can be read.
+ *
+ * These four primitive capabilities are checked in core in various locations.
+ * There are also seven other primitive capabilities which are not referenced
+ * directly in core, except in map_meta_cap(), which takes the three aforementioned
+ * meta capabilities and translates them into one or more primitive capabilities
+ * that must then be checked against the user or role, depending on the context.
+ *
+ * - read - Controls whether objects of this post type can be read.
+ * - delete_posts - Controls whether objects of this post type can be deleted.
+ * - delete_private_posts - Controls whether private objects can be deleted.
+ * - delete_published_posts - Controls whether published objects can be deleted.
+ * - delete_others_posts - Controls whether objects owned by other users can be
+ * can be deleted. If the post type does not support an author, then this will
+ * behave like delete_posts.
+ * - edit_private_posts - Controls whether private objects can be edited.
+ * - edit_published_posts - Controls whether published objects can be edited.
+ *
+ * These additional capabilities are only used in map_meta_cap(). Thus, they are
+ * only assigned by default if the post type is registered with the 'map_meta_cap'
+ * argument set to true (default is false).
+ *
+ * @see map_meta_cap()
+ * @since 3.0.0
+ *
+ * @param object $args Post type registration arguments
+ * @return object object with all the capabilities as member variables
+ */
+function get_post_type_capabilities( $args ) {
+ if ( ! is_array( $args->capability_type ) )
+ $args->capability_type = array( $args->capability_type, $args->capability_type . 's' );
+
+ // Singular base for meta capabilities, plural base for primitive capabilities.
+ list( $singular_base, $plural_base ) = $args->capability_type;
+
+ $default_capabilities = array(
+ // Meta capabilities
+ 'edit_post' => 'edit_' . $singular_base,
+ 'read_post' => 'read_' . $singular_base,
+ 'delete_post' => 'delete_' . $singular_base,
+ // Primitive capabilities used outside of map_meta_cap():
+ 'edit_posts' => 'edit_' . $plural_base,
+ 'edit_others_posts' => 'edit_others_' . $plural_base,
+ 'publish_posts' => 'publish_' . $plural_base,
+ 'read_private_posts' => 'read_private_' . $plural_base,
+ );
+
+ // Primitive capabilities used within map_meta_cap():
+ if ( $args->map_meta_cap ) {
+ $default_capabilities_for_mapping = array(
+ 'read' => 'read',
+ 'delete_posts' => 'delete_' . $plural_base,
+ 'delete_private_posts' => 'delete_private_' . $plural_base,
+ 'delete_published_posts' => 'delete_published_' . $plural_base,
+ 'delete_others_posts' => 'delete_others_' . $plural_base,
+ 'edit_private_posts' => 'edit_private_' . $plural_base,
+ 'edit_published_posts' => 'edit_published_' . $plural_base,
+ );
+ $default_capabilities = array_merge( $default_capabilities, $default_capabilities_for_mapping );
+ }
+
+ $capabilities = array_merge( $default_capabilities, $args->capabilities );
+
+ // Post creation capability simply maps to edit_posts by default:
+ if ( ! isset( $capabilities['create_posts'] ) )
+ $capabilities['create_posts'] = $capabilities['edit_posts'];
+
+ // Remember meta capabilities for future reference.
+ if ( $args->map_meta_cap )
+ _post_type_meta_capabilities( $capabilities );
+
+ return (object) $capabilities;
+}
+
+/**
+ * Stores or returns a list of post type meta caps for map_meta_cap().
+ *
+ * @since 3.1.0
+ * @access private
+ */
+function _post_type_meta_capabilities( $capabilities = null ) {
+ static $meta_caps = array();
+ if ( null === $capabilities )
+ return $meta_caps;
+ foreach ( $capabilities as $core => $custom ) {
+ if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ) ) )
+ $meta_caps[ $custom ] = $core;
+ }
+}
+
+/**
+ * Builds an object with all post type labels out of a post type object
+ *
+ * Accepted keys of the label array in the post type object:
+ * - name - general name for the post type, usually plural. The same and overridden by $post_type_object->label. Default is Posts/Pages
+ * - singular_name - name for one object of this post type. Default is Post/Page
+ * - add_new - Default is Add New for both hierarchical and non-hierarchical types. When internationalizing this string, please use a {@link http://codex.wordpress.org/I18n_for_WordPress_Developers#Disambiguation_by_context gettext context} matching your post type. Example: <code>_x('Add New', 'product');</code>
+ * - add_new_item - Default is Add New Post/Add New Page
+ * - edit_item - Default is Edit Post/Edit Page
+ * - new_item - Default is New Post/New Page
+ * - view_item - Default is View Post/View Page
+ * - search_items - Default is Search Posts/Search Pages
+ * - not_found - Default is No posts found/No pages found
+ * - not_found_in_trash - Default is No posts found in Trash/No pages found in Trash
+ * - parent_item_colon - This string isn't used on non-hierarchical types. In hierarchical ones the default is Parent Page:
+ * - all_items - String for the submenu. Default is All Posts/All Pages
+ * - menu_name - Default is the same as <code>name</code>
+ *
+ * Above, the first default value is for non-hierarchical post types (like posts) and the second one is for hierarchical post types (like pages).
+ *
+ * @since 3.0.0
+ * @access private
+ *
+ * @param object $post_type_object
+ * @return object object with all the labels as member variables
+ */
+function get_post_type_labels( $post_type_object ) {
+ $nohier_vs_hier_defaults = array(
+ 'name' => array( _x('Posts', 'post type general name'), _x('Pages', 'post type general name') ),
+ 'singular_name' => array( _x('Post', 'post type singular name'), _x('Page', 'post type singular name') ),
+ 'add_new' => array( _x('Add New', 'post'), _x('Add New', 'page') ),
+ 'add_new_item' => array( __('Add New Post'), __('Add New Page') ),
+ 'edit_item' => array( __('Edit Post'), __('Edit Page') ),
+ 'new_item' => array( __('New Post'), __('New Page') ),
+ 'view_item' => array( __('View Post'), __('View Page') ),
+ 'search_items' => array( __('Search Posts'), __('Search Pages') ),
+ 'not_found' => array( __('No posts found.'), __('No pages found.') ),
+ 'not_found_in_trash' => array( __('No posts found in Trash.'), __('No pages found in Trash.') ),
+ 'parent_item_colon' => array( null, __('Parent Page:') ),
+ 'all_items' => array( __( 'All Posts' ), __( 'All Pages' ) )
+ );
+ $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
+
+ $labels = _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults );
+
+ $post_type = $post_type_object->name;
+ return apply_filters( "post_type_labels_{$post_type}", $labels );
+}
+
+/**
+ * Builds an object with custom-something object (post type, taxonomy) labels out of a custom-something object
+ *
+ * @access private
+ * @since 3.0.0
+ */
+function _get_custom_object_labels( $object, $nohier_vs_hier_defaults ) {
+ $object->labels = (array) $object->labels;
+
+ if ( isset( $object->label ) && empty( $object->labels['name'] ) )
+ $object->labels['name'] = $object->label;
+
+ if ( !isset( $object->labels['singular_name'] ) && isset( $object->labels['name'] ) )
+ $object->labels['singular_name'] = $object->labels['name'];
+
+ if ( ! isset( $object->labels['name_admin_bar'] ) )
+ $object->labels['name_admin_bar'] = isset( $object->labels['singular_name'] ) ? $object->labels['singular_name'] : $object->name;
+
+ if ( !isset( $object->labels['menu_name'] ) && isset( $object->labels['name'] ) )
+ $object->labels['menu_name'] = $object->labels['name'];
+
+ if ( !isset( $object->labels['all_items'] ) && isset( $object->labels['menu_name'] ) )
+ $object->labels['all_items'] = $object->labels['menu_name'];
+
+ foreach ( $nohier_vs_hier_defaults as $key => $value )
+ $defaults[$key] = $object->hierarchical ? $value[1] : $value[0];
+
+ $labels = array_merge( $defaults, $object->labels );
+ return (object)$labels;
+}
+
+/**
+ * Adds submenus for post types.
+ *
+ * @access private
+ * @since 3.1.0
+ */
+function _add_post_type_submenus() {
+ foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) {
+ $ptype_obj = get_post_type_object( $ptype );
+ // Submenus only.
+ if ( ! $ptype_obj->show_in_menu || $ptype_obj->show_in_menu === true )
+ continue;
+ add_submenu_page( $ptype_obj->show_in_menu, $ptype_obj->labels->name, $ptype_obj->labels->all_items, $ptype_obj->cap->edit_posts, "edit.php?post_type=$ptype" );
+ }
+}
+add_action( 'admin_menu', '_add_post_type_submenus' );
+
+/**
+ * Register support of certain features for a post type.
+ *
+ * All features are directly associated with a functional area of the edit screen, such as the
+ * editor or a meta box: 'title', 'editor', 'comments', 'revisions', 'trackbacks', 'author',
+ * 'excerpt', 'page-attributes', 'thumbnail', and 'custom-fields'.
+ *
+ * Additionally, the 'revisions' feature dictates whether the post type will store revisions,
+ * and the 'comments' feature dictates whether the comments count will show on the edit screen.
+ *
+ * @since 3.0.0
+ * @param string $post_type The post type for which to add the feature
+ * @param string|array $feature the feature being added, can be an array of feature strings or a single string
+ */
+function add_post_type_support( $post_type, $feature ) {
+ global $_wp_post_type_features;
+
+ $features = (array) $feature;
+ foreach ($features as $feature) {
+ if ( func_num_args() == 2 )
+ $_wp_post_type_features[$post_type][$feature] = true;
+ else
+ $_wp_post_type_features[$post_type][$feature] = array_slice( func_get_args(), 2 );
+ }
+}
+
+/**
+ * Remove support for a feature from a post type.
+ *
+ * @since 3.0.0
+ * @param string $post_type The post type for which to remove the feature
+ * @param string $feature The feature being removed
+ */
+function remove_post_type_support( $post_type, $feature ) {
+ global $_wp_post_type_features;
+
+ if ( isset( $_wp_post_type_features[$post_type][$feature] ) )
+ unset( $_wp_post_type_features[$post_type][$feature] );
+}
+
+/**
+ * Get all the post type features
+ *
+ * @since 3.4.0
+ * @param string $post_type The post type
+ * @return array
+ */
+
+function get_all_post_type_supports( $post_type ) {
+ global $_wp_post_type_features;
+
+ if ( isset( $_wp_post_type_features[$post_type] ) )
+ return $_wp_post_type_features[$post_type];
+
+ return array();
+}
+
+/**
+ * Checks a post type's support for a given feature
+ *
+ * @since 3.0.0
+ * @param string $post_type The post type being checked
+ * @param string $feature the feature being checked
+ * @return boolean
+ */
+
+function post_type_supports( $post_type, $feature ) {
+ global $_wp_post_type_features;
+
+ return ( isset( $_wp_post_type_features[$post_type][$feature] ) );
+}
+
+/**
+ * Updates the post type for the post ID.
+ *
+ * The page or post cache will be cleaned for the post ID.
+ *
+ * @since 2.5.0
+ *
+ * @uses $wpdb
+ *
+ * @param int $post_id Post ID to change post type. Not actually optional.
+ * @param string $post_type Optional, default is post. Supported values are 'post' or 'page' to
+ * name a few.
+ * @return int Amount of rows changed. Should be 1 for success and 0 for failure.
+ */
+function set_post_type( $post_id = 0, $post_type = 'post' ) {
+ global $wpdb;
+
+ $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
+ $return = $wpdb->update( $wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
+
+ clean_post_cache( $post_id );
+
+ return $return;
+}
+
+/**
+ * Retrieve list of latest posts or posts matching criteria.
+ *
+ * The defaults are as follows:
+ * 'numberposts' - Default is 5. Total number of posts to retrieve.
+ * 'offset' - Default is 0. See {@link WP_Query::query()} for more.
+ * 'category' - What category to pull the posts from.
+ * 'orderby' - Default is 'post_date'. How to order the posts.
+ * 'order' - Default is 'DESC'. The order to retrieve the posts.
+ * 'include' - See {@link WP_Query::query()} for more.
+ * 'exclude' - See {@link WP_Query::query()} for more.
+ * 'meta_key' - See {@link WP_Query::query()} for more.
+ * 'meta_value' - See {@link WP_Query::query()} for more.
+ * 'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few.
+ * 'post_parent' - The parent of the post or post type.
+ * 'post_status' - Default is 'publish'. Post status to retrieve.
+ *
+ * @since 1.2.0
+ * @uses WP_Query::query() See for more default arguments and information.
+ * @link http://codex.wordpress.org/Template_Tags/get_posts
+ *
+ * @param array $args Optional. Overrides defaults.
+ * @return array List of posts.
+ */
+function get_posts($args = null) {
+ $defaults = array(
+ 'numberposts' => 5, 'offset' => 0,
+ 'category' => 0, 'orderby' => 'post_date',
+ 'order' => 'DESC', 'include' => array(),
+ 'exclude' => array(), 'meta_key' => '',
+ 'meta_value' =>'', 'post_type' => 'post',
+ 'suppress_filters' => true
+ );
+
+ $r = wp_parse_args( $args, $defaults );
+ if ( empty( $r['post_status'] ) )
+ $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
+ if ( ! empty($r['numberposts']) && empty($r['posts_per_page']) )
+ $r['posts_per_page'] = $r['numberposts'];
+ if ( ! empty($r['category']) )
+ $r['cat'] = $r['category'];
+ if ( ! empty($r['include']) ) {
+ $incposts = wp_parse_id_list( $r['include'] );
+ $r['posts_per_page'] = count($incposts); // only the number of posts included
+ $r['post__in'] = $incposts;
+ } elseif ( ! empty($r['exclude']) )
+ $r['post__not_in'] = wp_parse_id_list( $r['exclude'] );
+
+ $r['ignore_sticky_posts'] = true;
+ $r['no_found_rows'] = true;
+
+ $get_posts = new WP_Query;
+ return $get_posts->query($r);
+
+}
+
+//
+// Post meta functions
+//
+
+/**
+ * Add meta data field to a post.
+ *
+ * Post meta data is called "Custom Fields" on the Administration Screen.
+ *
+ * @since 1.5.0
+ * @link http://codex.wordpress.org/Function_Reference/add_post_meta
+ *
+ * @param int $post_id Post ID.
+ * @param string $meta_key Metadata name.
+ * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
+ * @param bool $unique Optional, default is false. Whether the same key should not be added.
+ * @return int|bool Meta ID on success, false on failure.
+ */
+function add_post_meta($post_id, $meta_key, $meta_value, $unique = false) {
+ // make sure meta is added to the post, not a revision
+ if ( $the_post = wp_is_post_revision($post_id) )
+ $post_id = $the_post;
+
+ return add_metadata('post', $post_id, $meta_key, $meta_value, $unique);
+}
+
+/**
+ * Remove metadata matching criteria from a post.
+ *
+ * You can match based on the key, or key and value. Removing based on key and
+ * value, will keep from removing duplicate metadata with the same key. It also
+ * allows removing all metadata matching key, if needed.
+ *
+ * @since 1.5.0
+ * @link http://codex.wordpress.org/Function_Reference/delete_post_meta
+ *
+ * @param int $post_id post ID
+ * @param string $meta_key Metadata name.
+ * @param mixed $meta_value Optional. Metadata value. Must be serializable if non-scalar.
+ * @return bool True on success, false on failure.
+ */
+function delete_post_meta($post_id, $meta_key, $meta_value = '') {
+ // make sure meta is added to the post, not a revision
+ if ( $the_post = wp_is_post_revision($post_id) )
+ $post_id = $the_post;
+
+ return delete_metadata('post', $post_id, $meta_key, $meta_value);
+}
+
+/**
+ * Retrieve post meta field for a post.
+ *
+ * @since 1.5.0
+ * @link http://codex.wordpress.org/Function_Reference/get_post_meta
+ *
+ * @param int $post_id Post ID.
+ * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
+ * @param bool $single Whether to return a single value.
+ * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
+ * is true.
+ */
+function get_post_meta($post_id, $key = '', $single = false) {
+ return get_metadata('post', $post_id, $key, $single);
+}
+
+/**
+ * Update post meta field based on post ID.
+ *
+ * Use the $prev_value parameter to differentiate between meta fields with the
+ * same key and post ID.
+ *
+ * If the meta field for the post does not exist, it will be added.
+ *
+ * @since 1.5.0
+ * @link http://codex.wordpress.org/Function_Reference/update_post_meta
+ *
+ * @param int $post_id Post ID.
+ * @param string $meta_key Metadata key.
+ * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
+ * @param mixed $prev_value Optional. Previous value to check before removing.
+ * @return bool True on success, false on failure.
+ */
+function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') {
+ // make sure meta is added to the post, not a revision
+ if ( $the_post = wp_is_post_revision($post_id) )
+ $post_id = $the_post;
+
+ return update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value);
+}
+
+/**
+ * Delete everything from post meta matching meta key.
+ *
+ * @since 2.3.0
+ *
+ * @param string $post_meta_key Key to search for when deleting.
+ * @return bool Whether the post meta key was deleted from the database
+ */
+function delete_post_meta_by_key($post_meta_key) {
+ return delete_metadata( 'post', null, $post_meta_key, '', true );
+}
+
+/**
+ * Retrieve post meta fields, based on post ID.
+ *
+ * The post meta fields are retrieved from the cache where possible,
+ * so the function is optimized to be called more than once.
+ *
+ * @since 1.2.0
+ * @link http://codex.wordpress.org/Function_Reference/get_post_custom
+ *
+ * @param int $post_id Post ID.
+ * @return array
+ */
+function get_post_custom( $post_id = 0 ) {
+ $post_id = absint( $post_id );
+ if ( ! $post_id )
+ $post_id = get_the_ID();
+
+ return get_post_meta( $post_id );
+}
+
+/**
+ * Retrieve meta field names for a post.
+ *
+ * If there are no meta fields, then nothing (null) will be returned.
+ *
+ * @since 1.2.0
+ * @link http://codex.wordpress.org/Function_Reference/get_post_custom_keys
+ *
+ * @param int $post_id post ID
+ * @return array|null Either array of the keys, or null if keys could not be retrieved.
+ */
+function get_post_custom_keys( $post_id = 0 ) {
+ $custom = get_post_custom( $post_id );
+
+ if ( !is_array($custom) )
+ return;
+
+ if ( $keys = array_keys($custom) )
+ return $keys;
+}
+
+/**
+ * Retrieve values for a custom post field.
+ *
+ * The parameters must not be considered optional. All of the post meta fields
+ * will be retrieved and only the meta field key values returned.
+ *
+ * @since 1.2.0
+ * @link http://codex.wordpress.org/Function_Reference/get_post_custom_values
+ *
+ * @param string $key Meta field key.
+ * @param int $post_id Post ID
+ * @return array Meta field values.
+ */
+function get_post_custom_values( $key = '', $post_id = 0 ) {
+ if ( !$key )
+ return null;
+
+ $custom = get_post_custom($post_id);
+
+ return isset($custom[$key]) ? $custom[$key] : null;
+}
+
+/**
+ * Check if post is sticky.
+ *
+ * Sticky posts should remain at the top of The Loop. If the post ID is not
+ * given, then The Loop ID for the current post will be used.
+ *
+ * @since 2.7.0
+ *
+ * @param int $post_id Optional. Post ID.
+ * @return bool Whether post is sticky.
+ */
+function is_sticky( $post_id = 0 ) {
+ $post_id = absint( $post_id );
+
+ if ( ! $post_id )
+ $post_id = get_the_ID();
+
+ $stickies = get_option( 'sticky_posts' );
+
+ if ( ! is_array( $stickies ) )
+ return false;
+
+ if ( in_array( $post_id, $stickies ) )
+ return true;
+
+ return false;
+}
+
+/**
+ * Sanitize every post field.
+ *
+ * If the context is 'raw', then the post object or array will get minimal santization of the int fields.
+ *
+ * @since 2.3.0
+ * @uses sanitize_post_field() Used to sanitize the fields.
+ *
+ * @param object|WP_Post|array $post The Post Object or Array
+ * @param string $context Optional, default is 'display'. How to sanitize post fields.
+ * @return object|WP_Post|array The now sanitized Post Object or Array (will be the same type as $post)
+ */
+function sanitize_post($post, $context = 'display') {
+ if ( is_object($post) ) {
+ // Check if post already filtered for this context
+ if ( isset($post->filter) && $context == $post->filter )
+ return $post;
+ if ( !isset($post->ID) )
+ $post->ID = 0;
+ foreach ( array_keys(get_object_vars($post)) as $field )
+ $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
+ $post->filter = $context;
+ } else {
+ // Check if post already filtered for this context
+ if ( isset($post['filter']) && $context == $post['filter'] )
+ return $post;
+ if ( !isset($post['ID']) )
+ $post['ID'] = 0;
+ foreach ( array_keys($post) as $field )
+ $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
+ $post['filter'] = $context;
+ }
+ return $post;
+}
+
+/**
+ * Sanitize post field based on context.
+ *
+ * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
+ * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
+ * when calling filters.
+ *
+ * @since 2.3.0
+ * @uses apply_filters() Calls 'edit_$field' and '{$field_no_prefix}_edit_pre' passing $value and
+ * $post_id if $context == 'edit' and field name prefix == 'post_'.
+ *
+ * @uses apply_filters() Calls 'edit_post_$field' passing $value and $post_id if $context == 'db'.
+ * @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db' and field name prefix == 'post_'.
+ * @uses apply_filters() Calls '{$field}_pre' passing $value if $context == 'db' and field name prefix != 'post_'.
+ *
+ * @uses apply_filters() Calls '$field' passing $value, $post_id and $context if $context == anything
+ * other than 'raw', 'edit' and 'db' and field name prefix == 'post_'.
+ * @uses apply_filters() Calls 'post_$field' passing $value if $context == anything other than 'raw',
+ * 'edit' and 'db' and field name prefix != 'post_'.
+ *
+ * @param string $field The Post Object field name.
+ * @param mixed $value The Post Object value.
+ * @param int $post_id Post ID.
+ * @param string $context How to sanitize post fields. Looks for 'raw', 'edit', 'db', 'display',
+ * 'attribute' and 'js'.
+ * @return mixed Sanitized value.
+ */
+function sanitize_post_field($field, $value, $post_id, $context) {
+ $int_fields = array('ID', 'post_parent', 'menu_order');
+ if ( in_array($field, $int_fields) )
+ $value = (int) $value;
+
+ // Fields which contain arrays of ints.
+ $array_int_fields = array( 'ancestors' );
+ if ( in_array($field, $array_int_fields) ) {
+ $value = array_map( 'absint', $value);
+ return $value;
+ }
+
+ if ( 'raw' == $context )
+ return $value;
+
+ $prefixed = false;
+ if ( false !== strpos($field, 'post_') ) {
+ $prefixed = true;
+ $field_no_prefix = str_replace('post_', '', $field);
+ }
+
+ if ( 'edit' == $context ) {
+ $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
+
+ if ( $prefixed ) {
+ $value = apply_filters("edit_{$field}", $value, $post_id);
+ // Old school
+ $value = apply_filters("{$field_no_prefix}_edit_pre", $value, $post_id);
+ } else {
+ $value = apply_filters("edit_post_{$field}", $value, $post_id);
+ }
+
+ if ( in_array($field, $format_to_edit) ) {
+ if ( 'post_content' == $field )
+ $value = format_to_edit($value, user_can_richedit());
+ else
+ $value = format_to_edit($value);
+ } else {
+ $value = esc_attr($value);
+ }
+ } else if ( 'db' == $context ) {
+ if ( $prefixed ) {
+ $value = apply_filters("pre_{$field}", $value);
+ $value = apply_filters("{$field_no_prefix}_save_pre", $value);
+ } else {
+ $value = apply_filters("pre_post_{$field}", $value);
+ $value = apply_filters("{$field}_pre", $value);
+ }
+ } else {
+ // Use display filters by default.
+ if ( $prefixed )
+ $value = apply_filters($field, $value, $post_id, $context);
+ else
+ $value = apply_filters("post_{$field}", $value, $post_id, $context);
+ }
+
+ if ( 'attribute' == $context )
+ $value = esc_attr($value);
+ else if ( 'js' == $context )
+ $value = esc_js($value);
+
+ return $value;
+}
+
+/**
+ * Make a post sticky.
+ *
+ * Sticky posts should be displayed at the top of the front page.
+ *
+ * @since 2.7.0
+ *
+ * @param int $post_id Post ID.
+ */
+function stick_post($post_id) {
+ $stickies = get_option('sticky_posts');
+
+ if ( !is_array($stickies) )
+ $stickies = array($post_id);
+
+ if ( ! in_array($post_id, $stickies) )
+ $stickies[] = $post_id;
+
+ update_option('sticky_posts', $stickies);
+}
+
+/**
+ * Unstick a post.
+ *
+ * Sticky posts should be displayed at the top of the front page.
+ *
+ * @since 2.7.0
+ *
+ * @param int $post_id Post ID.
+ */
+function unstick_post($post_id) {
+ $stickies = get_option('sticky_posts');
+
+ if ( !is_array($stickies) )
+ return;
+
+ if ( ! in_array($post_id, $stickies) )
+ return;
+
+ $offset = array_search($post_id, $stickies);
+ if ( false === $offset )
+ return;
+
+ array_splice($stickies, $offset, 1);
+
+ update_option('sticky_posts', $stickies);
+}
+
+/**
+ * Count number of posts of a post type and if user has permissions to view.
+ *
+ * This function provides an efficient method of finding the amount of post's
+ * type a blog has. Another method is to count the amount of items in
+ * get_posts(), but that method has a lot of overhead with doing so. Therefore,
+ * when developing for 2.5+, use this function instead.
+ *
+ * The $perm parameter checks for 'readable' value and if the user can read
+ * private posts, it will display that for the user that is signed in.
+ *
+ * @link http://codex.wordpress.org/Template_Tags/wp_count_posts
+ *
+ * @since 2.5.0
+ *
+ * @param string $type Optional. Post type to retrieve count
+ * @param string $perm Optional. 'readable' or empty.
+ * @return object Number of posts for each status
+ */
+function wp_count_posts( $type = 'post', $perm = '' ) {
+ global $wpdb;
+
+ if ( ! post_type_exists( $type ) )
+ return new stdClass;
+
+ $user = wp_get_current_user();
+
+ $cache_key = 'posts-' . $type;
+
+ $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
+ if ( 'readable' == $perm && is_user_logged_in() ) {
+ $post_type_object = get_post_type_object($type);
+ if ( !current_user_can( $post_type_object->cap->read_private_posts ) ) {
+ $cache_key .= '_' . $perm . '_' . $user->ID;
+ $query .= " AND (post_status != 'private' OR ( post_author = '$user->ID' AND post_status = 'private' ))";
+ }
+ }
+ $query .= ' GROUP BY post_status';
+
+ $counts = wp_cache_get( $cache_key, 'counts' );
+ if ( false === $counts ) {
+ $results = (array) $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
+ $counts = array_fill_keys( get_post_stati(), 0 );
+
+ foreach ( $results as $row )
+ $counts[ $row['post_status'] ] = $row['num_posts'];
+
+ $counts = (object) $counts;
+ wp_cache_set( $cache_key, $counts, 'counts' );
+ }
+
+ /**
+ * Modify returned post counts by status for the current post type.
+ *
+ * @since 3.7.0
+ *
+ * @param object $counts An object containing the current post_type's post counts by status.
+ * @param string $type The post type.
+ * @param string $perm The permission to determine if the posts are 'readable' by the current user.
+ */
+ return apply_filters( 'wp_count_posts', $counts, $type, $perm );
+}
+
+/**
+ * Count number of attachments for the mime type(s).
+ *
+ * If you set the optional mime_type parameter, then an array will still be
+ * returned, but will only have the item you are looking for. It does not give
+ * you the number of attachments that are children of a post. You can get that
+ * by counting the number of children that post has.
+ *
+ * @since 2.5.0
+ *
+ * @param string|array $mime_type Optional. Array or comma-separated list of MIME patterns.
+ * @return array Number of posts for each mime type.
+ */
+function wp_count_attachments( $mime_type = '' ) {
+ global $wpdb;
+
+ $and = wp_post_mime_type_where( $mime_type );
+ $count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' $and GROUP BY post_mime_type", ARRAY_A );
+
+ $counts = array();
+ foreach( (array) $count as $row ) {
+ $counts[ $row['post_mime_type'] ] = $row['num_posts'];
+ }
+ $counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and");
+
+ /**
+ * Modify returned attachment counts by mime type.
+ *
+ * @since 3.7.0
+ *
+ * @param object $counts An object containing the attachment counts by mime type.
+ * @param string $mime_type The mime type pattern used to filter the attachments counted.
+ */
+ return apply_filters( 'wp_count_attachments', (object) $counts, $mime_type );
+}
+
+/**
+ * Get default post mime types
+ *
+ * @since 2.9.0
+ *
+ * @return array
+ */
+function get_post_mime_types() {
+ $post_mime_types = array( // array( adj, noun )
+ 'image' => array(__('Images'), __('Manage Images'), _n_noop('Image <span class="count">(%s)</span>', 'Images <span class="count">(%s)</span>')),
+ 'audio' => array(__('Audio'), __('Manage Audio'), _n_noop('Audio <span class="count">(%s)</span>', 'Audio <span class="count">(%s)</span>')),
+ 'video' => array(__('Video'), __('Manage Video'), _n_noop('Video <span class="count">(%s)</span>', 'Video <span class="count">(%s)</span>')),
+ );
+
+ return apply_filters('post_mime_types', $post_mime_types);
+}
+
+/**
+ * Check a MIME-Type against a list.
+ *
+ * If the wildcard_mime_types parameter is a string, it must be comma separated
+ * list. If the real_mime_types is a string, it is also comma separated to
+ * create the list.
+ *
+ * @since 2.5.0
+ *
+ * @param string|array $wildcard_mime_types e.g. audio/mpeg or image (same as image/*) or
+ * flash (same as *flash*).
+ * @param string|array $real_mime_types post_mime_type values
+ * @return array array(wildcard=>array(real types))
+ */
+function wp_match_mime_types($wildcard_mime_types, $real_mime_types) {
+ $matches = array();
+ if ( is_string($wildcard_mime_types) )
+ $wildcard_mime_types = array_map('trim', explode(',', $wildcard_mime_types));
+ if ( is_string($real_mime_types) )
+ $real_mime_types = array_map('trim', explode(',', $real_mime_types));
+ $wild = '[-._a-z0-9]*';
+ foreach ( (array) $wildcard_mime_types as $type ) {
+ $type = str_replace('*', $wild, $type);
+ $patternses[1][$type] = "^$type$";
+ if ( false === strpos($type, '/') ) {
+ $patternses[2][$type] = "^$type/";
+ $patternses[3][$type] = $type;
+ }
+ }
+ asort($patternses);
+ foreach ( $patternses as $patterns )
+ foreach ( $patterns as $type => $pattern )
+ foreach ( (array) $real_mime_types as $real )
+ if ( preg_match("#$pattern#", $real) && ( empty($matches[$type]) || false === array_search($real, $matches[$type]) ) )
+ $matches[$type][] = $real;
+ return $matches;
+}
+
+/**
+ * Convert MIME types into SQL.
+ *
+ * @since 2.5.0
+ *
+ * @param string|array $post_mime_types List of mime types or comma separated string of mime types.
+ * @param string $table_alias Optional. Specify a table alias, if needed.
+ * @return string The SQL AND clause for mime searching.
+ */
+function wp_post_mime_type_where($post_mime_types, $table_alias = '') {
+ $where = '';
+ $wildcards = array('', '%', '%/%');
+ if ( is_string($post_mime_types) )
+ $post_mime_types = array_map('trim', explode(',', $post_mime_types));
+ foreach ( (array) $post_mime_types as $mime_type ) {
+ $mime_type = preg_replace('/\s/', '', $mime_type);
+ $slashpos = strpos($mime_type, '/');
+ if ( false !== $slashpos ) {
+ $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
+ $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
+ if ( empty($mime_subgroup) )
+ $mime_subgroup = '*';
+ else
+ $mime_subgroup = str_replace('/', '', $mime_subgroup);
+ $mime_pattern = "$mime_group/$mime_subgroup";
+ } else {
+ $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
+ if ( false === strpos($mime_pattern, '*') )
+ $mime_pattern .= '/*';
+ }
+
+ $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
+
+ if ( in_array( $mime_type, $wildcards ) )
+ return '';
+
+ if ( false !== strpos($mime_pattern, '%') )
+ $wheres[] = empty($table_alias) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'";
+ else
+ $wheres[] = empty($table_alias) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'";
+ }
+ if ( !empty($wheres) )
+ $where = ' AND (' . join(' OR ', $wheres) . ') ';
+ return $where;
+}
+
+/**
+ * Trashes or deletes a post or page.
+ *
+ * When the post and page is permanently deleted, everything that is tied to it is deleted also.
+ * This includes comments, post meta fields, and terms associated with the post.
+ *
+ * The post or page is moved to trash instead of permanently deleted unless trash is
+ * disabled, item is already in the trash, or $force_delete is true.
+ *
+ * @since 1.0.0
+ * @uses do_action() on 'delete_post' before deletion unless post type is 'attachment'.
+ * @uses do_action() on 'deleted_post' after deletion unless post type is 'attachment'.
+ * @uses wp_delete_attachment() if post type is 'attachment'.
+ * @uses wp_trash_post() if item should be trashed.
+ *
+ * @param int $postid Post ID.
+ * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false.
+ * @return mixed False on failure
+ */
+function wp_delete_post( $postid = 0, $force_delete = false ) {
+ global $wpdb;
+
+ if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
+ return $post;
+
+ if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS )
+ return wp_trash_post($postid);
+
+ if ( $post->post_type == 'attachment' )
+ return wp_delete_attachment( $postid, $force_delete );
+
+ do_action('before_delete_post', $postid);
+
+ delete_post_meta($postid,'_wp_trash_meta_status');
+ delete_post_meta($postid,'_wp_trash_meta_time');
+
+ wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
+
+ $parent_data = array( 'post_parent' => $post->post_parent );
+ $parent_where = array( 'post_parent' => $postid );
+
+ if ( is_post_type_hierarchical( $post->post_type ) ) {
+ // Point children of this page to its parent, also clean the cache of affected children
+ $children_query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s", $postid, $post->post_type );
+ $children = $wpdb->get_results( $children_query );
+
+ $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) );
+ }
+
+ // Do raw query. wp_get_post_revisions() is filtered
+ $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
+ // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
+ foreach ( $revision_ids as $revision_id )
+ wp_delete_post_revision( $revision_id );
+
+ // Point all attachments to this post up one level
+ $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
+
+ $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
+ foreach ( $comment_ids as $comment_id )
+ wp_delete_comment( $comment_id, true );
+
+ $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
+ foreach ( $post_meta_ids as $mid )
+ delete_metadata_by_mid( 'post', $mid );
+
+ do_action( 'delete_post', $postid );
+ $wpdb->delete( $wpdb->posts, array( 'ID' => $postid ) );
+ do_action( 'deleted_post', $postid );
+
+ clean_post_cache( $post );
+
+ if ( is_post_type_hierarchical( $post->post_type ) && $children ) {
+ foreach ( $children as $child )
+ clean_post_cache( $child );
+ }
+
+ wp_clear_scheduled_hook('publish_future_post', array( $postid ) );
+
+ do_action('after_delete_post', $postid);
+
+ return $post;
+}
+
+/**
+ * Resets the page_on_front, show_on_front, and page_for_post settings when a
+ * linked page is deleted or trashed.
+ *
+ * Also ensures the post is no longer sticky.
+ *
+ * @access private
+ * @since 3.7.0
+ * @param $post_id
+ */
+function _reset_front_page_settings_for_post( $post_id ) {
+ $post = get_post( $post_id );
+ if ( 'page' == $post->post_type ) {
+ // If the page is defined in option page_on_front or post_for_posts,
+ // adjust the corresponding options
+ if ( get_option( 'page_on_front' ) == $post->ID ) {
+ update_option( 'show_on_front', 'posts' );
+ update_option( 'page_on_front', 0 );
+ }
+ if ( get_option( 'page_for_posts' ) == $post->ID ) {
+ delete_option( 'page_for_posts', 0 );
+ }
+ }
+ unstick_post( $post->ID );
+}
+add_action( 'before_delete_post', '_reset_front_page_settings_for_post' );
+add_action( 'wp_trash_post', '_reset_front_page_settings_for_post' );
+
+/**
+ * Moves a post or page to the Trash
+ *
+ * If trash is disabled, the post or page is permanently deleted.
+ *
+ * @since 2.9.0
+ * @uses do_action() on 'trash_post' before trashing
+ * @uses do_action() on 'trashed_post' after trashing
+ * @uses wp_delete_post() if trash is disabled
+ *
+ * @param int $post_id Post ID.
+ * @return mixed False on failure
+ */
+function wp_trash_post($post_id = 0) {
+ if ( !EMPTY_TRASH_DAYS )
+ return wp_delete_post($post_id, true);
+
+ if ( !$post = get_post($post_id, ARRAY_A) )
+ return $post;
+
+ if ( $post['post_status'] == 'trash' )
+ return false;
+
+ do_action('wp_trash_post', $post_id);
+
+ add_post_meta($post_id,'_wp_trash_meta_status', $post['post_status']);
+ add_post_meta($post_id,'_wp_trash_meta_time', time());
+
+ $post['post_status'] = 'trash';
+ wp_insert_post($post);
+
+ wp_trash_post_comments($post_id);
+
+ do_action('trashed_post', $post_id);
+
+ return $post;
+}
+
+/**
+ * Restores a post or page from the Trash
+ *
+ * @since 2.9.0
+ * @uses do_action() on 'untrash_post' before undeletion
+ * @uses do_action() on 'untrashed_post' after undeletion
+ *
+ * @param int $post_id Post ID.
+ * @return mixed False on failure
+ */
+function wp_untrash_post($post_id = 0) {
+ if ( !$post = get_post($post_id, ARRAY_A) )
+ return $post;
+
+ if ( $post['post_status'] != 'trash' )
+ return false;
+
+ do_action('untrash_post', $post_id);
+
+ $post_status = get_post_meta($post_id, '_wp_trash_meta_status', true);
+
+ $post['post_status'] = $post_status;
+
+ delete_post_meta($post_id, '_wp_trash_meta_status');
+ delete_post_meta($post_id, '_wp_trash_meta_time');
+
+ wp_insert_post($post);
+
+ wp_untrash_post_comments($post_id);