WordPress 3.9
[autoinstalls/wordpress.git] / wp-content / themes / twentyfourteen / inc / featured-content.php
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, 2 );
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                 // Return array of cached results if they exist.
155                 $featured_ids = get_transient( 'featured_content_ids' );
156                 if ( ! empty( $featured_ids ) ) {
157                         return array_map( 'absint', (array) $featured_ids );
158                 }
159
160                 $settings = self::get_setting();
161
162                 // Return sticky post ids if no tag name is set.
163                 $term = get_term_by( 'name', $settings['tag-name'], 'post_tag' );
164                 if ( $term ) {
165                         $tag = $term->term_id;
166                 } else {
167                         return self::get_sticky_posts();
168                 }
169
170                 // Query for featured posts.
171                 $featured = get_posts( array(
172                         'numberposts' => self::$max_posts,
173                         'tax_query'   => array(
174                                 array(
175                                         'field'    => 'term_id',
176                                         'taxonomy' => 'post_tag',
177                                         'terms'    => $tag,
178                                 ),
179                         ),
180                 ) );
181
182                 // Return array with sticky posts if no Featured Content exists.
183                 if ( ! $featured ) {
184                         return self::get_sticky_posts();
185                 }
186
187                 // Ensure correct format before save/return.
188                 $featured_ids = wp_list_pluck( (array) $featured, 'ID' );
189                 $featured_ids = array_map( 'absint', $featured_ids );
190
191                 set_transient( 'featured_content_ids', $featured_ids );
192
193                 return $featured_ids;
194         }
195
196         /**
197          * Return an array with IDs of posts maked as sticky.
198          *
199          * @static
200          * @access public
201          * @since Twenty Fourteen 1.0
202          *
203          * @return array Array of sticky posts.
204          */
205         public static function get_sticky_posts() {
206                 $settings = self::get_setting();
207                 return array_slice( get_option( 'sticky_posts', array() ), 0, self::$max_posts );
208         }
209
210         /**
211          * Delete featured content ids transient.
212          *
213          * Hooks in the "save_post" action.
214          *
215          * @see Featured_Content::validate_settings().
216          *
217          * @static
218          * @access public
219          * @since Twenty Fourteen 1.0
220          */
221         public static function delete_transient() {
222                 delete_transient( 'featured_content_ids' );
223         }
224
225         /**
226          * Exclude featured posts from the home page blog query.
227          *
228          * Filter the home page posts, and remove any featured post ID's from it.
229          * Hooked onto the 'pre_get_posts' action, this changes the parameters of
230          * the query before it gets any posts.
231          *
232          * @static
233          * @access public
234          * @since Twenty Fourteen 1.0
235          *
236          * @param WP_Query $query WP_Query object.
237          * @return WP_Query Possibly-modified WP_Query.
238          */
239         public static function pre_get_posts( $query ) {
240
241                 // Bail if not home or not main query.
242                 if ( ! $query->is_home() || ! $query->is_main_query() ) {
243                         return;
244                 }
245
246                 $page_on_front = get_option( 'page_on_front' );
247
248                 // Bail if the blog page is not the front page.
249                 if ( ! empty( $page_on_front ) ) {
250                         return;
251                 }
252
253                 $featured = self::get_featured_post_ids();
254
255                 // Bail if no featured posts.
256                 if ( ! $featured ) {
257                         return;
258                 }
259
260                 // We need to respect post ids already in the blacklist.
261                 $post__not_in = $query->get( 'post__not_in' );
262
263                 if ( ! empty( $post__not_in ) ) {
264                         $featured = array_merge( (array) $post__not_in, $featured );
265                         $featured = array_unique( $featured );
266                 }
267
268                 $query->set( 'post__not_in', $featured );
269         }
270
271         /**
272          * Reset tag option when the saved tag is deleted.
273          *
274          * It's important to mention that the transient needs to be deleted,
275          * too. While it may not be obvious by looking at the function alone,
276          * the transient is deleted by Featured_Content::validate_settings().
277          *
278          * Hooks in the "delete_post_tag" action.
279          *
280          * @see Featured_Content::validate_settings().
281          *
282          * @static
283          * @access public
284          * @since Twenty Fourteen 1.0
285          *
286          * @param int $tag_id The term_id of the tag that has been deleted.
287          */
288         public static function delete_post_tag( $tag_id ) {
289                 $settings = self::get_setting();
290
291                 if ( empty( $settings['tag-id'] ) || $tag_id != $settings['tag-id'] ) {
292                         return;
293                 }
294
295                 $settings['tag-id'] = 0;
296                 $settings = self::validate_settings( $settings );
297                 update_option( 'featured-content', $settings );
298         }
299
300         /**
301          * Hide featured tag from displaying when global terms are queried from the front-end.
302          *
303          * Hooks into the "get_terms" filter.
304          *
305          * @static
306          * @access public
307          * @since Twenty Fourteen 1.0
308          *
309          * @param array $terms      List of term objects. This is the return value of get_terms().
310          * @param array $taxonomies An array of taxonomy slugs.
311          * @return array A filtered array of terms.
312          *
313          * @uses Featured_Content::get_setting()
314          */
315         public static function hide_featured_term( $terms, $taxonomies ) {
316
317                 // This filter is only appropriate on the front-end.
318                 if ( is_admin() ) {
319                         return $terms;
320                 }
321
322                 // We only want to hide the featured tag.
323                 if ( ! in_array( 'post_tag', $taxonomies ) ) {
324                         return $terms;
325                 }
326
327                 // Bail if no terms were returned.
328                 if ( empty( $terms ) ) {
329                         return $terms;
330                 }
331
332                 $settings = self::get_setting();
333                 foreach( $terms as $order => $term ) {
334                         if ( ( $settings['tag-id'] === $term->term_id || $settings['tag-name'] === $term->name ) && 'post_tag' === $term->taxonomy ) {
335                                 unset( $terms[ $order ] );
336                         }
337                 }
338
339                 return $terms;
340         }
341
342         /**
343          * Hide featured tag from display when terms associated with a post object
344          * are queried from the front-end.
345          *
346          * Hooks into the "get_the_terms" filter.
347          *
348          * @static
349          * @access public
350          * @since Twenty Fourteen 1.0
351          *
352          * @param array $terms    A list of term objects. This is the return value of get_the_terms().
353          * @param int   $id       The ID field for the post object that terms are associated with.
354          * @param array $taxonomy An array of taxonomy slugs.
355          * @return array Filtered array of terms.
356          *
357          * @uses Featured_Content::get_setting()
358          */
359         public static function hide_the_featured_term( $terms, $id, $taxonomy ) {
360
361                 // This filter is only appropriate on the front-end.
362                 if ( is_admin() ) {
363                         return $terms;
364                 }
365
366                 // Make sure we are in the correct taxonomy.
367                 if ( 'post_tag' != $taxonomy ) {
368                         return $terms;
369                 }
370
371                 // No terms? Return early!
372                 if ( empty( $terms ) ) {
373                         return $terms;
374                 }
375
376                 $settings = self::get_setting();
377                 foreach( $terms as $order => $term ) {
378                         if ( ( $settings['tag-id'] === $term->term_id || $settings['tag-name'] === $term->name ) && 'post_tag' === $term->taxonomy ) {
379                                 unset( $terms[ $term->term_id ] );
380                         }
381                 }
382
383                 return $terms;
384         }
385
386         /**
387          * Register custom setting on the Settings -> Reading screen.
388          *
389          * @static
390          * @access public
391          * @since Twenty Fourteen 1.0
392          */
393         public static function register_setting() {
394                 register_setting( 'featured-content', 'featured-content', array( __CLASS__, 'validate_settings' ) );
395         }
396
397         /**
398          * Add settings to the Customizer.
399          *
400          * @static
401          * @access public
402          * @since Twenty Fourteen 1.0
403          *
404          * @param WP_Customize_Manager $wp_customize Theme Customizer object.
405          */
406         public static function customize_register( $wp_customize ) {
407                 $wp_customize->add_section( 'featured_content', array(
408                         'title'          => __( 'Featured Content', 'twentyfourteen' ),
409                         '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' ),
410                                 esc_url( add_query_arg( 'tag', _x( 'featured', 'featured content default tag slug', 'twentyfourteen' ), admin_url( 'edit.php' ) ) ),
411                                 admin_url( 'edit.php?show_sticky=1' )
412                         ),
413                         'priority'       => 130,
414                         'theme_supports' => 'featured-content',
415                 ) );
416
417                 // Add Featured Content settings.
418                 $wp_customize->add_setting( 'featured-content[tag-name]', array(
419                         'default'              => _x( 'featured', 'featured content default tag slug', 'twentyfourteen' ),
420                         'type'                 => 'option',
421                         'sanitize_js_callback' => array( __CLASS__, 'delete_transient' ),
422                 ) );
423                 $wp_customize->add_setting( 'featured-content[hide-tag]', array(
424                         'default'              => true,
425                         'type'                 => 'option',
426                         'sanitize_js_callback' => array( __CLASS__, 'delete_transient' ),
427                 ) );
428
429                 // Add Featured Content controls.
430                 $wp_customize->add_control( 'featured-content[tag-name]', array(
431                         'label'    => __( 'Tag Name', 'twentyfourteen' ),
432                         'section'  => 'featured_content',
433                         'priority' => 20,
434                 ) );
435                 $wp_customize->add_control( 'featured-content[hide-tag]', array(
436                         'label'    => __( 'Don&rsquo;t display tag on front end.', 'twentyfourteen' ),
437                         'section'  => 'featured_content',
438                         'type'     => 'checkbox',
439                         'priority' => 30,
440                 ) );
441         }
442
443         /**
444          * Enqueue the tag suggestion script.
445          *
446          * @static
447          * @access public
448          * @since Twenty Fourteen 1.0
449          */
450         public static function enqueue_scripts() {
451                 wp_enqueue_script( 'featured-content-suggest', get_template_directory_uri() . '/js/featured-content-admin.js', array( 'jquery', 'suggest' ), '20131022', true );
452         }
453
454         /**
455          * Get featured content settings.
456          *
457          * Get all settings recognized by this module. This function
458          * will return all settings whether or not they have been stored
459          * in the database yet. This ensures that all keys are available
460          * at all times.
461          *
462          * In the event that you only require one setting, you may pass
463          * its name as the first parameter to the function and only that
464          * value will be returned.
465          *
466          * @static
467          * @access public
468          * @since Twenty Fourteen 1.0
469          *
470          * @param string $key The key of a recognized setting.
471          * @return mixed Array of all settings by default. A single value if passed as first parameter.
472          */
473         public static function get_setting( $key = 'all' ) {
474                 $saved = (array) get_option( 'featured-content' );
475
476                 $defaults = array(
477                         'hide-tag' => 1,
478                         'tag-id'   => 0,
479                         'tag-name' => _x( 'featured', 'featured content default tag slug', 'twentyfourteen' ),
480                 );
481
482                 $options = wp_parse_args( $saved, $defaults );
483                 $options = array_intersect_key( $options, $defaults );
484
485                 if ( 'all' != $key ) {
486                         return isset( $options[ $key ] ) ? $options[ $key ] : false;
487                 }
488
489                 return $options;
490         }
491
492         /**
493          * Validate featured content settings.
494          *
495          * Make sure that all user supplied content is in an expected
496          * format before saving to the database. This function will also
497          * delete the transient set in Featured_Content::get_featured_content().
498          *
499          * @static
500          * @access public
501          * @since Twenty Fourteen 1.0
502          *
503          * @param array $input Array of settings input.
504          * @return array Validated settings output.
505          */
506         public static function validate_settings( $input ) {
507                 $output = array();
508
509                 if ( empty( $input['tag-name'] ) ) {
510                         $output['tag-id'] = 0;
511                 } else {
512                         $term = get_term_by( 'name', $input['tag-name'], 'post_tag' );
513
514                         if ( $term ) {
515                                 $output['tag-id'] = $term->term_id;
516                         } else {
517                                 $new_tag = wp_create_tag( $input['tag-name'] );
518
519                                 if ( ! is_wp_error( $new_tag ) && isset( $new_tag['term_id'] ) ) {
520                                         $output['tag-id'] = $new_tag['term_id'];
521                                 }
522                         }
523
524                         $output['tag-name'] = $input['tag-name'];
525                 }
526
527                 $output['hide-tag'] = isset( $input['hide-tag'] ) && $input['hide-tag'] ? 1 : 0;
528
529                 // Delete the featured post ids transient.
530                 self::delete_transient();
531
532                 return $output;
533         }
534 } // Featured_Content
535
536 Featured_Content::setup();