wp/wp-content/themes/twentyfourteen/inc/featured-content.php
changeset 5 5e2f62d02dcd
child 7 cf61fcea0001
equal deleted inserted replaced
4:346c88efed21 5:5e2f62d02dcd
       
     1 <?php
       
     2 /**
       
     3  * Twenty Fourteen Featured Content
       
     4  *
       
     5  * This module allows you to define a subset of posts to be displayed
       
     6  * in the theme's Featured Content area.
       
     7  *
       
     8  * For maximum compatibility with different methods of posting users
       
     9  * will designate a featured post tag to associate posts with. Since
       
    10  * this tag now has special meaning beyond that of a normal tags, users
       
    11  * will have the ability to hide it from the front-end of their site.
       
    12  */
       
    13 class Featured_Content {
       
    14 
       
    15 	/**
       
    16 	 * The maximum number of posts a Featured Content area can contain.
       
    17 	 *
       
    18 	 * We define a default value here but themes can override
       
    19 	 * this by defining a "max_posts" entry in the second parameter
       
    20 	 * passed in the call to add_theme_support( 'featured-content' ).
       
    21 	 *
       
    22 	 * @see Featured_Content::init()
       
    23 	 *
       
    24 	 * @since Twenty Fourteen 1.0
       
    25 	 *
       
    26 	 * @static
       
    27 	 * @access public
       
    28 	 * @var int
       
    29 	 */
       
    30 	public static $max_posts = 15;
       
    31 
       
    32 	/**
       
    33 	 * Instantiate.
       
    34 	 *
       
    35 	 * All custom functionality will be hooked into the "init" action.
       
    36 	 *
       
    37 	 * @static
       
    38 	 * @access public
       
    39 	 * @since Twenty Fourteen 1.0
       
    40 	 */
       
    41 	public static function setup() {
       
    42 		add_action( 'init', array( __CLASS__, 'init' ), 30 );
       
    43 	}
       
    44 
       
    45 	/**
       
    46 	 * Conditionally hook into WordPress.
       
    47 	 *
       
    48 	 * Theme must declare that they support this module by adding
       
    49 	 * add_theme_support( 'featured-content' ); during after_setup_theme.
       
    50 	 *
       
    51 	 * If no theme support is found there is no need to hook into WordPress.
       
    52 	 * We'll just return early instead.
       
    53 	 *
       
    54 	 * @static
       
    55 	 * @access public
       
    56 	 * @since Twenty Fourteen 1.0
       
    57 	 */
       
    58 	public static function init() {
       
    59 		$theme_support = get_theme_support( 'featured-content' );
       
    60 
       
    61 		// Return early if theme does not support Featured Content.
       
    62 		if ( ! $theme_support ) {
       
    63 			return;
       
    64 		}
       
    65 
       
    66 		/*
       
    67 		 * An array of named arguments must be passed as the second parameter
       
    68 		 * of add_theme_support().
       
    69 		 */
       
    70 		if ( ! isset( $theme_support[0] ) ) {
       
    71 			return;
       
    72 		}
       
    73 
       
    74 		// Return early if "featured_content_filter" has not been defined.
       
    75 		if ( ! isset( $theme_support[0]['featured_content_filter'] ) ) {
       
    76 			return;
       
    77 		}
       
    78 
       
    79 		$filter = $theme_support[0]['featured_content_filter'];
       
    80 
       
    81 		// Theme can override the number of max posts.
       
    82 		if ( isset( $theme_support[0]['max_posts'] ) ) {
       
    83 			self::$max_posts = absint( $theme_support[0]['max_posts'] );
       
    84 		}
       
    85 
       
    86 		add_filter( $filter,                              array( __CLASS__, 'get_featured_posts' )    );
       
    87 		add_action( 'customize_register',                 array( __CLASS__, 'customize_register' ), 9 );
       
    88 		add_action( 'admin_init',                         array( __CLASS__, 'register_setting'   )    );
       
    89 		add_action( 'switch_theme',                       array( __CLASS__, 'delete_transient'   )    );
       
    90 		add_action( 'save_post',                          array( __CLASS__, 'delete_transient'   )    );
       
    91 		add_action( 'delete_post_tag',                    array( __CLASS__, 'delete_post_tag'    )    );
       
    92 		add_action( 'customize_controls_enqueue_scripts', array( __CLASS__, 'enqueue_scripts'    )    );
       
    93 		add_action( 'pre_get_posts',                      array( __CLASS__, 'pre_get_posts'      )    );
       
    94 		add_action( 'wp_loaded',                          array( __CLASS__, 'wp_loaded'          )    );
       
    95 	}
       
    96 
       
    97 	/**
       
    98 	 * Hide "featured" tag from the front-end.
       
    99 	 *
       
   100 	 * Has to run on wp_loaded so that the preview filters of the Customizer
       
   101 	 * have a chance to alter the value.
       
   102 	 *
       
   103 	 * @static
       
   104 	 * @access public
       
   105 	 * @since Twenty Fourteen 1.0
       
   106 	 */
       
   107 	public static function wp_loaded() {
       
   108 		if ( self::get_setting( 'hide-tag' ) ) {
       
   109 			add_filter( 'get_terms',     array( __CLASS__, 'hide_featured_term'     ), 10, 3 );
       
   110 			add_filter( 'get_the_terms', array( __CLASS__, 'hide_the_featured_term' ), 10, 3 );
       
   111 		}
       
   112 	}
       
   113 
       
   114 	/**
       
   115 	 * Get featured posts.
       
   116 	 *
       
   117 	 * @static
       
   118 	 * @access public
       
   119 	 * @since Twenty Fourteen 1.0
       
   120 	 *
       
   121 	 * @return array Array of featured posts.
       
   122 	 */
       
   123 	public static function get_featured_posts() {
       
   124 		$post_ids = self::get_featured_post_ids();
       
   125 
       
   126 		// No need to query if there is are no featured posts.
       
   127 		if ( empty( $post_ids ) ) {
       
   128 			return array();
       
   129 		}
       
   130 
       
   131 		$featured_posts = get_posts( array(
       
   132 			'include'        => $post_ids,
       
   133 			'posts_per_page' => count( $post_ids ),
       
   134 		) );
       
   135 
       
   136 		return $featured_posts;
       
   137 	}
       
   138 
       
   139 	/**
       
   140 	 * Get featured post IDs
       
   141 	 *
       
   142 	 * This function will return the an array containing the
       
   143 	 * post IDs of all featured posts.
       
   144 	 *
       
   145 	 * Sets the "featured_content_ids" transient.
       
   146 	 *
       
   147 	 * @static
       
   148 	 * @access public
       
   149 	 * @since Twenty Fourteen 1.0
       
   150 	 *
       
   151 	 * @return array Array of post IDs.
       
   152 	 */
       
   153 	public static function get_featured_post_ids() {
       
   154 		// Get array of cached results if they exist.
       
   155 		$featured_ids = get_transient( 'featured_content_ids' );
       
   156 
       
   157 		if ( false === $featured_ids ) {
       
   158 			$settings = self::get_setting();
       
   159 			$term     = get_term_by( 'name', $settings['tag-name'], 'post_tag' );
       
   160 
       
   161 			if ( $term ) {
       
   162 				// Query for featured posts.
       
   163 				$featured_ids = get_posts( array(
       
   164 					'fields'           => 'ids',
       
   165 					'numberposts'      => self::$max_posts,
       
   166 					'suppress_filters' => false,
       
   167 					'tax_query'        => array(
       
   168 						array(
       
   169 							'field'    => 'term_id',
       
   170 							'taxonomy' => 'post_tag',
       
   171 							'terms'    => $term->term_id,
       
   172 						),
       
   173 					),
       
   174 				) );
       
   175 			}
       
   176 
       
   177 			// Get sticky posts if no Featured Content exists.
       
   178 			if ( ! $featured_ids ) {
       
   179 				$featured_ids = self::get_sticky_posts();
       
   180 			}
       
   181 
       
   182 			set_transient( 'featured_content_ids', $featured_ids );
       
   183 		}
       
   184 
       
   185 		// Ensure correct format before return.
       
   186 		return array_map( 'absint', $featured_ids );
       
   187 	}
       
   188 
       
   189 	/**
       
   190 	 * Return an array with IDs of posts maked as sticky.
       
   191 	 *
       
   192 	 * @static
       
   193 	 * @access public
       
   194 	 * @since Twenty Fourteen 1.0
       
   195 	 *
       
   196 	 * @return array Array of sticky posts.
       
   197 	 */
       
   198 	public static function get_sticky_posts() {
       
   199 		return array_slice( get_option( 'sticky_posts', array() ), 0, self::$max_posts );
       
   200 	}
       
   201 
       
   202 	/**
       
   203 	 * Delete featured content ids transient.
       
   204 	 *
       
   205 	 * Hooks in the "save_post" action.
       
   206 	 *
       
   207 	 * @see Featured_Content::validate_settings().
       
   208 	 *
       
   209 	 * @static
       
   210 	 * @access public
       
   211 	 * @since Twenty Fourteen 1.0
       
   212 	 */
       
   213 	public static function delete_transient() {
       
   214 		delete_transient( 'featured_content_ids' );
       
   215 	}
       
   216 
       
   217 	/**
       
   218 	 * Exclude featured posts from the home page blog query.
       
   219 	 *
       
   220 	 * Filter the home page posts, and remove any featured post ID's from it.
       
   221 	 * Hooked onto the 'pre_get_posts' action, this changes the parameters of
       
   222 	 * the query before it gets any posts.
       
   223 	 *
       
   224 	 * @static
       
   225 	 * @access public
       
   226 	 * @since Twenty Fourteen 1.0
       
   227 	 *
       
   228 	 * @param WP_Query $query WP_Query object.
       
   229 	 * @return WP_Query Possibly-modified WP_Query.
       
   230 	 */
       
   231 	public static function pre_get_posts( $query ) {
       
   232 
       
   233 		// Bail if not home or not main query.
       
   234 		if ( ! $query->is_home() || ! $query->is_main_query() ) {
       
   235 			return;
       
   236 		}
       
   237 
       
   238 		// Bail if the blog page is not the front page.
       
   239 		if ( 'posts' !== get_option( 'show_on_front' ) ) {
       
   240 			return;
       
   241 		}
       
   242 
       
   243 		$featured = self::get_featured_post_ids();
       
   244 
       
   245 		// Bail if no featured posts.
       
   246 		if ( ! $featured ) {
       
   247 			return;
       
   248 		}
       
   249 
       
   250 		// We need to respect post ids already in the blacklist.
       
   251 		$post__not_in = $query->get( 'post__not_in' );
       
   252 
       
   253 		if ( ! empty( $post__not_in ) ) {
       
   254 			$featured = array_merge( (array) $post__not_in, $featured );
       
   255 			$featured = array_unique( $featured );
       
   256 		}
       
   257 
       
   258 		$query->set( 'post__not_in', $featured );
       
   259 	}
       
   260 
       
   261 	/**
       
   262 	 * Reset tag option when the saved tag is deleted.
       
   263 	 *
       
   264 	 * It's important to mention that the transient needs to be deleted,
       
   265 	 * too. While it may not be obvious by looking at the function alone,
       
   266 	 * the transient is deleted by Featured_Content::validate_settings().
       
   267 	 *
       
   268 	 * Hooks in the "delete_post_tag" action.
       
   269 	 *
       
   270 	 * @see Featured_Content::validate_settings().
       
   271 	 *
       
   272 	 * @static
       
   273 	 * @access public
       
   274 	 * @since Twenty Fourteen 1.0
       
   275 	 *
       
   276 	 * @param int $tag_id The term_id of the tag that has been deleted.
       
   277 	 */
       
   278 	public static function delete_post_tag( $tag_id ) {
       
   279 		$settings = self::get_setting();
       
   280 
       
   281 		if ( empty( $settings['tag-id'] ) || $tag_id != $settings['tag-id'] ) {
       
   282 			return;
       
   283 		}
       
   284 
       
   285 		$settings['tag-id'] = 0;
       
   286 		$settings = self::validate_settings( $settings );
       
   287 		update_option( 'featured-content', $settings );
       
   288 	}
       
   289 
       
   290 	/**
       
   291 	 * Hide featured tag from displaying when global terms are queried from the front-end.
       
   292 	 *
       
   293 	 * Hooks into the "get_terms" filter.
       
   294 	 *
       
   295 	 * @static
       
   296 	 * @access public
       
   297 	 * @since Twenty Fourteen 1.0
       
   298 	 *
       
   299 	 * @param array $terms      List of term objects. This is the return value of get_terms().
       
   300 	 * @param array $taxonomies An array of taxonomy slugs.
       
   301 	 * @return array A filtered array of terms.
       
   302 	 *
       
   303 	 * @uses Featured_Content::get_setting()
       
   304 	 */
       
   305 	public static function hide_featured_term( $terms, $taxonomies, $args ) {
       
   306 
       
   307 		// This filter is only appropriate on the front-end.
       
   308 		if ( is_admin() ) {
       
   309 			return $terms;
       
   310 		}
       
   311 
       
   312 		// We only want to hide the featured tag.
       
   313 		if ( ! in_array( 'post_tag', $taxonomies ) ) {
       
   314 			return $terms;
       
   315 		}
       
   316 
       
   317 		// Bail if no terms were returned.
       
   318 		if ( empty( $terms ) ) {
       
   319 			return $terms;
       
   320 		}
       
   321 
       
   322 		// Bail if term objects are unavailable.
       
   323 		if ( 'all' != $args['fields'] ) {
       
   324 			return $terms;
       
   325 		}
       
   326 
       
   327 		$settings = self::get_setting();
       
   328 		foreach ( $terms as $order => $term ) {
       
   329 			if ( ( $settings['tag-id'] === $term->term_id || $settings['tag-name'] === $term->name ) && 'post_tag' === $term->taxonomy ) {
       
   330 				unset( $terms[ $order ] );
       
   331 			}
       
   332 		}
       
   333 
       
   334 		return $terms;
       
   335 	}
       
   336 
       
   337 	/**
       
   338 	 * Hide featured tag from display when terms associated with a post object
       
   339 	 * are queried from the front-end.
       
   340 	 *
       
   341 	 * Hooks into the "get_the_terms" filter.
       
   342 	 *
       
   343 	 * @static
       
   344 	 * @access public
       
   345 	 * @since Twenty Fourteen 1.0
       
   346 	 *
       
   347 	 * @param array $terms    A list of term objects. This is the return value of get_the_terms().
       
   348 	 * @param int   $id       The ID field for the post object that terms are associated with.
       
   349 	 * @param array $taxonomy An array of taxonomy slugs.
       
   350 	 * @return array Filtered array of terms.
       
   351 	 *
       
   352 	 * @uses Featured_Content::get_setting()
       
   353 	 */
       
   354 	public static function hide_the_featured_term( $terms, $id, $taxonomy ) {
       
   355 
       
   356 		// This filter is only appropriate on the front-end.
       
   357 		if ( is_admin() ) {
       
   358 			return $terms;
       
   359 		}
       
   360 
       
   361 		// Make sure we are in the correct taxonomy.
       
   362 		if ( 'post_tag' != $taxonomy ) {
       
   363 			return $terms;
       
   364 		}
       
   365 
       
   366 		// No terms? Return early!
       
   367 		if ( empty( $terms ) ) {
       
   368 			return $terms;
       
   369 		}
       
   370 
       
   371 		$settings = self::get_setting();
       
   372 		foreach ( $terms as $order => $term ) {
       
   373 			if ( ( $settings['tag-id'] === $term->term_id || $settings['tag-name'] === $term->name ) && 'post_tag' === $term->taxonomy ) {
       
   374 				unset( $terms[ $term->term_id ] );
       
   375 			}
       
   376 		}
       
   377 
       
   378 		return $terms;
       
   379 	}
       
   380 
       
   381 	/**
       
   382 	 * Register custom setting on the Settings -> Reading screen.
       
   383 	 *
       
   384 	 * @static
       
   385 	 * @access public
       
   386 	 * @since Twenty Fourteen 1.0
       
   387 	 */
       
   388 	public static function register_setting() {
       
   389 		register_setting( 'featured-content', 'featured-content', array( __CLASS__, 'validate_settings' ) );
       
   390 	}
       
   391 
       
   392 	/**
       
   393 	 * Add settings to the Customizer.
       
   394 	 *
       
   395 	 * @static
       
   396 	 * @access public
       
   397 	 * @since Twenty Fourteen 1.0
       
   398 	 *
       
   399 	 * @param WP_Customize_Manager $wp_customize Customizer object.
       
   400 	 */
       
   401 	public static function customize_register( $wp_customize ) {
       
   402 		$wp_customize->add_section( 'featured_content', array(
       
   403 			'title'          => __( 'Featured Content', 'twentyfourteen' ),
       
   404 			'description'    => sprintf( __( 'Use a <a href="%1$s">tag</a> to feature your posts. If no posts match the tag, <a href="%2$s">sticky posts</a> will be displayed instead.', 'twentyfourteen' ),
       
   405 				esc_url( add_query_arg( 'tag', _x( 'featured', 'featured content default tag slug', 'twentyfourteen' ), admin_url( 'edit.php' ) ) ),
       
   406 				admin_url( 'edit.php?show_sticky=1' )
       
   407 			),
       
   408 			'priority'       => 130,
       
   409 			'theme_supports' => 'featured-content',
       
   410 		) );
       
   411 
       
   412 		// Add Featured Content settings.
       
   413 		$wp_customize->add_setting( 'featured-content[tag-name]', array(
       
   414 			'default'              => _x( 'featured', 'featured content default tag slug', 'twentyfourteen' ),
       
   415 			'type'                 => 'option',
       
   416 			'sanitize_js_callback' => array( __CLASS__, 'delete_transient' ),
       
   417 		) );
       
   418 		$wp_customize->add_setting( 'featured-content[hide-tag]', array(
       
   419 			'default'              => true,
       
   420 			'type'                 => 'option',
       
   421 			'sanitize_js_callback' => array( __CLASS__, 'delete_transient' ),
       
   422 		) );
       
   423 
       
   424 		// Add Featured Content controls.
       
   425 		$wp_customize->add_control( 'featured-content[tag-name]', array(
       
   426 			'label'    => __( 'Tag Name', 'twentyfourteen' ),
       
   427 			'section'  => 'featured_content',
       
   428 			'priority' => 20,
       
   429 		) );
       
   430 		$wp_customize->add_control( 'featured-content[hide-tag]', array(
       
   431 			'label'    => __( 'Don&rsquo;t display tag on front end.', 'twentyfourteen' ),
       
   432 			'section'  => 'featured_content',
       
   433 			'type'     => 'checkbox',
       
   434 			'priority' => 30,
       
   435 		) );
       
   436 	}
       
   437 
       
   438 	/**
       
   439 	 * Enqueue the tag suggestion script.
       
   440 	 *
       
   441 	 * @static
       
   442 	 * @access public
       
   443 	 * @since Twenty Fourteen 1.0
       
   444 	 */
       
   445 	public static function enqueue_scripts() {
       
   446 		wp_enqueue_script( 'featured-content-suggest', get_template_directory_uri() . '/js/featured-content-admin.js', array( 'jquery', 'suggest' ), '20131022', true );
       
   447 	}
       
   448 
       
   449 	/**
       
   450 	 * Get featured content settings.
       
   451 	 *
       
   452 	 * Get all settings recognized by this module. This function
       
   453 	 * will return all settings whether or not they have been stored
       
   454 	 * in the database yet. This ensures that all keys are available
       
   455 	 * at all times.
       
   456 	 *
       
   457 	 * In the event that you only require one setting, you may pass
       
   458 	 * its name as the first parameter to the function and only that
       
   459 	 * value will be returned.
       
   460 	 *
       
   461 	 * @static
       
   462 	 * @access public
       
   463 	 * @since Twenty Fourteen 1.0
       
   464 	 *
       
   465 	 * @param string $key The key of a recognized setting.
       
   466 	 * @return mixed Array of all settings by default. A single value if passed as first parameter.
       
   467 	 */
       
   468 	public static function get_setting( $key = 'all' ) {
       
   469 		$saved = (array) get_option( 'featured-content' );
       
   470 
       
   471 		$defaults = array(
       
   472 			'hide-tag' => 1,
       
   473 			'tag-id'   => 0,
       
   474 			'tag-name' => _x( 'featured', 'featured content default tag slug', 'twentyfourteen' ),
       
   475 		);
       
   476 
       
   477 		$options = wp_parse_args( $saved, $defaults );
       
   478 		$options = array_intersect_key( $options, $defaults );
       
   479 
       
   480 		if ( 'all' != $key ) {
       
   481 			return isset( $options[ $key ] ) ? $options[ $key ] : false;
       
   482 		}
       
   483 
       
   484 		return $options;
       
   485 	}
       
   486 
       
   487 	/**
       
   488 	 * Validate featured content settings.
       
   489 	 *
       
   490 	 * Make sure that all user supplied content is in an expected
       
   491 	 * format before saving to the database. This function will also
       
   492 	 * delete the transient set in Featured_Content::get_featured_content().
       
   493 	 *
       
   494 	 * @static
       
   495 	 * @access public
       
   496 	 * @since Twenty Fourteen 1.0
       
   497 	 *
       
   498 	 * @param array $input Array of settings input.
       
   499 	 * @return array Validated settings output.
       
   500 	 */
       
   501 	public static function validate_settings( $input ) {
       
   502 		$output = array();
       
   503 
       
   504 		if ( empty( $input['tag-name'] ) ) {
       
   505 			$output['tag-id'] = 0;
       
   506 		} else {
       
   507 			$term = get_term_by( 'name', $input['tag-name'], 'post_tag' );
       
   508 
       
   509 			if ( $term ) {
       
   510 				$output['tag-id'] = $term->term_id;
       
   511 			} else {
       
   512 				$new_tag = wp_create_tag( $input['tag-name'] );
       
   513 
       
   514 				if ( ! is_wp_error( $new_tag ) && isset( $new_tag['term_id'] ) ) {
       
   515 					$output['tag-id'] = $new_tag['term_id'];
       
   516 				}
       
   517 			}
       
   518 
       
   519 			$output['tag-name'] = $input['tag-name'];
       
   520 		}
       
   521 
       
   522 		$output['hide-tag'] = isset( $input['hide-tag'] ) && $input['hide-tag'] ? 1 : 0;
       
   523 
       
   524 		// Delete the featured post ids transient.
       
   525 		self::delete_transient();
       
   526 
       
   527 		return $output;
       
   528 	}
       
   529 } // Featured_Content
       
   530 
       
   531 Featured_Content::setup();