Ejemplo n.º 1
0
 protected function lazyLoadProperty($key)
 {
     switch ($key) {
         case 'page_template':
             return $this->page_template = get_post_meta($this->ID, '_wp_page_template', true);
         case 'post_category':
             if (is_object_in_taxonomy($this->post_type, 'category')) {
                 $terms = get_the_terms($this->ID, 'category');
                 if (empty($terms)) {
                     $this->post_category = array();
                 } else {
                     $this->post_category = wp_list_pluck($terms, 'term_id');
                 }
             }
             return $this->post_category;
         case 'tags_input':
             if (is_object_in_taxonomy($this->post_type, 'post_tag')) {
                 $terms = get_the_terms($this->ID, 'post_tag');
                 if (empty($terms)) {
                     $this->tags_input = array();
                 } else {
                     $this->tags_input = wp_list_pluck($terms, 'name');
                 }
             }
             return $this->tags_input;
         case 'ancestors':
             return $this->ancestors = get_post_ancestors($this);
         default:
             break;
     }
     throw new \InvalidArgumentException("Invalid lazy-loaded property '{$key}'");
 }
    function extra_tablenav($which)
    {
        global $post_type_object, $cat;
        ?>
		<div class="alignleft actions">
<?php 
        if ('top' == $which && !is_singular()) {
            $this->months_dropdown($post_type_object->name);
            if (is_object_in_taxonomy($post_type_object->name, 'category')) {
                $dropdown_options = array('show_option_all' => __('View all categories'), 'hide_empty' => 0, 'hierarchical' => 1, 'show_count' => 0, 'orderby' => 'name', 'selected' => $cat);
                wp_dropdown_categories($dropdown_options);
            }
            ?>
			&nbsp;
			<input type="checkbox" name="no_recipes" <?php 
            if (isset($_GET["no_recipes"])) {
                echo "checked='checked'";
            }
            ?>
/>  Hide Posts With Recipes  &nbsp;
			<?php 
            do_action('restrict_manage_posts');
            submit_button(__('Filter'), 'secondary', false, false, array('id' => 'post-query-submit'));
        }
        if ($this->is_trash && current_user_can($post_type_object->cap->edit_others_posts)) {
            submit_button(__('Empty Trash'), 'button-secondary apply', 'delete_all', false);
        }
        ?>
		</div>
<?php 
    }
    function extra_tablenav($which)
    {
        global $post_type_object, $cat;
        $term_id = 0;
        ?>
		<div class="alignleft actions"> <?php 
        if ('top' == $which && !is_singular()) {
            $this->months_dropdown(self::$post_type);
            if (is_object_in_taxonomy(self::$post_type, SI_Record::TAXONOMY)) {
                $term_id = isset($_GET[SI_Record::TAXONOMY]) ? $_GET[SI_Record::TAXONOMY] : 0;
                $dropdown_options = array('taxonomy' => SI_Record::TAXONOMY, 'show_option_all' => __('View all types'), 'hide_empty' => 0, 'hierarchical' => 1, 'show_count' => 0, 'orderby' => 'name', 'selected' => $term_id, 'name' => SI_Record::TAXONOMY);
                wp_dropdown_categories($dropdown_options);
            }
            do_action('restrict_manage_posts');
            submit_button(__('Filter'), 'secondary', false, false, array('id' => 'post-query-submit'));
            // Purge
            if (count($this->items) > 0) {
                if (isset($_GET[SI_Record::TAXONOMY]) && $_GET[SI_Record::TAXONOMY]) {
                    $term = get_term($_GET[SI_Record::TAXONOMY], SI_Record::TAXONOMY);
                    $button_label = __('Purge') . ' ' . $term->name . ' ' . __('Type');
                }
                $button_label = isset($button_label) ? $button_label : __('Purge All Types');
                printf('<button type="submit" name="purge_records" class="button" value="%s">%s</button>', $term_id, $button_label);
                printf('<input type="hidden" name="%s" value="%s" />', SI_Internal_Records::RECORD_PURGE_NONCE, wp_create_nonce(SI_Internal_Records::RECORD_PURGE_NONCE));
            }
        }
        ?>

		</div> <?php 
    }
