-
-
Notifications
You must be signed in to change notification settings - Fork 508
/
Timber.php
1405 lines (1267 loc) · 40.8 KB
/
Timber.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Timber;
use WP_Query;
use WP_Post;
use Timber\Factory\CommentFactory;
use Timber\Factory\MenuFactory;
use Timber\Factory\PostFactory;
use Timber\Factory\TermFactory;
use Timber\Factory\UserFactory;
use Timber\Helper;
use Timber\PostCollectionInterface;
use Timber\URLHelper;
/**
* Class Timber
*
* Main class called Timber for this plugin.
*
* @api
* @example
* ```php
* // Get default posts on an archive page
* $posts = Timber::get_posts();
*
* // Query for some posts
* $posts = Timber::get_posts( [
* 'post_type' => 'article',
* 'category_name' => 'sports',
* ] );
*
* $context = Timber::context();
* $context['posts'] = $posts;
*
* Timber::render( 'index.twig', $context );
* ```
*/
class Timber {
public static $version = '2.0.0';
public static $locations;
public static $dirname = 'views';
public static $auto_meta = true;
/**
* Global context cache.
*
* @var array An array containing global context variables.
*/
public static $context_cache = array();
/**
* Caching option for Twig.
*
* @deprecated 2.0.0
* @var bool
*/
public static $twig_cache = false;
/**
* Caching option for Twig.
*
* Alias for `Timber::$twig_cache`.
*
* @deprecated 2.0.0
* @var bool
*/
public static $cache = false;
/**
* Autoescaping option for Twig.
*
* @deprecated 2.0.0
* @var bool
*/
public static $autoescape = false;
/**
* @codeCoverageIgnore
*/
public function __construct() {
if ( !defined('ABSPATH') ) {
return;
}
if ( class_exists('\WP') && !defined('TIMBER_LOADED') ) {
$this->test_compatibility();
$this->init_constants();
self::init();
}
}
/**
* Tests whether we can use Timber
* @codeCoverageIgnore
*/
protected function test_compatibility() {
if ( is_admin() || $_SERVER['PHP_SELF'] == '/wp-login.php' ) {
return;
}
if ( version_compare(phpversion(), '5.3.0', '<') && !is_admin() ) {
trigger_error('Timber requires PHP 5.3.0 or greater. You have '.phpversion(), E_USER_ERROR);
}
if ( ! class_exists( 'Twig\Token' ) ) {
trigger_error('You have not run "composer install" to download required dependencies for Timber, you can read more on https://github.com/timber/timber#installation', E_USER_ERROR);
}
}
public function init_constants() {
defined("TIMBER_LOC") or define("TIMBER_LOC", realpath(dirname(__DIR__)));
}
/**
* @codeCoverageIgnore
*/
protected static function init() {
if ( class_exists('\WP') && !defined('TIMBER_LOADED') ) {
Twig::init();
ImageHelper::init();
Admin::init();
new Integrations();
// @todo find a more permanent home for this stuff, maybe in a QueryHelper class?
add_filter('pre_get_posts', function(WP_Query $query) {
$cat = $query->query['category'] ?? null;
if ( $cat && !isset($query->query['cat']) ) {
unset($query->query['category']);
$query->set('cat', $cat);
}
});
add_filter('pre_get_posts', function(WP_Query $query) {
$count = $query->query['numberposts'] ?? null;
if ( $count && !isset($query->query['posts_per_page']) ) {
$query->set('posts_per_page', $count);
}
});
add_filter('timber/post/import_data', function($data) {
if ( isset($_GET['preview']) && isset($_GET['preview_id']) ) {
$preview = wp_get_post_autosave($_GET['preview_id']);
if ( is_object($preview) ) {
$preview = sanitize_post($preview);
$data->post_content = $preview->post_content;
$data->post_title = $preview->post_title;
$data->post_excerpt = $preview->post_excerpt;
// @todo I think we can safely delete this?
// It was included in the old PostCollection method but not defined anywhere,
// so I think it was always just falling into a magic __call() and doing nothing.
// $post->import_custom($preview_id);
add_filter('get_the_terms', '_wp_preview_terms_filter', 10, 3);
}
}
return $data;
});
/**
* Make an alias for the Timber class.
*
* This way, developers can use Timber::render() instead of Timber\Timber::render, which
* is more user-friendly.
*/
class_alias( 'Timber\Timber', 'Timber' );
define('TIMBER_LOADED', true);
}
}
/* Post Retrieval Routine
================================ */
/**
* Get a Timber Post from a post ID, WP_Post object, a WP_Query object, or an associative
* array of arguments for WP_Query::__construct().
*
* By default, Timber will use the `Timber\Post` class to create a new post object. To control
* which class is instantiated for your Post object, use [Class Maps](https://timber.github.io/docs/v2/guides/class-maps/)
*
* @api
* @example
* ```php
* // Using a post ID.
* $post = Timber::get_post( 75 );
*
* // Using a WP_Post object.
* $wp_post = get_post( 123 );
* $post = Timber::get_post( $wp_post );
*
* // Using a WP_Query argument array
* $post = Timber::get_post( [
* 'post_type' => 'page',
* ] );
*
* // Use currently queried post. Same as using get_the_ID() as a parameter.
* $post = Timber::get_post();
*
* // From an associative array with an `ID` key. For ACF compatibility. Using this
* // approach directly is not recommended. If you can, configure the return type of your
* // ACF field to just the ID.
* $post = Timber::get_post( get_field('associated_post_array') ); // Just OK.
* $post = Timber::get_post( get_field('associated_post_id') ); // Better!
* ```
* @see https://developer.wordpress.org/reference/classes/wp_query/__construct/
*
* @param mixed $query Optional. Post ID or query (as an array of arguments for WP_Query).
* If a query is provided, only the first post of the result will be
* returned. Default false.
* @param array $options Optional associative array of options. Defaults to an empty array.
*
* @return \Timber\Post|bool Timber\Post object if a post was found, false if no post was
* found.
*/
public static function get_post( $query = false, $options = [] ) {
if ( is_string( $query ) && ! is_numeric( $query ) ) {
Helper::doing_it_wrong(
'Timber::get_post()',
'Getting a post by post slug or post name was removed from Timber::get_post() in Timber 2.0. Use Timber::get_post_by() instead.',
'2.0.0'
);
}
if ( is_string( $options ) ) {
Helper::doing_it_wrong(
'Timber::get_post()',
'The $PostClass parameter for passing in the post class to use in Timber::get_posts() was replaced with an $options array in Timber 2.0. To customize which class to instantiate for your post, use Class Maps instead: https://timber.github.io/docs/v2/guides/class-maps/',
'2.0.0'
);
$options = [];
}
$factory = new PostFactory();
global $wp_query;
$options = wp_parse_args($options, [
'merge_default' => false
]);
// Has WP already queried and found a post?
if ($query === false && ($wp_query->queried_object instanceof WP_Post)) {
$query = $wp_query->queried_object;
} elseif (is_array($query) && $options['merge_default']) {
$query = wp_parse_args($wp_query->query_vars);
}
// Default to the global query.
$result = $factory->from($query ?: $wp_query);
// If we got a Collection, return the first Post.
if ($result instanceof PostCollectionInterface) {
return $result[0] ?? false;
}
return $result;
}
/**
* Behaves just like Timber::get_post(), except that it returns false if it
* finds a Post that is not an Attachment. Honors Class Maps and falsifies return
* value *after* Class Map for the found Post has been resolved.
*
* @api
* @see Timber::get_post()
* @see https://timber.github.io/docs/v2/guides/class-maps/
* @param mixed $query query or post identifier
* @param array $options options to ::get_post()
* @return Attachment|false
*/
public static function get_attachment( $query = false, $options = [] ) {
$post = static::get_post( $query, $options );
// @todo make this determination at the Factory level.
// No need to instantiate a Post we're not going to use.
return ( $post instanceof Attachment ) ? $post : false;
}
/**
* Behaves just like Timber::get_post(), except that it returns false if it
* finds a Post that is not an Image. Honors Class Maps and falsifies return
* value *after* Class Map for the found Post has been resolved.
*
* @api
* @see Timber::get_post()
* @see https://timber.github.io/docs/v2/guides/class-maps/
* @param mixed $query query or post identifier
* @param array $options options to ::get_post()
* @return Image|false
*/
public static function get_image( $query = false, $options = [] ) {
$post = static::get_post( $query, $options );
// @todo make this determination at the Factory level.
// No need to instantiate a Post we're not going to use.
return ( $post instanceof Image ) ? $post : false;
}
/**
* Get posts.
*
* @api
*
* @todo improve this docblock
* @param mixed $query
* @param array $options
*
* @return array|bool|null
*/
public static function get_posts( $query = false, $options = [] ) {
if ( is_string( $query ) ) {
Helper::doing_it_wrong(
'Timber::get_posts()',
"Querying posts by using a query string was removed in Timber 2.0. Pass in the query string as an options array instead. For example, change Timber::get_posts( 'post_type=portfolio&posts_per_page=3') to Timber::get_posts( [ 'post_type' => 'portfolio', 'posts_per_page' => 3 ] ). Learn more: https://timber.github.io/docs/v2/reference/timber-timber/#get_posts",
'2.0.0'
);
$query = new WP_Query( $query );
}
if ( is_string( $options ) ) {
Helper::doing_it_wrong(
'Timber::get_posts()',
'The $PostClass parameter for passing in the post class to use in Timber::get_posts() was replaced with an $options array in Timber 2.0. To customize which class to instantiate for your post, use Class Maps instead: https://timber.github.io/docs/v2/guides/class-maps/',
'2.0.0'
);
$options = [];
}
if ( 3 === func_num_args() ) {
Helper::doing_it_wrong(
'Timber::get_posts()',
'The $return_collection parameter to control whether a post collection is returned in Timber::get_posts() was removed in Timber 2.0.',
'2.0.0'
);
}
/**
* @todo Are there any more default options to support?
*/
$options = wp_parse_args( $options, [
'merge_default' => false,
] );
global $wp_query;
if ( is_array($query) && $options['merge_default'] ) {
$query = wp_parse_args( $query, $wp_query->query_vars );
}
$factory = new PostFactory();
// Default to the global query.
return $factory->from($query ?: $wp_query);
}
/**
* Gets a post by title or slug.
*
* @api
* @since 2.0.0
* @example
* ```php
* // By slug
* $post = Timber::get_post_by( 'slug', 'about-us' );
*
* // By title
* $post = Timber::get_post_by( 'title', 'About us' );
* ```
*
* @param string $type The type to look for. One of `slug` or `title`.
* @param string $search_value The post slug or post title to search for. When searching
* for `title`, this parameter doesn’t need to be
* case-sensitive, because the `=` comparison is used in
* MySQL.
* @param array $args {
* Optional. An array of arguments to configure what is returned.
*
* @type string|array $post_type Optional. What WordPress post type to limit the
* results to. Defaults to 'any'
* @type string $order_by Optional. The field to sort by. Defaults to
* 'post_date'
* @type string $order Optional. The sort to apply. Defaults to ASC
*
* }
*
* @return \Timber\Post|false A Timber post or `false` if no post could be found. If multiple
* posts with the same slug or title were found, it will select the
* post with the oldest date.
*/
public static function get_post_by( $type, $search_value, $args = array() ) {
$post_id = false;
$args = wp_parse_args( $args, [
'post_type' => 'any',
'order_by' => 'post_date',
'order' => 'ASC'
] );
if ( 'slug' === $type ) {
$args = wp_parse_args($args, [
'name' => $search_value,
'fields' => 'ids'
]);
$query = new \WP_Query( $args );
if ( $query->post_count < 1 ) {
return false;
}
$posts = $query->get_posts();
$post_id = array_shift( $posts );
} elseif ( 'title' === $type ) {
/**
* The following section is inspired by post_exists() as well as get_page_by_title().
*
* These two functions always return the post with lowest ID. However, we want the post
* with oldest post date.
*
* @see \post_exists()
* @see \get_page_by_title()
*/
global $wpdb;
$sql = "SELECT ID FROM $wpdb->posts WHERE post_title = %s";
$query_args = [ $search_value ];
if ( is_array( $args['post_type'] ) ) {
$post_type = esc_sql( $args['post_type'] );
$post_type_in_string = "'" . implode( "','", $args['post_type'] ) . "'";
$sql .= " AND post_type IN ($post_type_in_string)";
} elseif ( 'any' !== $args['post_type'] ) {
$sql .= ' AND post_type = %s';
$query_args[] = $args['post_type'];
}
// Always return the oldest post first.
$sql .= ' ORDER BY post_date ASC';
$post_id = $wpdb->get_var( $wpdb->prepare( $sql, $query_args ) );
}
if ( ! $post_id ) {
return false;
}
return self::get_post( $post_id );
}
/**
* Query post.
*
* @api
* @deprecated since 2.0.0 Use `Timber::get_post()` instead.
*
* @param mixed $query
* @param array $options
*
* @return Post|array|bool|null
*/
public static function query_post( $query = false, array $options = [] ) {
Helper::deprecated('Timber::query_post()', 'Timber::get_post()', '2.0.0');
return self::get_post($query, $options);
}
/**
* Query posts.
*
* @api
* @deprecated since 2.0.0 Use `Timber::get_posts()` instead.
*
* @param mixed $query
* @param array $options
*
* @return PostCollection
*/
public static function query_posts( $query = false, array $options = [] ) {
Helper::deprecated('Timber::query_posts()', 'Timber::get_posts()', '2.0.0');
return self::get_posts($query, $options);
}
/**
* Gets an attachment by its URL or absolute file path.
*
* Honors the `timber/post/image_extensions` filter, returning a Timber\Image if the found
* attachment is identified as an image. Also honors Class Maps.
*
* @api
* @since 2.0.0
* @example
* ```php
* // Get attachment by URL.
* $attachment = Timber::get_attachment_by( 'url', 'https://example.com/uploads/2020/09/cat.gif' );
*
* // Get attachment by filepath.
* $attachment = Timber::get_attachment_by( 'path', '/path/to/wp-content/uploads/2020/09/cat.gif' );
*
* // Try to handle either case.
* $mystery_string = some_function();
* $attachment = Timber::get_attachment_by( $mystery_string );
* ```
*
* @param string $field_or_ident Can be "url", "path", an attachment URL, or the absolute
* path of an attachment file. If "url" or "path" is given, a
* second arg is required.
* @param string $ident Optional. An attachment URL or absolute path. Default empty
* string.
*
* @return \Timber\Attachment|false
*/
public static function get_attachment_by( string $field_or_ident, string $ident = '' ) {
if ($field_or_ident === 'url') {
if (empty($ident)) {
Helper::doing_it_wrong(
'Timber::get_attachment_by()',
'Passing "url" as the first arg requires passing a URL as the second arg.',
'2.0.0'
);
return false;
}
$id = attachment_url_to_postid($ident);
return $id ? (new PostFactory())->from($id) : false;
}
if ($field_or_ident === 'path') {
if (empty($ident)) {
Helper::doing_it_wrong(
'Timber::get_attachment_by()',
'Passing "path" as the first arg requires passing an absolute path as the second arg.',
'2.0.0'
);
return false;
}
if (!file_exists($ident)) {
// Deal with a relative path.
$ident = URLHelper::get_full_path($ident);
}
return self::get_attachment_by('url', URLHelper::file_system_to_url($ident));
}
if (empty($ident)) {
$field = URLHelper::starts_with($field_or_ident, ABSPATH) ? 'path' : 'url';
return self::get_attachment_by($field, $field_or_ident);
}
return false;
}
/* Term Retrieval
================================ */
/**
* Get terms.
* @api
* @param string|array $args a string or array identifying the taxonomy or
* `WP_Term_Query` args. Numeric strings are treated as term IDs; non-numeric
* strings are treated as taxonomy names. Numeric arrays are treated as a
* list a of term identifiers; associative arrays are treated as args to
* `WP_Term_Query::__construct()` and accepts any valid parameters to that
* constructor.
* @param array $options optional; none are currently supported.
* @return Iterable
* @see https://developer.wordpress.org/reference/classes/wp_term_query/__construct/
* @example
* ```php
* // Get all tags.
* $tags = Timber::get_terms('post_tag');
* // Note that this is equivalent to:
* $tags = Timber::get_terms( 'tag' );
* $tags = Timber::get_terms( 'tags' );
*
* // Get all categories.
* $cats = Timber::get_terms('category');
*
* // Get all terms in a custom taxonomy.
* $cats = Timber::get_terms('my_taxonomy');
*
* // Perform a custom Term query.
* $cats = Timber::get_terms([
* 'taxonomy' => 'my_taxonomy',
* 'orderby' => 'slug',
* 'order' => 'DESC',
* ]);
* ```
*/
public static function get_terms( $args = null, array $options = [] ) : Iterable {
// default to all queryable taxonomies
$args = $args ?? [
'taxonomy' => get_taxonomies(),
];
$factory = new TermFactory();
return $factory->from($args);
}
/**
* Get term.
* @api
* @param int|\WP_Term $term a WP_Term or term_id
* @return \Timber\Term|false
* @example
* ```php
* // Get a Term.
* $tag = Timber::get_term(123);
* ```
*/
public static function get_term( $term = null ) {
if (null === $term) {
// get the fallback term_id from the current query
global $wp_query;
$term = $wp_query->queried_object->term_id ?? null;
}
if (null === $term) {
// not able to get term_id from the current query; bail
return false;
}
$factory = new TermFactory();
return $factory->from($term);
}
/* User Retrieval
================================ */
/**
* Gets one or more users as an array.
*
* By default, Timber will use the `Timber\User` class to create a your post objects. To
* control which class is used for your post objects, use [Class Maps]().
*
* @api
* @since 2.0.0
* @example
* ```php
* // Get users with on an array of user IDs.
* $users = Timber::get_users( [ 24, 81, 325 ] );
*
* // Get all users that only have a subscriber role.
* $subscribers = Timber::get_users( [
* 'role' => 'subscriber',
* ] );
*
* // Get all users that have published posts.
* $post_authors = Timber::get_users( [
* 'has_published_posts' => [ 'post' ],
* ] );
* ```
*
* @todo Add links to Class Maps documentation in function summary.
*
* @param array $query Optional. A WordPress-style query or an array of user IDs. Use an
* array in the same way you would use the `$args` parameter in
* [WP_User_Query](https://developer.wordpress.org/reference/classes/wp_user_query/).
* See
* [WP_User_Query::prepare_query()](https://developer.wordpress.org/reference/classes/WP_User_Query/prepare_query/)
* for a list of all available parameters. Passing an empty parameter
* will return an empty array. Default empty array
* `[]`.
* @param array $options Optional. An array of options. None are currently supported. This
* parameter exists to prevent future breaking changes. Default empty
* array `[]`.
*
* @return \Iterable An array of users objects. Will be empty if no users were found.
*/
public static function get_users( array $query = [], array $options = [] ) : Iterable {
$factory = new UserFactory();
// TODO return a Collection type?
return $factory->from($query);
}
/**
* Gets a single user.
*
* By default, Timber will use the `Timber\User` class to create a your post objects. To
* control which class is used for your post objects, use [Class Maps]().
*
* @api
* @since 2.0.0
* @example
* ```php
* $current_user = Timber::get_user();
*
* // Get user by ID.
* $user = Timber::get_user( $user_id );
*
* // Convert a WP_User object to a Timber\User object.
* $user = Timber::get_user( $wp_user_object );
*
* // Check if a user is logged in.
*
* $user = Timber::get_user();
*
* if ( $user ) {
* // Yay, user is logged in.
* }
* ```
*
* @todo Add links to Class Maps documentation in function summary.
*
* @param int|\WP_User $user A WP_User object or a WordPress user ID. Defaults to the ID of the
* currently logged-in user.
*
* @return \Timber\User|false
*/
public static function get_user( $user = null ) {
/*
* TODO in the interest of time, I'm implementing this logic here. If there's
* a better place to do this or something that already implements this, let me know
* and I'll switch over to that.
*/
$user = $user ?: get_current_user_id();
$factory = new UserFactory();
return $factory->from($user);
}
/**
* Gets a user by field.
*
* This function works like
* [`get_user_by()`](https://developer.wordpress.org/reference/functions/get_user_by/), but
* returns a `Timber\User` object.
*
* @api
* @since 2.0.0
* @example
* ```php
* // Get a user by email.
* $user = Timber::get_user_by( 'email', 'user@example.com' );
*
* // Get a user by login.
* $user = Timber::get_user_by( 'login', 'keanu-reeves' );
* ```
*
* @param string $field The name of the field to retrieve the user with. One of: `id`,
* `ID`, `slug`, `email` or `login`.
* @param int|string $value The value to search for by `$field`.
*
* @return \Timber\User|null
*/
public static function get_user_by( string $field, $value ) {
$wp_user = get_user_by($field, $value);
if ($wp_user === false) {
return false;
}
return static::get_user($wp_user);
}
/* Menu Retrieval
================================ */
/**
* Gets a nav menu object.
*
* @api
* @since 2.0.0
* @example
* ```php
* // Get a menu by location
* $menu = Timber::get_menu( 'primary-menu' );
*
* // Get a menu by slug
* $menu = Timber::get_menu( 'my-menu' );
*
* // Get a menu by name
* $menu = Timber::get_menu( 'Main Menu' );
*
* // Get a menu by ID (term_id)
* $menu = Timber::get_menu( 123 );
* ```
*
* @param int|string $ident A menu identifier: a term_id, slug, menu name, or menu location name
* @param array $options An associative array of options. Currently only one option is
* supported:
* - `depth`: How deep down the tree of menu items to query. Useful if you only want
* the first N levels of items in the menu.
*
* @return \Timber\Menu|false
*/
public static function get_menu( $ident = null, array $options = [] ) {
$factory = new MenuFactory();
return $factory->from($ident, $options);
}
/**
* @todo implement PagesMenuFactory
*/
public static function get_pages_menu( array $pages = [], array $options = [] ) {
$menu = new Menu( $pages, $options );
$menu->init_as_page_menu();
return $menu;
}
/* Comment Retrieval
================================ */
/**
* Get comments.
* @api
* @param array $query
* @param array $options optional; none are currently supported
* @return mixed
*/
public static function get_comments( array $query = [], array $options = [] ) : Iterable {
$factory = new CommentFactory();
// TODO return a Collection type?
return $factory->from($query);
}
/**
* Get comment.
* @api
* @param int|\WP_Comment $comment
* @return \Timber\Comment|null
*/
public static function get_comment( $comment ) {
$factory = new CommentFactory();
return $factory->from($comment);
}
/* Site Retrieval
================================ */
/**
* Get sites.
* @api
* @param array|bool $blog_ids
* @return array
*/
public static function get_sites( $blog_ids = false ) {
if ( !is_array($blog_ids) ) {
global $wpdb;
$blog_ids = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs ORDER BY blog_id ASC");
}
$return = array();
foreach ( $blog_ids as $blog_id ) {
$return[] = new Site($blog_id);
}
return $return;
}
/* Template Setup and Display
================================ */
/**
* Get context.
* @api
* @deprecated 2.0.0, use `Timber::context()` instead.
*
* @return array
*/
public static function get_context() {
Helper::deprecated( 'get_context', 'context', '2.0.0' );
return self::context();
}
/**
* Gets the global context.
*
* The context always contains the global context with the following variables:
*
* - `site` – An instance of `Timber\Site`.
* - `request` - An instance of `Timber\Request`.
* - `theme` - An instance of `Timber\Theme`.
* - `user` - An instance of `Timber\User`.
* - `http_host` - The HTTP host.
* - `wp_title` - Title retrieved for the currently displayed page, retrieved through
* `wp_title()`.
* - `body_class` - The body class retrieved through `get_body_class()`.
*
* The global context will be cached, which means that you can call this function again without
* losing performance.
*
* Additionally to that, the context will contain template contexts depending on which template
* is being displayed. For archive templates, a `posts` variable will be present that will
* contain a collection of `Timber\Post` objects for the default query. For singular templates,
* a `post` variable will be present that that contains a `Timber\Post` object of the `$post`
* global.
*
* @api
* @since 2.0.0
*
* @param array $extra any extra data to merge in. Overrides whatever is
* already there for this call only. In other words, the underlying context
* data is immutable and unaffected by passing this param.
* @return array An array of context variables that is used to pass into Twig templates through
* a render or compile function.
*/
public static function context(array $extra = []) {
$context = self::context_global();
if ( is_singular() ) {
$context['post'] = Timber::get_post()->setup();
} elseif ( is_archive() || is_home() ) {
$context['posts'] = Timber::get_posts();
}
return array_merge( $context, $extra );
}
/**
* Gets the global context.
*
* This function is used by `Timber::context()` to get the global context. Usually, you don’t
* call this function directly, except when you need the global context in a partial view.
*
* The global context will be cached, which means that you can call this function again without
* losing performance.
*
* @api
* @since 2.0.0
* @example
* ```php
* add_shortcode( 'global_address', function() {
* return Timber::compile(
* 'global_address.twig',
* Timber::context_global()
* );
* } );
* ```
*
* @return array An array of global context variables.
*/
public static function context_global() {
if ( empty( self::$context_cache ) ) {
self::$context_cache['site'] = new Site();
self::$context_cache['request'] = new Request();
self::$context_cache['theme'] = self::$context_cache['site']->theme;
self::$context_cache['user'] = is_user_logged_in() ? static::get_user() : false;
self::$context_cache['http_host'] = URLHelper::get_scheme() . '://' . URLHelper::get_host();
self::$context_cache['wp_title'] = Helper::get_wp_title();
self::$context_cache['body_class'] = implode( ' ', get_body_class() );
/**
* Filters the global Timber context.
*
* By using this filter, you can add custom data to the global Timber context, which
* means that this data will be available on every page that is initialized with
* `Timber::context()`.
*
* Be aware that data will be cached as soon as you call `Timber::context()` for the
* first time. That’s why you should add this filter before you call
* `Timber::context()`.
*
* @see \Timber\Timber::context()
* @since 0.21.7
* @example
* ```php
* add_filter( 'timber/context', function( $context ) {
* // Example: A custom value
* $context['custom_site_value'] = 'Hooray!';
*
* // Example: Add a menu to the global context.
* $context['menu'] = new \Timber\Menu( 'primary-menu' );
*
* // Example: Add all ACF options to global context.
* $context['options'] = get_fields( 'options' );
*
* return $context;
* } );
* ```
* ```twig
* <h1>{{ custom_site_value|e }}</h1>
*
* {% for item in menu.items %}
* {# Display menu item #}
* {% endfor %}
*
* <footer>
* {% if options.footer_text is not empty %}
* {{ options.footer_text|e }}
* {% endif %}
* </footer>
* ```
*
* @param array $context The global context.
*/
self::$context_cache = apply_filters( 'timber/context', self::$context_cache );