function sfhiv_draw_taxonomy_query_menu($tax_name, $query, $args = array())
{
    if (!is_object_in_taxonomy($query->query_vars['post_type'], $tax_name)) {
        return;
    }
    if (!isset($args['include'])) {
        $query = sfhiv_remove_url_vars_from_query($query, array($tax_name));
        $query = sfhiv_unpage_query($query);
        $categories = sfhiv_get_taxonomy_in($query, $tax_name, 'ids');
        $args['include'] = implode(",", $categories);
        if (!isset($args['min_display'])) {
            $args['min_display'] = 2;
        }
        if (count($categories) < $args['min_display']) {
            return;
        }
    }
    if (!isset($args['base_link'])) {
        if (is_page() && mini_archive_on_page(get_the_ID())) {
            $args['base_link'] = get_permalink();
        } else {
            $args['base_link'] = get_post_type_archive_link($query->query_vars['post_type']);
        }
    }
    if (!isset($args['title_li'])) {
        $taxonomies = get_taxonomies(array('name' => $tax_name), 'objects');
        foreach ($taxonomies as $taxonomy) {
            $args['title_li'] = $taxonomy->label;
        }
    }
    $args = array_merge(array('taxonomy' => $tax_name, 'show_all_link' => true), $args);
    sfhiv_draw_taxonomy_menu($args);
}
Ejemplo n.º 5
0
function twentyten_posted_in()
{
    // Retrieves tag list of current post, separated by commas.
    $tag_list = get_the_tag_list('', ', ');
    $temp_tag_array = explode(', ', $tag_list);
    $buf_tag_list = array();
    foreach ($temp_tag_array as $temp_tag) {
        if (strpos($temp_tag, "html") > 0) {
            $buf_tag_list[] = '<div class="html">' . $temp_tag . '</div>';
        } elseif (strpos($temp_tag, "css") > 0) {
            $buf_tag_list[] = '<div class="css">' . $temp_tag . '</div>';
        } elseif (strpos($temp_tag, "jquery") > 0) {
            $buf_tag_list[] = '<div class="jquery">' . $temp_tag . '</div>';
        } elseif (strpos($temp_tag, "Javascript") > 0) {
            $buf_tag_list[] = '<div class="Javascript">' . $temp_tag . '</div>';
        } elseif (strpos($temp_tag, "wordpress") > 0) {
            $buf_tag_list[] = '<div class="wordpress">' . $temp_tag . '</div>';
        } else {
            $buf_tag_list[] = $temp_tag;
        }
    }
    $tag_list = implode(', ', $buf_tag_list);
    if ($tag_list) {
        $posted_in = __('This entry was posted in %1$s and tagged %2$s. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'twentyten');
    } elseif (is_object_in_taxonomy(get_post_type(), 'category')) {
        $posted_in = __('This entry was posted in %1$s. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'twentyten');
    } else {
        $posted_in = __('Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'twentyten');
    }
    // Prints the string, replacing the placeholders.
    printf($posted_in, get_the_category_list(', '), $tag_list, get_permalink(), the_title_attribute('echo=0'));
}
Ejemplo n.º 6
0
function iron_post_class_terms($classes = array())
{
    global $post, $iron_taxonomies;
    /*
    	// Tags
    	if ( is_object_in_taxonomy( $post->post_type, 'post_tag' ) ) {
    		foreach ( (array) get_the_tags($post->ID) as $tag ) {
    			if ( empty($tag->slug ) )
    				continue;
    			$classes[] = 'tag-' . sanitize_html_class($tag->slug, $tag->term_id);
    		}
    	}
    */
    global $post;
    foreach ($iron_taxonomies as $tax) {
        if (is_object_in_taxonomy($post->post_type, $tax)) {
            $terms = get_the_terms($post->ID, $tax);
            foreach ((array) $terms as $term) {
                if (empty($term->slug)) {
                    continue;
                }
                $classes[] = sanitize_html_class($tax, 'tax') . '-' . sanitize_html_class($term->slug, $term->term_id);
            }
            # Alternate
            // $terms = wp_list_pluck($terms, 'slug');
            // $classes = array_merge($classes, $terms);
        }
    }
    return $classes;
}
 function zm_base_posted_in()
 {
     // Retrieves tag list of current post, separated by commas.
     $tag_list = get_the_tag_list('', ', ');
     if ($tag_list) {
         $posted_in = __('<span class="zm-base-posted-in"> &nbsp;Posted in %1$s </span> Tags %2$s', 'collection');
     } elseif (is_object_in_taxonomy(get_post_type(), 'category')) {
         $posted_in = __('<span class="zm-base-posted-in"> Posted in %1$s </span> ', 'collection');
     } else {
         $posted_in = null;
     }
     // Prints the string, replacing the placeholders.
     printf($posted_in, get_the_category_list(', '), $tag_list, get_the_category_list(', '));
 }
Ejemplo n.º 8
0
 /**
  * Prints HTML with meta information for the current post (category, tags and permalink).
  *
  * @since Twenty Ten 1.0
  */
 function theme_posted_in()
 {
     // Retrieves tag list of current post, separated by commas.
     $tag_list = get_the_tag_list('', ', ');
     if ($tag_list) {
         $posted_in = __('This entry was posted in %1$s and tagged %2$s. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'wpdance');
     } elseif (is_object_in_taxonomy(get_post_type(), 'category')) {
         $posted_in = __('This entry was posted in %1$s. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'wpdance');
     } else {
         $posted_in = __('Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'wpdance');
     }
     // Prints the string, replacing the placeholders.
     printf($posted_in, get_the_category_list(', '), $tag_list, get_permalink(), the_title_attribute('echo=0'));
 }
Ejemplo n.º 9
0
/**
 * Prints HTML with meta information for the current post (category, tags and permalink).
 *
 * @since 1.0
 */
function teamtheme_posted_in()
{
    // Retrieves tag list of current post, separated by commas.
    $tag_list = get_the_tag_list('', ', ');
    if ($tag_list) {
        $posted_in = __('This entry was posted in %1$s and tagged %2$s. ', 'twentyten');
    } elseif (is_object_in_taxonomy(get_post_type(), 'category')) {
        $posted_in = __('This entry was posted in %1$s.', 'twentyten');
    } else {
        $posted_in = __('', 'twentyten');
    }
    // Prints the string, replacing the placeholders.
    printf($posted_in, get_the_category_list(', '), $tag_list, the_title_attribute('echo=0'));
}
 function wp_rest_api_add_taxonomies()
 {
     $post_types = get_post_types(array('public' => true), 'objects');
     foreach ($post_types as $post_type) {
         $show_in_rest = isset($post_type->show_in_rest) && $post_type->show_in_rest ? true : false;
         if ($show_in_rest) {
             $taxonomies = get_taxonomies(array(), "objects");
             foreach ($taxonomies as $taxonomy) {
                 if (is_object_in_taxonomy($post_type->name, $taxonomy->name)) {
                     register_api_field($post_type->name, $taxonomy->name, array('get_callback' => array($this, 'wp_rest_api_register_taxonomy'), 'schema' => null));
                 }
             }
         }
     }
 }
 /**
  * This filter registers the necessary query variables in WP_Query to detect whether we should filter by them.
  *
  * @since 0.6.1
  * @param array $vars array of original query vars
  * @return array the query vars array including the new ones
  */
 public function register_table_filter_query_vars($vars)
 {
     $table_columns = $this->component->table_columns;
     foreach ($table_columns as $column_slug => $column_args) {
         if (is_array($column_args) && $column_args['filterable']) {
             if (isset($column_args['taxonomy_slug']) && !empty($column_args['taxonomy_slug'])) {
                 if ('category' !== $column_args['taxonomy_slug'] && is_object_in_taxonomy($this->component->slug, $column_args['taxonomy_slug'])) {
                     $vars[] = $column_slug;
                 }
             } elseif (isset($column_args['meta_key']) && !empty($column_args['meta_key'])) {
                 $vars[] = $column_slug;
             }
         }
     }
     return $vars;
 }
Ejemplo n.º 12
0
 function tx_folio_term($taxonomy)
 {
     global $post;
     $folio_categories = array();
     $folio_cats = "";
     $tax_seperator = "";
     if (is_object_in_taxonomy($post->post_type, $taxonomy)) {
         foreach ((array) wp_get_post_terms($post->ID, $taxonomy) as $term) {
             if (empty($term->name)) {
                 continue;
             }
             $folio_cats .= $tax_seperator . $term->name;
             $tax_seperator = ', ';
         }
     }
     return $folio_cats;
 }
Ejemplo n.º 13
0
 function test_register_taxonomy_for_object_type()
 {
     global $wp_taxonomies;
     register_post_type('bar');
     register_taxonomy_for_object_type('post_tag', 'bar');
     $this->assertEquals(array('post_tag'), get_object_taxonomies('bar'));
     register_taxonomy_for_object_type('category', 'bar');
     $this->assertEquals(array('category', 'post_tag'), get_object_taxonomies('bar'));
     $this->assertTrue(is_object_in_taxonomy('bar', 'post_tag'));
     $this->assertTrue(is_object_in_taxonomy('bar', 'post_tag'));
     // Clean up. Remove the 'bar' post type from these taxonomies.
     $GLOBALS['wp_taxonomies']['post_tag']->object_type = array('post');
     $GLOBALS['wp_taxonomies']['category']->object_type = array('post');
     $this->assertFalse(is_object_in_taxonomy('bar', 'post_tag'));
     $this->assertFalse(is_object_in_taxonomy('bar', 'post_tag'));
     _unregister_post_type('bar');
 }
Ejemplo n.º 14
0
/**
 * Output dropdowns & filters
 *
 * @since 0.1.2
 */
function wp_event_calendar_add_dropdown_filters($post_type = '')
{
    // Bail if not the event post type
    if ('event' !== $post_type) {
        return;
    }
    // Bail if event type taxonomy was unregistered
    if (!is_object_in_taxonomy('event', 'event-type')) {
        return;
    }
    // Get registered taxonomies
    $taxonomies = get_object_taxonomies('event', 'objects');
    // Loop through query vars
    foreach ($taxonomies as $taxonomy) {
        // Is this taxonomy being queried?
        $selected = isset($_GET[$taxonomy->query_var]) ? sanitize_key($_GET[$taxonomy->query_var]) : '';
        // Output lable & dropdown
        echo '<label class="screen-reader-text" for="event-type">' . sprintf(__('Filter by %s', 'wp-event-calendar'), strtolower($taxonomy->labels->singular_name)) . '</label>';
        wp_dropdown_categories(array('show_option_none' => $taxonomy->labels->all_items, 'option_none_value' => 0, 'hide_empty' => true, 'hierarchical' => false, 'taxonomy' => $taxonomy->name, 'show_count' => 0, 'orderby' => 'name', 'name' => $taxonomy->query_var, 'selected' => $selected));
    }
}
Ejemplo n.º 15
0
function __wcb_post_single_meta($meta)
{
    if (get_post_type() != 'post' || !is_single()) {
        return $meta;
    }
    if (is_object_in_taxonomy(get_post_type(), 'category')) {
        $meta['category'] = sprintf(__('Posted in %s', 'wordcampbase'), get_the_category_list(', '));
    }
    if (is_object_in_taxonomy(get_post_type(), 'tag')) {
        $meta['tag'] = sprintf(__('Tagged %s', 'wordcampbase'), get_the_tag_list('', ', '));
    }
    $meta['order'][] = 'br';
    if (isset($meta['category']) && isset($meta['tag'])) {
        array_push($meta['order'], 'category', 'sep', 'tag');
    } elseif (isset($meta['category'])) {
        $meta['order'][] = 'category';
    } elseif (isset($meta['tag'])) {
        $meta['order'][] = 'tag';
    } else {
        array_pop($meta['order']);
    }
    return $meta;
}
/**
 * Retrieves the classes for the post div as an array.
 *
 * The class names are many. If the post is a sticky, then the 'sticky'
 * class name. The class 'hentry' is always added to each post. If the post has a
 * post thumbnail, 'has-post-thumbnail' is added as a class. For each taxonomy that
 * the post belongs to, a class will be added of the format '{$taxonomy}-{$slug}' -
 * eg 'category-foo' or 'my_custom_taxonomy-bar'.
 *
 * The 'post_tag' taxonomy is a special
 * case; the class has the 'tag-' prefix instead of 'post_tag-'. All classes are
 * passed through the filter, {@see 'post_class'}, with the list of classes, followed by
 * $class parameter value, with the post ID as the last parameter.
 *
 * @since 2.7.0
 * @since 4.2.0 Custom taxonomy classes were added.
 *
 * @param string|array $class   One or more classes to add to the class list.
 * @param int|WP_Post  $post_id Optional. Post ID or post object.
 * @return array Array of classes.
 */
function get_post_class($class = '', $post_id = null)
{
    $post = get_post($post_id);
    $classes = array();
    if ($class) {
        if (!is_array($class)) {
            $class = preg_split('#\\s+#', $class);
        }
        $classes = array_map('esc_attr', $class);
    } else {
        // Ensure that we always coerce class to being an array.
        $class = array();
    }
    if (!$post) {
        return $classes;
    }
    $classes[] = 'post-' . $post->ID;
    if (!is_admin()) {
        $classes[] = $post->post_type;
    }
    $classes[] = 'type-' . $post->post_type;
    $classes[] = 'status-' . $post->post_status;
    // Post Format
    if (post_type_supports($post->post_type, 'post-formats')) {
        $post_format = get_post_format($post->ID);
        if ($post_format && !is_wp_error($post_format)) {
            $classes[] = 'format-' . sanitize_html_class($post_format);
        } else {
            $classes[] = 'format-standard';
        }
    }
    $post_password_required = post_password_required($post->ID);
    // Post requires password.
    if ($post_password_required) {
        $classes[] = 'post-password-required';
    } elseif (!empty($post->post_password)) {
        $classes[] = 'post-password-protected';
    }
    // Post thumbnails.
    if (current_theme_supports('post-thumbnails') && has_post_thumbnail($post->ID) && !is_attachment($post) && !$post_password_required) {
        $classes[] = 'has-post-thumbnail';
    }
    // sticky for Sticky Posts
    if (is_sticky($post->ID)) {
        if (is_home() && !is_paged()) {
            $classes[] = 'sticky';
        } elseif (is_admin()) {
            $classes[] = 'status-sticky';
        }
    }
    // hentry for hAtom compliance
    $classes[] = 'hentry';
    // All public taxonomies
    $taxonomies = get_taxonomies(array('public' => true));
    foreach ((array) $taxonomies as $taxonomy) {
        if (is_object_in_taxonomy($post->post_type, $taxonomy)) {
            foreach ((array) get_the_terms($post->ID, $taxonomy) as $term) {
                if (empty($term->slug)) {
                    continue;
                }
                $term_class = sanitize_html_class($term->slug, $term->term_id);
                if (is_numeric($term_class) || !trim($term_class, '-')) {
                    $term_class = $term->term_id;
                }
                // 'post_tag' uses the 'tag' prefix for backward compatibility.
                if ('post_tag' == $taxonomy) {
                    $classes[] = 'tag-' . $term_class;
                } else {
                    $classes[] = sanitize_html_class($taxonomy . '-' . $term_class, $taxonomy . '-' . $term->term_id);
                }
            }
        }
    }
    $classes = array_map('esc_attr', $classes);
    /**
     * Filters the list of CSS classes for the current post.
     *
     * @since 2.7.0
     *
     * @param array $classes An array of post classes.
     * @param array $class   An array of additional classes added to the post.
     * @param int   $post_id The post ID.
     */
    $classes = apply_filters('post_class', $classes, $class, $post->ID);
    return array_unique($classes);
}
Ejemplo n.º 17
0
                    $default = '';
                }
                echo "<option{$default} value='" . esc_attr("{$arc_row->yyear}{$arc_row->mmonth}") . "'>";
                echo $wp_locale->get_month($arc_row->mmonth) . " {$arc_row->yyear}";
                echo "</option>\n";
            }
            ?>
                        </select>
                    <?php 
        }
        if (isset($_REQUEST["cat"]) && is_numeric($_REQUEST["cat"])) {
            $cat = intval($_REQUEST["cat"]);
        } else {
            $cat = 0;
        }
        if (is_object_in_taxonomy($post_type, 'category')) {
            $dropdown_options = array('show_option_all' => 'View all categories', 'hide_empty' => 0, 'hierarchical' => 1, 'show_count' => 0, 'orderby' => 'name', 'selected' => $cat);
            wp_dropdown_categories($dropdown_options);
        }
        $posts = get_posts(array("cat" => $cat, "m" => $m, "meta_query" => $meta_query, "numberposts" => $numberposts, "offset" => $offset, "post__not_in" => $ignored_posts));
        $all_posts = get_posts(array("cat" => $cat, "m" => $m, "meta_query" => $meta_query, "numberposts" => -1, "post__not_in" => $ignored_posts));
        ?>
                    <input type="submit" id="post-query-submit" value="<?php 
        esc_attr_e('Filter');
        ?>
" class="button-secondary" />

                    <select name="action">
                        <option value="none">Bulk Actions</option>
                        <option value="remove">Remove</option>
                        <option value="save">Save</option>
Ejemplo n.º 18
0
/**
 * Insert or update a post.
 *
 * If the $postarr parameter has 'ID' set to a value, then post will be updated.
 *
 * You can set the post date manually, by setting the values for 'post_date'
 * and 'post_date_gmt' keys. You can close the comments or open the comments by
 * setting the value for 'comment_status' key.
 *
 * @since 1.0.0
 * @since 4.2.0 Support was added for encoding emoji in the post title, content, and excerpt.
 * @since 4.4.0 A 'meta_input' array can now be passed to `$postarr` to add post meta data.
 *
 * @see sanitize_post()
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param array $postarr {
 *     An array of elements that make up a post to update or insert.
 *
 *     @type int    $ID                    The post ID. If equal to something other than 0,
 *                                         the post with that ID will be updated. Default 0.
 *     @type int    $post_author           The ID of the user who added the post. Default is
 *                                         the current user ID.
 *     @type string $post_date             The date of the post. Default is the current time.
 *     @type string $post_date_gmt         The date of the post in the GMT timezone. Default is
 *                                         the value of `$post_date`.
 *     @type mixed  $post_content          The post content. Default empty.
 *     @type string $post_content_filtered The filtered post content. Default empty.
 *     @type string $post_title            The post title. Default empty.
 *     @type string $post_excerpt          The post excerpt. Default empty.
 *     @type string $post_status           The post status. Default 'draft'.
 *     @type string $post_type             The post type. Default 'post'.
 *     @type string $comment_status        Whether the post can accept comments. Accepts 'open' or 'closed'.
 *                                         Default is the value of 'default_comment_status' option.
 *     @type string $ping_status           Whether the post can accept pings. Accepts 'open' or 'closed'.
 *                                         Default is the value of 'default_ping_status' option.
 *     @type string $post_password         The password to access the post. Default empty.
 *     @type string $post_name             The post name. Default is the sanitized post title.
 *     @type string $to_ping               Space or carriage return-separated list of URLs to ping.
 *                                         Default empty.
 *     @type string $pinged                Space or carriage return-separated list of URLs that have
 *                                         been pinged. Default empty.
 *     @type string $post_modified         The date when the post was last modified. Default is
 *                                         the current time.
 *     @type string $post_modified_gmt     The date when the post was last modified in the GMT
 *                                         timezone. Default is the current time.
 *     @type int    $post_parent           Set this for the post it belongs to, if any. Default 0.
 *     @type int    $menu_order            The order the post should be displayed in. Default 0.
 *     @type string $post_mime_type        The mime type of the post. Default empty.
 *     @type string $guid                  Global Unique ID for referencing the post. Default empty.
 *     @type array  $tax_input             Array of taxonomy terms keyed by their taxonomy name. Default empty.
 *     @type array  $meta_input            Array of post meta values keyed by their post meta key. Default empty.
 * }
 * @param bool  $wp_error Optional. Whether to allow return of WP_Error on failure. Default false.
 * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
 */
function wp_insert_post($postarr, $wp_error = false)
{
    global $wpdb;
    $user_id = get_current_user_id();
    $defaults = array('post_author' => $user_id, 'post_content' => '', 'post_content_filtered' => '', 'post_title' => '', 'post_excerpt' => '', 'post_status' => 'draft', 'post_type' => 'post', 'comment_status' => '', 'ping_status' => '', 'post_password' => '', 'to_ping' => '', 'pinged' => '', 'post_parent' => 0, 'menu_order' => 0, 'guid' => '', 'import_id' => 0, 'context' => '');
    $postarr = wp_parse_args($postarr, $defaults);
    unset($postarr['filter']);
    $postarr = sanitize_post($postarr, 'db');
    // Are we updating or creating?
    $post_ID = 0;
    $update = false;
    $guid = $postarr['guid'];
    if (!empty($postarr['ID'])) {
        $update = true;
        // Get the post ID and GUID.
        $post_ID = $postarr['ID'];
        $post_before = get_post($post_ID);
        if (is_null($post_before)) {
            if ($wp_error) {
                return new WP_Error('invalid_post', __('Invalid post ID.'));
            }
            return 0;
        }
        $guid = get_post_field('guid', $post_ID);
        $previous_status = get_post_field('post_status', $post_ID);
    } else {
        $previous_status = 'new';
    }
    $post_type = empty($postarr['post_type']) ? 'post' : $postarr['post_type'];
    $post_title = $postarr['post_title'];
    $post_content = $postarr['post_content'];
    $post_excerpt = $postarr['post_excerpt'];
    if (isset($postarr['post_name'])) {
        $post_name = $postarr['post_name'];
    }
    $maybe_empty = 'attachment' !== $post_type && !$post_content && !$post_title && !$post_excerpt && post_type_supports($post_type, 'editor') && post_type_supports($post_type, 'title') && post_type_supports($post_type, 'excerpt');
    /**
     * Filter whether the post should be considered "empty".
     *
     * The post is considered "empty" if both:
     * 1. The post type supports the title, editor, and excerpt fields
     * 2. The title, editor, and excerpt fields are all empty
     *
     * Returning a truthy value to the filter will effectively short-circuit
     * the new post being inserted, returning 0. If $wp_error is true, a WP_Error
     * will be returned instead.
     *
     * @since 3.3.0
     *
     * @param bool  $maybe_empty Whether the post should be considered "empty".
     * @param array $postarr     Array of post data.
     */
    if (apply_filters('wp_insert_post_empty_content', $maybe_empty, $postarr)) {
        if ($wp_error) {
            return new WP_Error('empty_content', __('Content, title, and excerpt are empty.'));
        } else {
            return 0;
        }
    }
    $post_status = empty($postarr['post_status']) ? 'draft' : $postarr['post_status'];
    if ('attachment' === $post_type && !in_array($post_status, array('inherit', 'private', 'trash'))) {
        $post_status = 'inherit';
    }
    if (!empty($postarr['post_category'])) {
        // Filter out empty terms.
        $post_category = array_filter($postarr['post_category']);
    }
    // Make sure we set a valid category.
    if (empty($post_category) || 0 == count($post_category) || !is_array($post_category)) {
        // 'post' requires at least one category.
        if ('post' == $post_type && 'auto-draft' != $post_status) {
            $post_category = array(get_option('default_category'));
        } else {
            $post_category = array();
        }
    }
    // Don't allow contributors to set the post slug for pending review posts.
    if ('pending' == $post_status && !current_user_can('publish_posts')) {
        $post_name = '';
    }
    /*
     * Create a valid post name. Drafts and pending posts are allowed to have
     * an empty post name.
     */
    if (empty($post_name)) {
        if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
            $post_name = sanitize_title($post_title);
        } else {
            $post_name = '';
        }
    } else {
        // On updates, we need to check to see if it's using the old, fixed sanitization context.
        $check_name = sanitize_title($post_name, '', 'old-save');
        if ($update && strtolower(urlencode($post_name)) == $check_name && get_post_field('post_name', $post_ID) == $check_name) {
            $post_name = $check_name;
        } else {
            // new post, or slug has changed.
            $post_name = sanitize_title($post_name);
        }
    }
    /*
     * If the post date is empty (due to having been new or a draft) and status
     * is not 'draft' or 'pending', set date to now.
     */
    if (empty($postarr['post_date']) || '0000-00-00 00:00:00' == $postarr['post_date']) {
        if (empty($postarr['post_date_gmt']) || '0000-00-00 00:00:00' == $postarr['post_date_gmt']) {
            $post_date = current_time('mysql');
        } else {
            $post_date = get_date_from_gmt($postarr['post_date_gmt']);
        }
    } else {
        $post_date = $postarr['post_date'];
    }
    // Validate the date.
    $mm = substr($post_date, 5, 2);
    $jj = substr($post_date, 8, 2);
    $aa = substr($post_date, 0, 4);
    $valid_date = wp_checkdate($mm, $jj, $aa, $post_date);
    if (!$valid_date) {
        if ($wp_error) {
            return new WP_Error('invalid_date', __('Whoops, the provided date is invalid.'));
        } else {
            return 0;
        }
    }
    if (empty($postarr['post_date_gmt']) || '0000-00-00 00:00:00' == $postarr['post_date_gmt']) {
        if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
            $post_date_gmt = get_gmt_from_date($post_date);
        } else {
            $post_date_gmt = '0000-00-00 00:00:00';
        }
    } else {
        $post_date_gmt = $postarr['post_date_gmt'];
    }
    if ($update || '0000-00-00 00:00:00' == $post_date) {
        $post_modified = current_time('mysql');
        $post_modified_gmt = current_time('mysql', 1);
    } else {
        $post_modified = $post_date;
        $post_modified_gmt = $post_date_gmt;
    }
    if ('attachment' !== $post_type) {
        if ('publish' == $post_status) {
            $now = gmdate('Y-m-d H:i:59');
            if (mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false)) {
                $post_status = 'future';
            }
        } elseif ('future' == $post_status) {
            $now = gmdate('Y-m-d H:i:59');
            if (mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false)) {
                $post_status = 'publish';
            }
        }
    }
    // Comment status.
    if (empty($postarr['comment_status'])) {
        if ($update) {
            $comment_status = 'closed';
        } else {
            $comment_status = get_default_comment_status($post_type);
        }
    } else {
        $comment_status = $postarr['comment_status'];
    }
    // These variables are needed by compact() later.
    $post_content_filtered = $postarr['post_content_filtered'];
    $post_author = isset($postarr['post_author']) ? $postarr['post_author'] : $user_id;
    $ping_status = empty($postarr['ping_status']) ? get_default_comment_status($post_type, 'pingback') : $postarr['ping_status'];
    $to_ping = isset($postarr['to_ping']) ? sanitize_trackback_urls($postarr['to_ping']) : '';
    $pinged = isset($postarr['pinged']) ? $postarr['pinged'] : '';
    $import_id = isset($postarr['import_id']) ? $postarr['import_id'] : 0;
    /*
     * The 'wp_insert_post_parent' filter expects all variables to be present.
     * Previously, these variables would have already been extracted
     */
    if (isset($postarr['menu_order'])) {
        $menu_order = (int) $postarr['menu_order'];
    } else {
        $menu_order = 0;
    }
    $post_password = isset($postarr['post_password']) ? $postarr['post_password'] : '';
    if ('private' == $post_status) {
        $post_password = '';
    }
    if (isset($postarr['post_parent'])) {
        $post_parent = (int) $postarr['post_parent'];
    } else {
        $post_parent = 0;
    }
    /**
     * Filter the post parent -- used to check for and prevent hierarchy loops.
     *
     * @since 3.1.0
     *
     * @param int   $post_parent Post parent ID.
     * @param int   $post_ID     Post ID.
     * @param array $new_postarr Array of parsed post data.
     * @param array $postarr     Array of sanitized, but otherwise unmodified post data.
     */
    $post_parent = apply_filters('wp_insert_post_parent', $post_parent, $post_ID, compact(array_keys($postarr)), $postarr);
    $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
    // Don't unslash.
    $post_mime_type = isset($postarr['post_mime_type']) ? $postarr['post_mime_type'] : '';
    // Expected_slashed (everything!).
    $data = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid');
    $emoji_fields = array('post_title', 'post_content', 'post_excerpt');
    foreach ($emoji_fields as $emoji_field) {
        if (isset($data[$emoji_field])) {
            $charset = $wpdb->get_col_charset($wpdb->posts, $emoji_field);
            if ('utf8' === $charset) {
                $data[$emoji_field] = wp_encode_emoji($data[$emoji_field]);
            }
        }
    }
    if ('attachment' === $post_type) {
        /**
         * Filter attachment post data before it is updated in or added to the database.
         *
         * @since 3.9.0
         *
         * @param array $data    An array of sanitized attachment post data.
         * @param array $postarr An array of unsanitized attachment post data.
         */
        $data = apply_filters('wp_insert_attachment_data', $data, $postarr);
    } else {
        /**
         * Filter slashed post data just before it is inserted into the database.
         *
         * @since 2.7.0
         *
         * @param array $data    An array of slashed post data.
         * @param array $postarr An array of sanitized, but otherwise unmodified post data.
         */
        $data = apply_filters('wp_insert_post_data', $data, $postarr);
    }
    $data = wp_unslash($data);
    $where = array('ID' => $post_ID);
    if ($update) {
        /**
         * Fires immediately before an existing post is updated in the database.
         *
         * @since 2.5.0
         *
         * @param int   $post_ID Post ID.
         * @param array $data    Array of unslashed post data.
         */
        do_action('pre_post_update', $post_ID, $data);
        if (false === $wpdb->update($wpdb->posts, $data, $where)) {
            if ($wp_error) {
                return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
            } else {
                return 0;
            }
        }
    } else {
        // If there is a suggested ID, use it if not already present.
        if (!empty($import_id)) {
            $import_id = (int) $import_id;
            if (!$wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE ID = %d", $import_id))) {
                $data['ID'] = $import_id;
            }
        }
        if (false === $wpdb->insert($wpdb->posts, $data)) {
            if ($wp_error) {
                return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
            } else {
                return 0;
            }
        }
        $post_ID = (int) $wpdb->insert_id;
        // Use the newly generated $post_ID.
        $where = array('ID' => $post_ID);
    }
    if (empty($data['post_name']) && !in_array($data['post_status'], array('draft', 'pending', 'auto-draft'))) {
        $data['post_name'] = wp_unique_post_slug(sanitize_title($data['post_title'], $post_ID), $post_ID, $data['post_status'], $post_type, $post_parent);
        $wpdb->update($wpdb->posts, array('post_name' => $data['post_name']), $where);
        clean_post_cache($post_ID);
    }
    if (is_object_in_taxonomy($post_type, 'category')) {
        wp_set_post_categories($post_ID, $post_category);
    }
    if (isset($postarr['tags_input']) && is_object_in_taxonomy($post_type, 'post_tag')) {
        wp_set_post_tags($post_ID, $postarr['tags_input']);
    }
    // New-style support for all custom taxonomies.
    if (!empty($postarr['tax_input'])) {
        foreach ($postarr['tax_input'] as $taxonomy => $tags) {
            $taxonomy_obj = get_taxonomy($taxonomy);
            if (!$taxonomy_obj) {
                /* translators: %s: taxonomy name */
                _doing_it_wrong(__FUNCTION__, sprintf(__('Invalid taxonomy: %s.'), $taxonomy), '4.4.0');
                continue;
            }
            // array = hierarchical, string = non-hierarchical.
            if (is_array($tags)) {
                $tags = array_filter($tags);
            }
            if (current_user_can($taxonomy_obj->cap->assign_terms)) {
                wp_set_post_terms($post_ID, $tags, $taxonomy);
            }
        }
    }
    if (!empty($postarr['meta_input'])) {
        foreach ($postarr['meta_input'] as $field => $value) {
            update_post_meta($post_ID, $field, $value);
        }
    }
    $current_guid = get_post_field('guid', $post_ID);
    // Set GUID.
    if (!$update && '' == $current_guid) {
        $wpdb->update($wpdb->posts, array('guid' => get_permalink($post_ID)), $where);
    }
    if ('attachment' === $postarr['post_type']) {
        if (!empty($postarr['file'])) {
            update_attached_file($post_ID, $postarr['file']);
        }
        if (!empty($postarr['context'])) {
            add_post_meta($post_ID, '_wp_attachment_context', $postarr['context'], true);
        }
    }
    clean_post_cache($post_ID);
    $post = get_post($post_ID);
    if (!empty($postarr['page_template']) && 'page' == $data['post_type']) {
        $post->page_template = $postarr['page_template'];
        $page_templates = wp_get_theme()->get_page_templates($post);
        if ('default' != $postarr['page_template'] && !isset($page_templates[$postarr['page_template']])) {
            if ($wp_error) {
                return new WP_Error('invalid_page_template', __('The page template is invalid.'));
            }
            update_post_meta($post_ID, '_wp_page_template', 'default');
        } else {
            update_post_meta($post_ID, '_wp_page_template', $postarr['page_template']);
        }
    }
    if ('attachment' !== $postarr['post_type']) {
        wp_transition_post_status($data['post_status'], $previous_status, $post);
    } else {
        if ($update) {
            /**
             * Fires once an existing attachment has been updated.
             *
             * @since 2.0.0
             *
             * @param int $post_ID Attachment ID.
             */
            do_action('edit_attachment', $post_ID);
            $post_after = get_post($post_ID);
            /**
             * Fires once an existing attachment has been updated.
             *
             * @since 4.4.0
             *
             * @param int     $post_ID      Post ID.
             * @param WP_Post $post_after   Post object following the update.
             * @param WP_Post $post_before  Post object before the update.
             */
            do_action('attachment_updated', $post_ID, $post_after, $post_before);
        } else {
            /**
             * Fires once an attachment has been added.
             *
             * @since 2.0.0
             *
             * @param int $post_ID Attachment ID.
             */
            do_action('add_attachment', $post_ID);
        }
        return $post_ID;
    }
    if ($update) {
        /**
         * Fires once an existing post has been updated.
         *
         * @since 1.2.0
         *
         * @param int     $post_ID Post ID.
         * @param WP_Post $post    Post object.
         */
        do_action('edit_post', $post_ID, $post);
        $post_after = get_post($post_ID);
        /**
         * Fires once an existing post has been updated.
         *
         * @since 3.0.0
         *
         * @param int     $post_ID      Post ID.
         * @param WP_Post $post_after   Post object following the update.
         * @param WP_Post $post_before  Post object before the update.
         */
        do_action('post_updated', $post_ID, $post_after, $post_before);
    }
    /**
     * Fires once a post has been saved.
     *
     * The dynamic portion of the hook name, `$post->post_type`, refers to
     * the post type slug.
     *
     * @since 3.7.0
     *
     * @param int     $post_ID Post ID.
     * @param WP_Post $post    Post object.
     * @param bool    $update  Whether this is an existing post being updated or not.
     */
    do_action("save_post_{$post->post_type}", $post_ID, $post, $update);
    /**
     * Fires once a post has been saved.
     *
     * @since 1.5.0
     *
     * @param int     $post_ID Post ID.
     * @param WP_Post $post    Post object.
     * @param bool    $update  Whether this is an existing post being updated or not.
     */
    do_action('save_post', $post_ID, $post, $update);
    /**
     * Fires once a post has been saved.
     *
     * @since 2.0.0
     *
     * @param int     $post_ID Post ID.
     * @param WP_Post $post    Post object.
     * @param bool    $update  Whether this is an existing post being updated or not.
     */
    do_action('wp_insert_post', $post_ID, $post, $update);
    return $post_ID;
}
    function extra_tablenav($which)
    {
        global $cat;
        ?>
		<div class="alignleft actions">
<?php 
        if ('top' == $which && !is_singular()) {
            $this->months_dropdown($this->screen->post_type);
            if (is_object_in_taxonomy($this->screen->post_type, 'category')) {
                $dropdown_options = array('show_option_all' => __('View all categories'), 'hide_empty' => 0, 'hierarchical' => 1, 'show_count' => 0, 'orderby' => 'name', 'selected' => $cat);
                wp_dropdown_categories($dropdown_options);
            }
            do_action('restrict_manage_posts');
            submit_button(__('Filter'), 'button', false, false, array('id' => 'post-query-submit'));
        }
        if ($this->is_trash && current_user_can(get_post_type_object($this->screen->post_type)->cap->edit_others_posts)) {
            submit_button(__('Empty Trash'), 'apply', 'delete_all', false);
        }
        ?>
		</div>
<?php 
    }
Ejemplo n.º 20
0
 /**
  * Getter.
  *
  * @param string $key Key to get.
  * @return array|mixed
  */
 public function __get($key)
 {
     if ('page_template' == $key && $this->__isset($key)) {
         return get_post_meta($this->ID, '_wp_page_template', true);
     }
     if ('post_category' == $key) {
         if (is_object_in_taxonomy($this->post_type, 'category')) {
             $terms = get_the_terms($this, 'category');
         }
         if (empty($terms)) {
             return array();
         }
         return wp_list_pluck($terms, 'term_id');
     }
     if ('tags_input' == $key) {
         if (is_object_in_taxonomy($this->post_type, 'post_tag')) {
             $terms = get_the_terms($this, 'post_tag');
         }
         if (empty($terms)) {
             return array();
         }
         return wp_list_pluck($terms, 'name');
     }
     // Rest of the values need filtering.
     if ('ancestors' == $key) {
         $value = get_post_ancestors($this);
     } else {
         $value = get_post_meta($this->ID, $key, true);
     }
     if ($this->filter) {
         $value = sanitize_post_field($key, $value, $this->ID, $this->filter);
     }
     return $value;
 }
Ejemplo n.º 21
0
/**
 * Retrieve the classes for the post div as an array.
 *
 * The class names are add are many. If the post is a sticky, then the 'sticky'
 * class name. The class 'hentry' is always added to each post. For each
 * category, the class will be added with 'category-' with category slug is
 * added. The tags are the same way as the categories with 'tag-' before the tag
 * slug. All classes are passed through the filter, 'post_class' with the list
 * of classes, followed by $class parameter value, with the post ID as the last
 * parameter.
 *
 * @since 2.7.0
 *
 * @param string|array $class One or more classes to add to the class list.
 * @param int $post_id An optional post ID.
 * @return array Array of classes.
 */
function get_post_class($class = '', $post_id = null)
{
    $post = get_post($post_id);
    $classes = array();
    if (empty($post)) {
        return $classes;
    }
    $classes[] = 'post-' . $post->ID;
    $classes[] = $post->post_type;
    $classes[] = 'type-' . $post->post_type;
    $classes[] = 'status-' . $post->post_status;
    // Post Format
    if (post_type_supports($post->post_type, 'post-formats')) {
        $post_format = get_post_format($post->ID);
        if ($post_format && !is_wp_error($post_format)) {
            $classes[] = 'format-' . sanitize_html_class($post_format);
        } else {
            $classes[] = 'format-standard';
        }
    }
    // post requires password
    if (post_password_required($post->ID)) {
        $classes[] = 'post-password-required';
    }
    // sticky for Sticky Posts
    if (is_sticky($post->ID) && is_home() && !is_paged()) {
        $classes[] = 'sticky';
    }
    // hentry for hAtom compliance
    $classes[] = 'hentry';
    // Categories
    if (is_object_in_taxonomy($post->post_type, 'category')) {
        foreach ((array) get_the_category($post->ID) as $cat) {
            if (empty($cat->slug)) {
                continue;
            }
            $classes[] = 'category-' . sanitize_html_class($cat->slug, $cat->term_id);
        }
    }
    // Tags
    if (is_object_in_taxonomy($post->post_type, 'post_tag')) {
        foreach ((array) get_the_tags($post->ID) as $tag) {
            if (empty($tag->slug)) {
                continue;
            }
            $classes[] = 'tag-' . sanitize_html_class($tag->slug, $tag->term_id);
        }
    }
    if (!empty($class)) {
        if (!is_array($class)) {
            $class = preg_split('#\\s+#', $class);
        }
        $classes = array_merge($classes, $class);
    }
    $classes = array_map('esc_attr', $classes);
    return apply_filters('post_class', $classes, $class, $post->ID);
}
/**
 * Retrieve category list in either HTML list or custom format.
 *
 * @since 1.5.1
 *
 * @global WP_Rewrite $wp_rewrite
 *
 * @param string $separator Optional, default is empty string. Separator for between the categories.
 * @param string $parents Optional. How to display the parents.
 * @param int $post_id Optional. Post ID to retrieve categories.
 * @return string
 */
function get_the_category_list($separator = '', $parents = '', $post_id = false)
{
    global $wp_rewrite;
    if (!is_object_in_taxonomy(get_post_type($post_id), 'category')) {
        /** This filter is documented in wp-includes/category-template.php */
        return apply_filters('the_category', '', $separator, $parents);
    }
    /**
     * Filters the categories before building the category list.
     *
     * @since 4.4.0
     *
     * @param array    $categories An array of the post's categories.
     * @param int|bool $post_id    ID of the post we're retrieving categories for. When `false`, we assume the
     *                             current post in the loop.
     */
    $categories = apply_filters('the_category_list', get_the_category($post_id), $post_id);
    if (empty($categories)) {
        /** This filter is documented in wp-includes/category-template.php */
        return apply_filters('the_category', __('Uncategorized'), $separator, $parents);
    }
    $rel = is_object($wp_rewrite) && $wp_rewrite->using_permalinks() ? 'rel="category tag"' : 'rel="category"';
    $thelist = '';
    if ('' == $separator) {
        $thelist .= '<ul class="post-categories">';
        foreach ($categories as $category) {
            $thelist .= "\n\t<li>";
            switch (strtolower($parents)) {
                case 'multiple':
                    if ($category->parent) {
                        $thelist .= get_category_parents($category->parent, true, $separator);
                    }
                    $thelist .= '<a href="' . esc_url(get_category_link($category->term_id)) . '" ' . $rel . '>' . $category->name . '</a></li>';
                    break;
                case 'single':
                    $thelist .= '<a href="' . esc_url(get_category_link($category->term_id)) . '"  ' . $rel . '>';
                    if ($category->parent) {
                        $thelist .= get_category_parents($category->parent, false, $separator);
                    }
                    $thelist .= $category->name . '</a></li>';
                    break;
                case '':
                default:
                    $thelist .= '<a href="' . esc_url(get_category_link($category->term_id)) . '" ' . $rel . '>' . $category->name . '</a></li>';
            }
        }
        $thelist .= '</ul>';
    } else {
        $i = 0;
        foreach ($categories as $category) {
            if (0 < $i) {
                $thelist .= $separator;
            }
            switch (strtolower($parents)) {
                case 'multiple':
                    if ($category->parent) {
                        $thelist .= get_category_parents($category->parent, true, $separator);
                    }
                    $thelist .= '<a href="' . esc_url(get_category_link($category->term_id)) . '" ' . $rel . '>' . $category->name . '</a>';
                    break;
                case 'single':
                    $thelist .= '<a href="' . esc_url(get_category_link($category->term_id)) . '" ' . $rel . '>';
                    if ($category->parent) {
                        $thelist .= get_category_parents($category->parent, false, $separator);
                    }
                    $thelist .= "{$category->name}</a>";
                    break;
                case '':
                default:
                    $thelist .= '<a href="' . esc_url(get_category_link($category->term_id)) . '" ' . $rel . '>' . $category->name . '</a>';
            }
            ++$i;
        }
    }
    /**
     * Filters the category or list of categories.
     *
     * @since 1.2.0
     *
     * @param string $thelist   List of categories for the current post.
     * @param string $separator Separator used between the categories.
     * @param string $parents   How to display the category parents. Accepts 'multiple',
     *                          'single', or empty.
     */
    return apply_filters('the_category', $thelist, $separator, $parents);
}
 function get_columns()
 {
     $screen = get_current_screen();
     if (empty($screen)) {
         $post_type = 'post';
     } else {
         $post_type = $screen->post_type;
     }
     $posts_columns = array();
     $posts_columns['cb'] = '<input type="checkbox" />';
     /* translators: manage posts column name */
     $posts_columns['title'] = _x('Title', 'column name');
     if (post_type_supports($post_type, 'author')) {
         $posts_columns['author'] = __('Author');
     }
     if (empty($post_type) || is_object_in_taxonomy($post_type, 'category')) {
         $posts_columns['categories'] = __('Categories');
     }
     if (empty($post_type) || is_object_in_taxonomy($post_type, 'post_tag')) {
         $posts_columns['tags'] = __('Tags');
     }
     $post_status = !empty($_REQUEST['post_status']) ? $_REQUEST['post_status'] : 'all';
     if (post_type_supports($post_type, 'comments') && !in_array($post_status, array('pending', 'draft', 'future'))) {
         $posts_columns['comments'] = '<span class="vers"><img alt="' . esc_attr__('Comments') . '" src="' . esc_url(admin_url('images/comment-grey-bubble.png')) . '" /></span>';
     }
     $posts_columns['date'] = __('Date');
     if ('page' == $post_type) {
         $posts_columns = apply_filters('manage_pages_columns', $posts_columns);
     } else {
         $posts_columns = apply_filters('manage_posts_columns', $posts_columns, $post_type);
     }
     $posts_columns = apply_filters("manage_{$post_type}_posts_columns", $posts_columns);
     return $posts_columns;
 }
function get_adjacent_post_product($in_same_cat = false, $excluded_categories = '', $previous = true)
{
    global $wpdb;
    if (!($post = get_post())) {
        return null;
    }
    $current_post_date = $post->post_date;
    $join = '';
    $posts_in_ex_cats_sql = '';
    if ($in_same_cat || !empty($excluded_categories)) {
        $join = " INNER JOIN {$wpdb->term_relationships} AS tr ON p.ID = tr.object_id INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id";
        if ($in_same_cat) {
            if (!is_object_in_taxonomy($post->post_type, 'product_cat')) {
                return '';
            }
            $cat_array = wp_get_object_terms($post->ID, 'product_cat', array('fields' => 'ids'));
            if (!$cat_array || is_wp_error($cat_array)) {
                return '';
            }
            $join .= " AND tt.taxonomy = 'product_cat' AND tt.term_id IN (" . implode(',', $cat_array) . ")";
        }
        $posts_in_ex_cats_sql = "AND tt.taxonomy = 'product_cat'";
        if (!empty($excluded_categories)) {
            if (!is_array($excluded_categories)) {
                // back-compat, $excluded_categories used to be IDs separated by " and "
                if (strpos($excluded_categories, ' and ') !== false) {
                    _deprecated_argument(__FUNCTION__, '3.3', sprintf(__('Use commas instead of %s to separate excluded categories.', 'commercegurus'), "'and'"));
                    $excluded_categories = explode(' and ', $excluded_categories);
                } else {
                    $excluded_categories = explode(',', $excluded_categories);
                }
            }
            $excluded_categories = array_map('intval', $excluded_categories);
            if (!empty($cat_array)) {
                $excluded_categories = array_diff($excluded_categories, $cat_array);
                $posts_in_ex_cats_sql = '';
            }
            if (!empty($excluded_categories)) {
                $posts_in_ex_cats_sql = " AND tt.taxonomy = 'product_cat' AND tt.term_id NOT IN (" . implode($excluded_categories, ',') . ')';
            }
        }
    }
    $adjacent = $previous ? 'previous' : 'next';
    $op = $previous ? '<' : '>';
    $order = $previous ? 'DESC' : 'ASC';
    $join = apply_filters("get_{$adjacent}_post_join", $join, $in_same_cat, $excluded_categories);
    $where = apply_filters("get_{$adjacent}_post_where", $wpdb->prepare("WHERE p.post_date {$op} %s AND p.post_type = %s AND p.post_status = 'publish' {$posts_in_ex_cats_sql}", $current_post_date, $post->post_type), $in_same_cat, $excluded_categories);
    $sort = apply_filters("get_{$adjacent}_post_sort", "ORDER BY p.post_date {$order} LIMIT 1");
    $query = "SELECT p.id FROM {$wpdb->posts} AS p {$join} {$where} {$sort}";
    $query_key = 'adjacent_post_' . md5($query);
    $result = wp_cache_get($query_key, 'counts');
    if (false !== $result) {
        if ($result) {
            $result = get_post($result);
        }
        return $result;
    }
    $result = $wpdb->get_var($query);
    if (null === $result) {
        $result = '';
    }
    wp_cache_set($query_key, $result, 'counts');
    if ($result) {
        $result = get_post($result);
    }
    return $result;
}
Ejemplo n.º 25
0
/**
 * Insert a post.
 *
 * If the $postarr parameter has 'ID' set to a value, then post will be updated.
 *
 * You can set the post date manually, but setting the values for 'post_date'
 * and 'post_date_gmt' keys. You can close the comments or open the comments by
 * setting the value for 'comment_status' key.
 *
 * The defaults for the parameter $postarr are:
 *     'post_status'   - Default is 'draft'.
 *     'post_type'     - Default is 'post'.
 *     'post_author'   - Default is current user ID ($user_ID). The ID of the user who added the post.
 *     'ping_status'   - Default is the value in 'default_ping_status' option.
 *                       Whether the attachment can accept pings.
 *     'post_parent'   - Default is 0. Set this for the post it belongs to, if any.
 *     'menu_order'    - Default is 0. The order it is displayed.
 *     'to_ping'       - Whether to ping.
 *     'pinged'        - Default is empty string.
 *     'post_password' - Default is empty string. The password to access the attachment.
 *     'guid'          - Global Unique ID for referencing the attachment.
 *     'post_content_filtered' - Post content filtered.
 *     'post_excerpt'  - Post excerpt.
 *
 * @since 1.0.0
 * @uses $wpdb
 * @uses $wp_rewrite
 * @uses $user_ID
 * @uses do_action() Calls 'pre_post_update' on post ID if this is an update.
 * @uses do_action() Calls 'edit_post' action on post ID and post data if this is an update.
 * @uses do_action() Calls 'save_post' and 'wp_insert_post' on post id and post data just before returning.
 * @uses apply_filters() Calls 'wp_insert_post_data' passing $data, $postarr prior to database update or insert.
 * @uses wp_transition_post_status()
 *
 * @param array $postarr Elements that make up post to insert.
 * @param bool $wp_error Optional. Allow return of WP_Error on failure.
 * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
 */
function wp_insert_post($postarr, $wp_error = false)
{
    global $wpdb, $wp_rewrite, $user_ID;
    $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'post_content' => '', 'post_title' => '');
    $postarr = wp_parse_args($postarr, $defaults);
    $postarr = sanitize_post($postarr, 'db');
    // export array as variables
    extract($postarr, EXTR_SKIP);
    // Are we updating or creating?
    $update = false;
    if (!empty($ID)) {
        $update = true;
        $previous_status = get_post_field('post_status', $ID);
    } else {
        $previous_status = 'new';
    }
    if ('' == $post_content && '' == $post_title && '' == $post_excerpt && 'attachment' != $post_type) {
        if ($wp_error) {
            return new WP_Error('empty_content', __('Content, title, and excerpt are empty.'));
        } else {
            return 0;
        }
    }
    if (empty($post_type)) {
        $post_type = 'post';
    }
    if (empty($post_status)) {
        $post_status = 'draft';
    }
    if (!empty($post_category)) {
        $post_category = array_filter($post_category);
    }
    // Filter out empty terms
    // Make sure we set a valid category.
    if (empty($post_category) || 0 == count($post_category) || !is_array($post_category)) {
        // 'post' requires at least one category.
        if ('post' == $post_type && 'auto-draft' != $post_status) {
            $post_category = array(get_option('default_category'));
        } else {
            $post_category = array();
        }
    }
    if (empty($post_author)) {
        $post_author = $user_ID;
    }
    $post_ID = 0;
    // Get the post ID and GUID
    if ($update) {
        $post_ID = (int) $ID;
        $guid = get_post_field('guid', $post_ID);
        $post_before = get_post($post_ID);
    }
    // Don't allow contributors to set to set the post slug for pending review posts
    if ('pending' == $post_status && !current_user_can('publish_posts')) {
        $post_name = '';
    }
    // Create a valid post name.  Drafts and pending posts are allowed to have an empty
    // post name.
    if (empty($post_name)) {
        if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
            $post_name = sanitize_title($post_title);
        } else {
            $post_name = '';
        }
    } else {
        $post_name = sanitize_title($post_name);
    }
    // If the post date is empty (due to having been new or a draft) and status is not 'draft' or 'pending', set date to now
    if (empty($post_date) || '0000-00-00 00:00:00' == $post_date) {
        $post_date = current_time('mysql');
    }
    if (empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt) {
        if (!in_array($post_status, array('draft', 'pending', 'auto-draft'))) {
            $post_date_gmt = get_gmt_from_date($post_date);
        } else {
            $post_date_gmt = '0000-00-00 00:00:00';
        }
    }
    if ($update || '0000-00-00 00:00:00' == $post_date) {
        $post_modified = current_time('mysql');
        $post_modified_gmt = current_time('mysql', 1);
    } else {
        $post_modified = $post_date;
        $post_modified_gmt = $post_date_gmt;
    }
    if ('publish' == $post_status) {
        $now = gmdate('Y-m-d H:i:59');
        if (mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false)) {
            $post_status = 'future';
        }
    } elseif ('future' == $post_status) {
        $now = gmdate('Y-m-d H:i:59');
        if (mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false)) {
            $post_status = 'publish';
        }
    }
    if (empty($comment_status)) {
        if ($update) {
            $comment_status = 'closed';
        } else {
            $comment_status = get_option('default_comment_status');
        }
    }
    if (empty($ping_status)) {
        $ping_status = get_option('default_ping_status');
    }
    if (isset($to_ping)) {
        $to_ping = preg_replace('|\\s+|', "\n", $to_ping);
    } else {
        $to_ping = '';
    }
    if (!isset($pinged)) {
        $pinged = '';
    }
    if (isset($post_parent)) {
        $post_parent = (int) $post_parent;
    } else {
        $post_parent = 0;
    }
    // Check the post_parent to see if it will cause a hierarchy loop
    $post_parent = apply_filters('wp_insert_post_parent', $post_parent, $post_ID, compact(array_keys($postarr)), $postarr);
    if (isset($menu_order)) {
        $menu_order = (int) $menu_order;
    } else {
        $menu_order = 0;
    }
    if (!isset($post_password) || 'private' == $post_status) {
        $post_password = '';
    }
    $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
    // expected_slashed (everything!)
    $data = compact(array('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'guid'));
    $data = apply_filters('wp_insert_post_data', $data, $postarr);
    $data = stripslashes_deep($data);
    $where = array('ID' => $post_ID);
    if ($update) {
        do_action('pre_post_update', $post_ID);
        if (false === $wpdb->update($wpdb->posts, $data, $where)) {
            if ($wp_error) {
                return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
            } else {
                return 0;
            }
        }
    } else {
        if (isset($post_mime_type)) {
            $data['post_mime_type'] = stripslashes($post_mime_type);
        }
        // This isn't in the update
        // If there is a suggested ID, use it if not already present
        if (!empty($import_id)) {
            $import_id = (int) $import_id;
            if (!$wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE ID = %d", $import_id))) {
                $data['ID'] = $import_id;
            }
        }
        if (false === $wpdb->insert($wpdb->posts, $data)) {
            if ($wp_error) {
                return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
            } else {
                return 0;
            }
        }
        $post_ID = (int) $wpdb->insert_id;
        // use the newly generated $post_ID
        $where = array('ID' => $post_ID);
    }
    if (empty($data['post_name']) && !in_array($data['post_status'], array('draft', 'pending', 'auto-draft'))) {
        $data['post_name'] = sanitize_title($data['post_title'], $post_ID);
        $wpdb->update($wpdb->posts, array('post_name' => $data['post_name']), $where);
    }
    if (is_object_in_taxonomy($post_type, 'category')) {
        wp_set_post_categories($post_ID, $post_category);
    }
    if (isset($tags_input) && is_object_in_taxonomy($post_type, 'post_tag')) {
        wp_set_post_tags($post_ID, $tags_input);
    }
    // new-style support for all custom taxonomies
    if (!empty($tax_input)) {
        foreach ($tax_input as $taxonomy => $tags) {
            $taxonomy_obj = get_taxonomy($taxonomy);
            if (is_array($tags)) {
                // array = hierarchical, string = non-hierarchical.
                $tags = array_filter($tags);
            }
            if (current_user_can($taxonomy_obj->cap->assign_terms)) {
                wp_set_post_terms($post_ID, $tags, $taxonomy);
            }
        }
    }
    $current_guid = get_post_field('guid', $post_ID);
    if ('page' == $data['post_type']) {
        clean_page_cache($post_ID);
    } else {
        clean_post_cache($post_ID);
    }
    // Set GUID
    if (!$update && '' == $current_guid) {
        $wpdb->update($wpdb->posts, array('guid' => get_permalink($post_ID)), $where);
    }
    $post = get_post($post_ID);
    if (!empty($page_template) && 'page' == $data['post_type']) {
        $post->page_template = $page_template;
        $page_templates = get_page_templates();
        if ('default' != $page_template && !in_array($page_template, $page_templates)) {
            if ($wp_error) {
                return new WP_Error('invalid_page_template', __('The page template is invalid.'));
            } else {
                return 0;
            }
        }
        update_post_meta($post_ID, '_wp_page_template', $page_template);
    }
    wp_transition_post_status($data['post_status'], $previous_status, $post);
    if ($update) {
        do_action('edit_post', $post_ID, $post);
        $post_after = get_post($post_ID);
        do_action('post_updated', $post_ID, $post_after, $post_before);
    }
    do_action('save_post', $post_ID, $post);
    do_action('wp_insert_post', $post_ID, $post);
    return $post_ID;
}
Ejemplo n.º 26
0
 /**
  * Prepares page data for return in an XML-RPC object.
  *
  * @access protected
  *
  * @param object $page The unprepared page data
  * @return array The prepared page data
  */
 protected function _prepare_page($page)
 {
     // Get all of the page content and link.
     $full_page = get_extended($page->post_content);
     $link = post_permalink($page->ID);
     // Get info the page parent if there is one.
     $parent_title = "";
     if (!empty($page->post_parent)) {
         $parent = get_post($page->post_parent);
         $parent_title = $parent->post_title;
     }
     // Determine comment and ping settings.
     $allow_comments = comments_open($page->ID) ? 1 : 0;
     $allow_pings = pings_open($page->ID) ? 1 : 0;
     // Format page date.
     $page_date = $this->_convert_date($page->post_date);
     $page_date_gmt = $this->_convert_date_gmt($page->post_date_gmt, $page->post_date);
     // Pull the categories info together.
     $categories = array();
     if (is_object_in_taxonomy('page', 'category')) {
         foreach (wp_get_post_categories($page->ID) as $cat_id) {
             $categories[] = get_cat_name($cat_id);
         }
     }
     // Get the author info.
     $author = get_userdata($page->post_author);
     $page_template = get_page_template_slug($page->ID);
     if (empty($page_template)) {
         $page_template = 'default';
     }
     $_page = array('dateCreated' => $page_date, 'userid' => $page->post_author, 'page_id' => $page->ID, 'page_status' => $page->post_status, 'description' => $full_page['main'], 'title' => $page->post_title, 'link' => $link, 'permaLink' => $link, 'categories' => $categories, 'excerpt' => $page->post_excerpt, 'text_more' => $full_page['extended'], 'mt_allow_comments' => $allow_comments, 'mt_allow_pings' => $allow_pings, 'wp_slug' => $page->post_name, 'wp_password' => $page->post_password, 'wp_author' => $author->display_name, 'wp_page_parent_id' => $page->post_parent, 'wp_page_parent_title' => $parent_title, 'wp_page_order' => $page->menu_order, 'wp_author_id' => (string) $author->ID, 'wp_author_display_name' => $author->display_name, 'date_created_gmt' => $page_date_gmt, 'custom_fields' => $this->get_custom_fields($page->ID), 'wp_page_template' => $page_template);
     /**
      * Filter XML-RPC-prepared data for the given page.
      *
      * @since 3.4.0
      *
      * @param array   $_page An array of page data.
      * @param WP_Post $page  Page object.
      */
     return apply_filters('xmlrpc_prepare_page', $_page, $page);
 }
Ejemplo n.º 27
0
    /**
     * @global int $cat
     * @param string $which
     */
    protected function extra_tablenav($which)
    {
        global $cat;
        ?>
		<div class="alignleft actions">
<?php 
        if ('top' == $which && !is_singular()) {
            $this->months_dropdown($this->screen->post_type);
            if (is_object_in_taxonomy($this->screen->post_type, 'category')) {
                $dropdown_options = array('show_option_all' => __('All categories'), 'hide_empty' => 0, 'hierarchical' => 1, 'show_count' => 0, 'orderby' => 'name', 'selected' => $cat);
                echo '<label class="screen-reader-text" for="cat">' . __('Filter by category') . '</label>';
                wp_dropdown_categories($dropdown_options);
            }
            /**
             * Fires before the Filter button on the Posts and Pages list tables.
             *
             * The Filter button allows sorting by date and/or category on the
             * Posts list table, and sorting by date on the Pages list table.
             *
             * @since 2.1.0
             * @since 4.4.0 The `$post_type` parameter was added.
             *
             * @param string $post_type The post type slug.
             */
            do_action('restrict_manage_posts', $this->screen->post_type);
            submit_button(__('Filter'), 'button', 'filter_action', false, array('id' => 'post-query-submit'));
        }
        if ($this->is_trash && current_user_can(get_post_type_object($this->screen->post_type)->cap->edit_others_posts)) {
            submit_button(__('Empty Trash'), 'apply', 'delete_all', false);
        }
        ?>
		</div>
<?php 
    }
Ejemplo n.º 28
0
/**
 * Retrieve adjacent post.
 *
 * Can either be next or previous post.
 *
 * @since 2.5.0
 *
 * @param bool         $in_same_term   Optional. Whether post should be in a same taxonomy term.
 * @param array|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs.
 * @param bool         $previous       Optional. Whether to retrieve previous post.
 * @param string       $taxonomy       Optional. Taxonomy, if $in_same_term is true. Default 'category'.
 * @return mixed       Post object if successful. Null if global $post is not set. Empty string if no corresponding post exists.
 */
function get_adjacent_post($in_same_term = false, $excluded_terms = '', $previous = true, $taxonomy = 'category')
{
    global $wpdb;
    if (!($post = get_post()) || !taxonomy_exists($taxonomy)) {
        return null;
    }
    $current_post_date = $post->post_date;
    $join = '';
    $posts_in_ex_terms_sql = '';
    if ($in_same_term || !empty($excluded_terms)) {
        $join = " INNER JOIN {$wpdb->term_relationships} AS tr ON p.ID = tr.object_id INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id";
        if ($in_same_term) {
            if (!is_object_in_taxonomy($post->post_type, $taxonomy)) {
                return '';
            }
            $term_array = wp_get_object_terms($post->ID, $taxonomy, array('fields' => 'ids'));
            if (!$term_array || is_wp_error($term_array)) {
                return '';
            }
            $join .= $wpdb->prepare(" AND tt.taxonomy = %s AND tt.term_id IN (" . implode(',', array_map('intval', $term_array)) . ")", $taxonomy);
        }
        $posts_in_ex_terms_sql = $wpdb->prepare("AND tt.taxonomy = %s", $taxonomy);
        if (!empty($excluded_terms)) {
            if (!is_array($excluded_terms)) {
                // back-compat, $excluded_terms used to be $excluded_terms with IDs separated by " and "
                if (false !== strpos($excluded_terms, ' and ')) {
                    _deprecated_argument(__FUNCTION__, '3.3', sprintf(__('Use commas instead of %s to separate excluded terms.'), "'and'"));
                    $excluded_terms = explode(' and ', $excluded_terms);
                } else {
                    $excluded_terms = explode(',', $excluded_terms);
                }
            }
            $excluded_terms = array_map('intval', $excluded_terms);
            if (!empty($term_array)) {
                $excluded_terms = array_diff($excluded_terms, $term_array);
                $posts_in_ex_terms_sql = '';
            }
            if (!empty($excluded_terms)) {
                $posts_in_ex_terms_sql = $wpdb->prepare(" AND tt.taxonomy = %s AND tt.term_id NOT IN (" . implode($excluded_terms, ',') . ')', $taxonomy);
            }
        }
    }
    $adjacent = $previous ? 'previous' : 'next';
    $op = $previous ? '<' : '>';
    $order = $previous ? 'DESC' : 'ASC';
    /**
     * Filter the JOIN clause in the SQL for an adjacent post query.
     *
     * The dynamic portion of the hook name, $adjacent, refers to the type
     * of adjacency, 'next' or 'previous'.
     *
     * @since 2.5.0
     *
     * @param string $join           The JOIN clause in the SQL.
     * @param bool   $in_same_term   Whether post should be in a same taxonomy term.
     * @param array  $excluded_terms Array of excluded term IDs.
     */
    $join = apply_filters("get_{$adjacent}_post_join", $join, $in_same_term, $excluded_terms);
    /**
     * Filter the WHERE clause in the SQL for an adjacent post query.
     *
     * The dynamic portion of the hook name, $adjacent, refers to the type
     * of adjacency, 'next' or 'previous'.
     *
     * @since 2.5.0
     *
     * @param string $where          The WHERE clause in the SQL.
     * @param bool   $in_same_term   Whether post should be in a same taxonomy term.
     * @param array  $excluded_terms Array of excluded term IDs.
     */
    $where = apply_filters("get_{$adjacent}_post_where", $wpdb->prepare("WHERE p.post_date {$op} %s AND p.post_type = %s AND p.post_status = 'publish' {$posts_in_ex_terms_sql}", $current_post_date, $post->post_type), $in_same_term, $excluded_terms);
    /**
     * Filter the ORDER BY clause in the SQL for an adjacent post query.
     *
     * The dynamic portion of the hook name, $adjacent, refers to the type
     * of adjacency, 'next' or 'previous'.
     *
     * @since 2.5.0
     *
     * @param string $order_by The ORDER BY clause in the SQL.
     */
    $sort = apply_filters("get_{$adjacent}_post_sort", "ORDER BY p.post_date {$order} LIMIT 1");
    $query = "SELECT p.ID FROM {$wpdb->posts} AS p {$join} {$where} {$sort}";
    $query_key = 'adjacent_post_' . md5($query);
    $result = wp_cache_get($query_key, 'counts');
    if (false !== $result) {
        if ($result) {
            $result = get_post($result);
        }
        return $result;
    }
    $result = $wpdb->get_var($query);
    if (null === $result) {
        $result = '';
    }
    wp_cache_set($query_key, $result, 'counts');
    if ($result) {
        $result = get_post($result);
    }
    return $result;
}
Ejemplo n.º 29
0
/**
 * Retrieve adjacent post.
 *
 * Can either be next or previous post.
 *
 * @since 2.5.0
 *
 * @global wpdb $wpdb
 *
 * @param bool         $in_same_term   Optional. Whether post should be in a same taxonomy term.
 * @param array|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs.
 * @param bool         $previous       Optional. Whether to retrieve previous post.
 * @param string       $taxonomy       Optional. Taxonomy, if $in_same_term is true. Default 'category'.
 * @return null|string|WP_Post Post object if successful. Null if global $post is not set. Empty string if no corresponding post exists.
 */
function get_adjacent_post($in_same_term = false, $excluded_terms = '', $previous = true, $taxonomy = 'category')
{
    global $wpdb;
    if (!($post = get_post()) || !taxonomy_exists($taxonomy)) {
        return null;
    }
    $current_post_date = $post->post_date;
    $join = '';
    $where = '';
    if ($in_same_term || !empty($excluded_terms)) {
        $join = " INNER JOIN {$wpdb->term_relationships} AS tr ON p.ID = tr.object_id INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id";
        $where = $wpdb->prepare("AND tt.taxonomy = %s", $taxonomy);
        if (!empty($excluded_terms) && !is_array($excluded_terms)) {
            // back-compat, $excluded_terms used to be $excluded_terms with IDs separated by " and "
            if (false !== strpos($excluded_terms, ' and ')) {
                _deprecated_argument(__FUNCTION__, '3.3', sprintf(__('Use commas instead of %s to separate excluded terms.'), "'and'"));
                $excluded_terms = explode(' and ', $excluded_terms);
            } else {
                $excluded_terms = explode(',', $excluded_terms);
            }
            $excluded_terms = array_map('intval', $excluded_terms);
        }
        if ($in_same_term) {
            if (!is_object_in_taxonomy($post->post_type, $taxonomy)) {
                return '';
            }
            $term_array = wp_get_object_terms($post->ID, $taxonomy, array('fields' => 'ids'));
            // Remove any exclusions from the term array to include.
            $term_array = array_diff($term_array, (array) $excluded_terms);
            $term_array = array_map('intval', $term_array);
            if (!$term_array || is_wp_error($term_array)) {
                return '';
            }
            $where .= " AND tt.term_id IN (" . implode(',', $term_array) . ")";
        }
        if (!empty($excluded_terms)) {
            $where .= " AND p.ID NOT IN ( SELECT tr.object_id FROM {$wpdb->term_relationships} tr LEFT JOIN {$wpdb->term_taxonomy} tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id) WHERE tt.term_id IN (" . implode($excluded_terms, ',') . ') )';
        }
    }
    // 'post_status' clause depends on the current user.
    if (is_user_logged_in()) {
        $user_id = get_current_user_id();
        $post_type_object = get_post_type_object($post->post_type);
        if (empty($post_type_object)) {
            $post_type_cap = $post->post_type;
            $read_private_cap = 'read_private_' . $post_type_cap . 's';
        } else {
            $read_private_cap = $post_type_object->cap->read_private_posts;
        }
        /*
         * Results should include private posts belonging to the current user, or private posts where the
         * current user has the 'read_private_posts' cap.
         */
        $private_states = get_post_stati(array('private' => true));
        $where .= " AND ( p.post_status = 'publish'";
        foreach ((array) $private_states as $state) {
            if (current_user_can($read_private_cap)) {
                $where .= $wpdb->prepare(" OR p.post_status = %s", $state);
            } else {
                $where .= $wpdb->prepare(" OR (p.post_author = %d AND p.post_status = %s)", $user_id, $state);
            }
        }
        $where .= " )";
    } else {
        $where .= " AND p.post_status = 'publish'";
    }
    $adjacent = $previous ? 'previous' : 'next';
    $op = $previous ? '<' : '>';
    $order = $previous ? 'DESC' : 'ASC';
    /**
     * Filter the JOIN clause in the SQL for an adjacent post query.
     *
     * The dynamic portion of the hook name, `$adjacent`, refers to the type
     * of adjacency, 'next' or 'previous'.
     *
     * @since 2.5.0
     *
     * @param string $join           The JOIN clause in the SQL.
     * @param bool   $in_same_term   Whether post should be in a same taxonomy term.
     * @param array  $excluded_terms Array of excluded term IDs.
     */
    $join = apply_filters("get_{$adjacent}_post_join", $join, $in_same_term, $excluded_terms);
    /**
     * Filter the WHERE clause in the SQL for an adjacent post query.
     *
     * The dynamic portion of the hook name, `$adjacent`, refers to the type
     * of adjacency, 'next' or 'previous'.
     *
     * @since 2.5.0
     *
     * @param string $where          The `WHERE` clause in the SQL.
     * @param bool   $in_same_term   Whether post should be in a same taxonomy term.
     * @param array  $excluded_terms Array of excluded term IDs.
     */
    $where = apply_filters("get_{$adjacent}_post_where", $wpdb->prepare("WHERE p.post_date {$op} %s AND p.post_type = %s {$where}", $current_post_date, $post->post_type), $in_same_term, $excluded_terms);
    /**
     * Filter the ORDER BY clause in the SQL for an adjacent post query.
     *
     * The dynamic portion of the hook name, `$adjacent`, refers to the type
     * of adjacency, 'next' or 'previous'.
     *
     * @since 2.5.0
     *
     * @param string $order_by The `ORDER BY` clause in the SQL.
     */
    $sort = apply_filters("get_{$adjacent}_post_sort", "ORDER BY p.post_date {$order} LIMIT 1");
    $query = "SELECT p.ID FROM {$wpdb->posts} AS p {$join} {$where} {$sort}";
    $query_key = 'adjacent_post_' . md5($query);
    $result = wp_cache_get($query_key, 'counts');
    if (false !== $result) {
        if ($result) {
            $result = get_post($result);
        }
        return $result;
    }
    $result = $wpdb->get_var($query);
    if (null === $result) {
        $result = '';
    }
    wp_cache_set($query_key, $result, 'counts');
    if ($result) {
        $result = get_post($result);
    }
    return $result;
}
Ejemplo n.º 30
0
 /**
  * Fetches a screen object.
  *
  * @since 3.3.0
  * @access public
  *
  * @param string $hook_name Optional. The hook name (also known as the hook suffix) used to determine the screen.
  * 	Defaults to the current $hook_suffix global.
  * @return WP_Screen Screen object.
  */
 public static function get($hook_name = '')
 {
     if (is_a($hook_name, 'WP_Screen')) {
         return $hook_name;
     }
     $post_type = $taxonomy = null;
     $in_admin = false;
     $action = '';
     if ($hook_name) {
         $id = $hook_name;
     } else {
         $id = $GLOBALS['hook_suffix'];
     }
     // For those pesky meta boxes.
     if ($hook_name && post_type_exists($hook_name)) {
         $post_type = $id;
         $id = 'post';
         // changes later. ends up being $base.
     } else {
         if ('.php' == substr($id, -4)) {
             $id = substr($id, 0, -4);
         }
         if ('post-new' == $id || 'link-add' == $id || 'media-new' == $id || 'user-new' == $id) {
             $id = substr($id, 0, -4);
             $action = 'add';
         }
     }
     if (!$post_type && $hook_name) {
         if ('-network' == substr($id, -8)) {
             $id = substr($id, 0, -8);
             $in_admin = 'network';
         } elseif ('-user' == substr($id, -5)) {
             $id = substr($id, 0, -5);
             $in_admin = 'user';
         }
         $id = sanitize_key($id);
         if ('edit-comments' != $id && 'edit-tags' != $id && 'edit-' == substr($id, 0, 5)) {
             $maybe = substr($id, 5);
             if (taxonomy_exists($maybe)) {
                 $id = 'edit-tags';
                 $taxonomy = $maybe;
             } elseif (post_type_exists($maybe)) {
                 $id = 'edit';
                 $post_type = $maybe;
             }
         }
         if (!$in_admin) {
             $in_admin = 'site';
         }
     } else {
         if (defined('WP_NETWORK_ADMIN') && WP_NETWORK_ADMIN) {
             $in_admin = 'network';
         } elseif (defined('WP_USER_ADMIN') && WP_USER_ADMIN) {
             $in_admin = 'user';
         } else {
             $in_admin = 'site';
         }
     }
     if ('index' == $id) {
         $id = 'dashboard';
     } elseif ('front' == $id) {
         $in_admin = false;
     }
     $base = $id;
     // If this is the current screen, see if we can be more accurate for post types and taxonomies.
     if (!$hook_name) {
         if (isset($_REQUEST['post_type'])) {
             $post_type = post_type_exists($_REQUEST['post_type']) ? $_REQUEST['post_type'] : false;
         }
         if (isset($_REQUEST['taxonomy'])) {
             $taxonomy = taxonomy_exists($_REQUEST['taxonomy']) ? $_REQUEST['taxonomy'] : false;
         }
         switch ($base) {
             case 'post':
                 if (isset($_GET['post'])) {
                     $post_id = (int) $_GET['post'];
                 } elseif (isset($_POST['post_ID'])) {
                     $post_id = (int) $_POST['post_ID'];
                 } else {
                     $post_id = 0;
                 }
                 if ($post_id) {
                     $post = get_post($post_id);
                     if ($post) {
                         $post_type = $post->post_type;
                     }
                 }
                 break;
             case 'edit-tags':
                 if (null === $post_type && is_object_in_taxonomy('post', $taxonomy ? $taxonomy : 'post_tag')) {
                     $post_type = 'post';
                 }
                 break;
         }
     }
     switch ($base) {
         case 'post':
             if (null === $post_type) {
                 $post_type = 'post';
             }
             $id = $post_type;
             break;
         case 'edit':
             if (null === $post_type) {
                 $post_type = 'post';
             }
             $id .= '-' . $post_type;
             break;
         case 'edit-tags':
             if (null === $taxonomy) {
                 $taxonomy = 'post_tag';
             }
             // The edit-tags ID does not contain the post type. Look for it in the request.
             if (null === $post_type) {
                 $post_type = 'post';
                 if (isset($_REQUEST['post_type']) && post_type_exists($_REQUEST['post_type'])) {
                     $post_type = $_REQUEST['post_type'];
                 }
             }
             $id = 'edit-' . $taxonomy;
             break;
     }
     if ('network' == $in_admin) {
         $id .= '-network';
         $base .= '-network';
     } elseif ('user' == $in_admin) {
         $id .= '-user';
         $base .= '-user';
     }
     if (isset(self::$_registry[$id])) {
         $screen = self::$_registry[$id];
         if ($screen === get_current_screen()) {
             return $screen;
         }
     } else {
         $screen = new WP_Screen();
         $screen->id = $id;
     }
     $screen->base = $base;
     $screen->action = $action;
     $screen->post_type = (string) $post_type;
     $screen->taxonomy = (string) $taxonomy;
     $screen->is_user = '******' == $in_admin;
     $screen->is_network = 'network' == $in_admin;
     $screen->in_admin = $in_admin;
     self::$_registry[$id] = $screen;
     return $screen;
 }