forked from vthierry/wordpress-add-meta-tags
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathamt-utils.php
4433 lines (3784 loc) · 171 KB
/
amt-utils.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
/**
* This file is part of the Add-Meta-Tags distribution package.
*
* Add-Meta-Tags is an extension for the WordPress publishing platform.
*
* Homepage:
* - http://wordpress.org/plugins/add-meta-tags/
* Documentation:
* - http://www.codetrax.org/projects/wp-add-meta-tags/wiki
* Development Web Site and Bug Tracker:
* - http://www.codetrax.org/projects/wp-add-meta-tags
* Main Source Code Repository (Mercurial):
* - https://bitbucket.org/gnotaras/wordpress-add-meta-tags
* Mirror repository (Git):
* - https://github.com/gnotaras/wordpress-add-meta-tags
* Historical plugin home:
* - http://www.g-loaded.eu/2006/01/05/add-meta-tags-wordpress-plugin/
*
* Licensing Information
*
* Copyright 2006-2013 George Notaras <gnot@g-loaded.eu>, CodeTRAX.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* The NOTICE file contains additional licensing and copyright information.
*/
/**
* Module containing utility functions.
*/
// Prevent direct access to this file.
if ( ! defined( 'ABSPATH' ) ) {
header( 'HTTP/1.0 403 Forbidden' );
echo 'This file should not be accessed directly!';
exit; // Exit if accessed directly
}
// Returns the post object filtered.
// In addition see this: https://github.com/Automattic/amp-wp/commit/21180205487d71e595088e2cd1d1acba3f240ea5
function amt_get_queried_object() {
// Sometimes, it is possible that a post object (static WP Page), which behaves
// like a custom post type archive (eg the WooCommerce main shop page -- slug=shop)
// has been set as the static front page.
// In such cases the get_queried_object() function may not return a regular
// WP_Post object, which is required by this plugin. So, in such cases we
// retrieve the WP_Post object manually.
if ( amt_is_static_front_page() && is_post_type_archive() ) {
$post = get_post( amt_get_front_page_id() );
} else {
// Use the normal way to get the $post object.
// Get current post object
$post = get_queried_object();
}
// Allow filtering of the $post object.
$post = apply_filters('amt_get_queried_object', $post);
return $post;
}
// Returns the plugin options
function amt_get_options() {
return get_option("add_meta_tags_opts");
}
// Returns a key for the non persistent cache
function amt_get_amtcache_key($basename, $post=null) {
// Non persistent object cache
if ( is_null($post) ) { // other data
$amtcache_key = sprintf('%s_data', $basename);
} elseif ( is_numeric($post) ) { // id
$amtcache_key = sprintf('%s_%d', $basename, $post);
} elseif ( isset($post->ID) ) { // post, user
$amtcache_key = sprintf('%s_%d', $basename, $post->ID);
} elseif ( isset($post->term_id) ) { // term
$amtcache_key = sprintf('%s_%d', $basename, $post->term_id);
} else {
// Use a static key name. Very unlikely for the page to have two non post objects.
$amtcache_key = sprintf('%s_other_post', $basename);
}
//var_dump($post);
//var_dump($amtcache_key);
return $amtcache_key;
}
/**
* Helper function that returns an array of allowable HTML elements and attributes
* for use in wp_kses() function.
*/
function amt_get_allowed_html_kses() {
// Store supported global attributes to an array
// As of http://www.w3schools.com/tags/ref_standardattributes.asp
$global_attributes = array(
'accesskey' => array(),
'class' => array(),
'contenteditable' => array(),
'contextmenu' => array(),
// 'data-*' => array(),
'dir' => array(),
'draggable' => array(),
'dropzone' => array(),
'hidden' => array(),
'id' => array(),
'lang' => array(),
'spellcheck' => array(),
'style' => array(),
'tabindex' => array(),
'title' => array(),
'translate' => array()
);
// Construct an array of valid elements and attributes
$valid_elements_attributes = array(
// As of http://www.w3schools.com/tags/tag_meta.asp
// plus 'itemprop' and 'property'
'meta' => array_merge( array(
'charset' => array(),
'content' => array(),
'value' => array(),
'http-equiv' => array(),
'name' => array(),
'scheme' => array(),
'itemprop' => array(), // schema.org
'property' => array() // opengraph and others
), $global_attributes
),
// As of http://www.w3schools.com/tags/tag_link.asp
'link' => array_merge( array(
'charset' => array(),
'href' => array(),
'hreflang' => array(),
'media' => array(),
'rel' => array(),
'rev' => array(),
'sizes' => array(),
'target' => array(),
'type' => array()
), $global_attributes
)
);
// Allow filtering of $valid_elements_attributes
$valid_elements_attributes = apply_filters( 'amt_valid_full_metatag_html', $valid_elements_attributes );
return $valid_elements_attributes;
}
/**
* Sanitizes text for use in the description and similar metatags.
*
* Currently:
* - removes shortcodes
* - removes double quotes
* - convert single quotes to space
*/
function amt_sanitize_description($desc) {
// Remove shortcode
// Needs to be before cleaning double quotes as it may contain quoted settings.
// $pattern = get_shortcode_regex();
//var_dump($pattern);
// TODO: Possibly this is not needed since shortcodes are stripped in amt_get_the_excerpt().
// $desc = preg_replace('#' . $pattern . '#s', '', $desc);
// Clean double quotes
$desc = str_replace('"', '', $desc);
// $desc = str_replace('"', '', $desc);
// Convert single quotes to space
//$desc = str_replace("'", ' ', $desc);
//$desc = str_replace(''', ' ', $desc);
//$desc = str_replace("'", ' ', $desc);
//$desc = str_replace("‘", ' ', $desc);
//$desc = str_replace("’", ' ', $desc);
// Finally, convert double space to single space.
//$desc = str_replace(' ', ' ', $desc);
// Allow further filtering of description
$desc = apply_filters( 'amt_sanitize_description_extra', $desc );
return $desc;
}
/**
* Sanitizes text for use in the 'keywords' or similar metatags.
*
* Currently:
* - converts to lowercase
* - removes double quotes
* - convert single quotes to space
*/
function amt_sanitize_keywords( $text ) {
// Convert to lowercase
if (function_exists('mb_strtolower')) {
$text = mb_strtolower($text, get_bloginfo('charset'));
} else {
$text = strtolower($text);
}
// Clean double quotes
$text = str_replace('"', '', $text);
$text = str_replace('"', '', $text);
// Convert single quotes to space
$text = str_replace("'", ' ', $text);
$text = str_replace(''', ' ', $text);
$text = str_replace("'", ' ', $text);
// Allow further filtering of keywords
$text = apply_filters( 'amt_sanitize_keywords_extra', $text );
return $text;
}
/**
* Helper function that converts the placeholders used by Add-Meta-Tags
* to a form, in which they remain unaffected by the sanitization functions.
*
* Currently the problem is the '%ca' part of '%cats%' which is removed
* by sanitize_text_field().
*/
function amt_convert_placeholders( $data ) {
$data = str_replace('%cats%', '#cats#', $data);
$data = str_replace('%tags%', '#tags#', $data);
$data = str_replace('%terms%', '#terms#', $data);
$data = str_replace('%contentkw%', '#contentkw#', $data);
$data = str_replace('%title%', '#title#', $data);
return $data;
}
/**
* Helper function that reverts the placeholders used by Add-Meta-Tags
* back to their original form. This action should be performed after
* after the sanitization functions have processed the data.
*/
function amt_revert_placeholders( $data ) {
$data = str_replace('#cats#', '%cats%', $data);
$data = str_replace('#tags#', '%tags%', $data);
$data = str_replace('#terms#', '%terms%', $data);
$data = str_replace('#contentkw#', '%contentkw%', $data);
$data = str_replace('#title#', '%title%', $data);
return $data;
}
/**
* This function is meant to be used in order to append information about the
* current page to the description or the title of the content.
*
* Works on both:
* 1. paged archives or main blog page
* 2. multipage content
*/
function amt_process_paged( $data ) {
if ( !empty( $data ) ) {
$data_to_append = ' | Page ';
//TODO: Check if it should be translatable
//$data_to_append = ' | ' . __('Page', 'add-meta-tags') . ' ';
// Allowing filtering of the $data_to_append
$data_to_append = apply_filters( 'amt_paged_append_data', $data_to_append );
// For paginated archives or paginated main page with latest posts.
if ( is_paged() ) {
$paged = get_query_var( 'paged' ); // paged
if ( $paged && $paged >= 2 ) {
return $data . $data_to_append . $paged;
}
// For a Post or PAGE Page that has been divided into pages using the <!--nextpage--> QuickTag
} else {
$paged = get_query_var( 'page' ); // page
if ( $paged && $paged >= 2 ) {
return $data . $data_to_append . $paged;
}
}
}
return $data;
}
// Escapes the contents of a field that can accept an attachment ID (integer) and a URL
// Mainly used for 'Global Image Override' fields and 'Default_image_URL' field.
function amt_esc_id_or_url_notation( $data ) {
if ( empty($data) || is_numeric($data) ) {
return $data;
}
// Treat as URL. Split into pieaces (URL,WIDTHxHEIGHT), escape each and
// then reconstruct the data.
$parts = explode(',', $data);
if ( count($parts) == 1 ) {
// We have just the URL
return esc_url($data);
} else {
$url = $parts[0];
$dimensions = explode('x', $parts[1]);
if ( count($dimensions) != 2 ) {
return esc_url($url);
} elseif ( ! is_numeric($dimensions[0]) || ! is_numeric($dimensions[1]) ) {
return esc_url($url);
}
}
return sprintf('%s,%dx%d', esc_url($url), absint($dimensions[0]), absint($dimensions[1]));
}
// Function that cleans the content of the post
// Removes HTML markup, expands or removes short codes etc.
function amt_get_clean_post_content( $options, $post ) {
// Non persistent object cache
$amtcache_key = amt_get_amtcache_key('amt_cache_get_clean_post_content', $post);
$plain_text_processed = wp_cache_get( $amtcache_key, $group='add-meta-tags' );
if ( $plain_text_processed !== false ) {
return $plain_text_processed;
}
// Early filter that lets dev define the post. This makes it possible to
// exclude specific parts of the post for the rest of the algorithm.
// NOTE: qtranslate-X needs to pass through __() at this point.
$initial_content = apply_filters( 'amt_get_the_excerpt_initial_content', $post->post_content, $post );
// First expand the shortcodes if the relevant setting is enabled.
if ( $options['expand_shortcodes'] == '1' ) {
$initial_content = do_shortcode( $initial_content );
// Filter the initial content again after expanding the shortcodes.
$initial_content = apply_filters( 'amt_get_the_excerpt_initial_content_expanded_shortcodes', $initial_content, $post );
}
// Second strip all HTML tags
//$plain_text = wp_kses( $initial_content, array() );
// Use wp_strip_all_tags() instead of wp_kses(). The latter leave the contents
// of script/style HTML tags.
$plain_text = wp_strip_all_tags( $initial_content, true );
// Strip properly registered shortcodes
$plain_text = strip_shortcodes( $plain_text );
// Also strip any shortcodes (For example, required for the removal of Visual Composer shortcodes)
$plain_text = preg_replace('#\[[^\]]+\]#', '', $plain_text);
// Late preprocessing filter. Content has no HTML tags and no properly registered shortcodes. Other shortcodes might still exist.
$plain_text_processed = apply_filters( 'amt_get_the_excerpt_plain_text', $plain_text, $post );
// Non persistent object cache
// Cache even empty
wp_cache_add( $amtcache_key, $plain_text_processed, $group='add-meta-tags' );
return $plain_text_processed;
}
/**
* Returns the post's excerpt.
* This function was written in order to get the excerpt *outside* the loop
* because the get_the_excerpt() function does not work there any more.
* This function makes the retrieval of the excerpt independent from the
* WordPress function in order not to break compatibility with older WP versions.
*
* Also, this is even better as the algorithm tries to get text of average
* length 250 characters, which is more SEO friendly. The algorithm is not
* perfect, but will do for now.
*
* MUST return sanitized text.
*/
function amt_get_the_excerpt( $post, $excerpt_max_len=300, $desc_avg_length=250, $desc_min_length=150 ) {
$options = amt_get_options();
// Non persistent object cache
$amtcache_key = amt_get_amtcache_key('amt_cache_get_the_excerpt', $post);
$amt_excerpt = wp_cache_get( $amtcache_key, $group='add-meta-tags' );
if ( $amt_excerpt !== false ) {
return $amt_excerpt;
}
if ( empty($post->post_excerpt) || get_post_type( $post ) == 'attachment' ) { // In attachments we always use $post->post_content to get a description
// Here we generate an excerpt from $post->post_content
// Get clean content data
$plain_text_processed = amt_get_clean_post_content( $options, $post );
// Get the initial text.
// We use $excerpt_max_len characters of the text for the description.
$amt_excerpt = sanitize_text_field( amt_sanitize_description( substr($plain_text_processed, 0, $excerpt_max_len) ) );
// Remove any URLs that may exist exactly at the beginning of the description.
// This may happen if for example you put a youtube video url first thing in
// the post body.
$amt_excerpt = preg_replace( '#^https?:[^\t\r\n\s]+#i', '', $amt_excerpt );
$amt_excerpt = ltrim( $amt_excerpt );
// If this was not enough, try to get some more clean data for the description (nasty hack)
if ( strlen($amt_excerpt) < $desc_avg_length ) {
$amt_excerpt = sanitize_text_field( amt_sanitize_description( substr($plain_text_processed, 0, (int) ($excerpt_max_len * 1.5)) ) );
if ( strlen($amt_excerpt) < $desc_avg_length ) {
$amt_excerpt = sanitize_text_field( amt_sanitize_description( substr($plain_text_processed, 0, (int) ($excerpt_max_len * 2)) ) );
}
}
/** ORIGINAL ALGO
// Get the initial data for the excerpt
$amt_excerpt = strip_tags(substr($post->post_content, 0, $excerpt_max_len));
// If this was not enough, try to get some more clean data for the description (nasty hack)
if ( strlen($amt_excerpt) < $desc_avg_length ) {
$amt_excerpt = strip_tags(substr($post->post_content, 0, (int) ($excerpt_max_len * 1.5)));
if ( strlen($amt_excerpt) < $desc_avg_length ) {
$amt_excerpt = strip_tags(substr($post->post_content, 0, (int) ($excerpt_max_len * 2)));
}
}
*/
$end_of_excerpt = strrpos($amt_excerpt, ".");
if ($end_of_excerpt) {
// if there are sentences, end the description at the end of a sentence.
$amt_excerpt_test = substr($amt_excerpt, 0, $end_of_excerpt + 1);
if ( strlen($amt_excerpt_test) < $desc_min_length ) {
// don't end at the end of the sentence because the description would be too small
$amt_excerpt .= "...";
} else {
// If after ending at the end of a sentence the description has an acceptable length, use this
$amt_excerpt = $amt_excerpt_test;
}
} else {
// otherwise (no end-of-sentence in the excerpt) add this stuff at the end of the description.
$amt_excerpt .= "...";
}
} else {
// When the post excerpt has been set explicitly, then it has priority.
$amt_excerpt = sanitize_text_field( amt_sanitize_description( $post->post_excerpt ) );
// NOTE ABOUT ATTACHMENTS: In attachments $post->post_excerpt is the caption.
// It is usual that attachments have both the post_excerpt and post_content set.
// Attachments should never enter here, but be processed above, so that
// post->post_content is always used as the source of the excerpt.
}
/**
* In some cases, the algorithm might not work, depending on the content.
* In those cases, $amt_excerpt might only contain ``...``. Here we perform
* a check for this and return an empty $amt_excerpt.
*/
if ( trim($amt_excerpt) == "..." ) {
$amt_excerpt = "";
}
/**
* Allow filtering of the generated excerpt.
*
* Filter with:
*
* function customize_amt_excerpt( $amt_excerpt, $post ) {
* $amt_excerpt = ...
* return $amt_excerpt;
* }
* add_filter( 'amt_get_the_excerpt', 'customize_amt_excerpt', 10, 2 );
*/
$amt_excerpt = apply_filters( 'amt_get_the_excerpt', $amt_excerpt, $post );
// Non persistent object cache
// Cache even empty
wp_cache_add( $amtcache_key, $amt_excerpt, $group='add-meta-tags' );
return $amt_excerpt;
}
/**
* Returns a comma-delimited list of a post's terms that belong to custom taxonomies.
*/
function amt_get_keywords_from_custom_taxonomies( $post ) {
// Non persistent object cache
$amtcache_key = amt_get_amtcache_key('amt_cache_get_keywords_from_custom_taxonomies', $post);
$custom_tax_keywords = wp_cache_get( $amtcache_key, $group='add-meta-tags' );
if ( $custom_tax_keywords !== false ) {
return $custom_tax_keywords;
}
$custom_tax_keywords = '';
// Array to hold all terms of custom taxonomies.
$keywords_arr = array();
// Get the custom taxonomy names.
// Arguments in order to retrieve all public custom taxonomies
// (excluding the builtin categories, tags and post formats.)
$args = array(
'public' => true,
'_builtin' => false
);
$output = 'names'; // or objects
$operator = 'and'; // 'and' or 'or'
$taxonomies = get_taxonomies( $args, $output, $operator );
// Get the terms of each taxonomy and append to $keywords_arr
foreach ( $taxonomies as $taxonomy ) {
$terms = get_the_terms( $post->ID, $taxonomy );
if ( $terms && is_array($terms) ) {
foreach ( $terms as $term ) {
$keywords_arr[] = $term->name;
}
}
}
if ( ! empty( $keywords_arr ) ) {
$custom_tax_keywords = implode(', ', $keywords_arr);
} else {
$custom_tax_keywords = '';
}
// Non persistent object cache
// Cache even empty
wp_cache_add( $amtcache_key, $custom_tax_keywords, $group='add-meta-tags' );
return $custom_tax_keywords;
}
/**
* Returns a comma-delimited list of a post's categories.
*/
function amt_get_keywords_from_post_cats( $post ) {
// Non persistent object cache
$amtcache_key = amt_get_amtcache_key('amt_cache_get_keywords_from_post_cats', $post);
$postcats = wp_cache_get( $amtcache_key, $group='add-meta-tags' );
if ( $postcats !== false ) {
return $postcats;
}
$postcats = '';
foreach((get_the_category($post->ID)) as $cat) {
if ( $cat->slug != 'uncategorized' ) {
$postcats .= $cat->cat_name . ', ';
}
}
// strip final comma
$postcats = substr($postcats, 0, -2);
// Non persistent object cache
// Cache even empty
wp_cache_add( $amtcache_key, $postcats, $group='add-meta-tags' );
return $postcats;
}
/**
* Helper function. Returns the first category the post belongs to.
*/
function amt_get_first_category( $post ) {
$cats = amt_get_keywords_from_post_cats( $post );
$bits = explode(',', $cats);
if (!empty($bits)) {
return $bits[0];
}
return '';
}
/**
* Retrieves the post's user-defined tags.
*
* This will only work in WordPress 2.3 or newer. On older versions it will
* return an empty string.
*/
function amt_get_post_tags( $post ) {
// Non persistent object cache
$amtcache_key = amt_get_amtcache_key('amt_cache_get_post_tags', $post);
$posttags = wp_cache_get( $amtcache_key, $group='add-meta-tags' );
if ( $posttags !== false ) {
return $posttags;
}
$posttags = '';
if ( version_compare( get_bloginfo('version'), '2.3', '>=' ) ) {
$tags = get_the_tags($post->ID);
if ( ! empty( $tags ) ) {
foreach ( $tags as $tag ) {
$posttags .= $tag->name . ', ';
}
$posttags = rtrim($posttags, " ,");
}
}
// Non persistent object cache
// Cache even empty
wp_cache_add( $amtcache_key, $posttags, $group='add-meta-tags' );
return $posttags;
}
/**
* Returns a comma-delimited list of all the blog's categories.
* The built-in category "Uncategorized" is excluded.
*/
function amt_get_all_categories($no_uncategorized = TRUE) {
// Non persistent object cache
$amtcache_key = amt_get_amtcache_key('amt_cache_get_all_categories');
$all_cats = wp_cache_get( $amtcache_key, $group='add-meta-tags' );
if ( $all_cats !== false ) {
return $all_cats;
}
$all_cats = '';
global $wpdb;
if ( version_compare( get_bloginfo('version'), '2.3', '>=' ) ) {
$cat_field = "name";
$sql = "SELECT name FROM $wpdb->terms LEFT OUTER JOIN $wpdb->term_taxonomy ON ($wpdb->terms.term_id = $wpdb->term_taxonomy.term_id) WHERE $wpdb->term_taxonomy.taxonomy = 'category' ORDER BY name ASC";
} else {
$cat_field = "cat_name";
$sql = "SELECT cat_name FROM $wpdb->categories ORDER BY cat_name ASC";
}
$categories = $wpdb->get_results($sql);
if ( ! empty( $categories ) ) {
foreach ( $categories as $cat ) {
if ($no_uncategorized && $cat->$cat_field != "Uncategorized") {
$all_cats .= $cat->$cat_field . ', ';
}
}
$all_cats = rtrim($all_cats, " ,");
}
// Non persistent object cache
// Cache even empty
wp_cache_add( $amtcache_key, $all_cats, $group='add-meta-tags' );
return $all_cats;
}
/**
* Returns an array of the category names that appear in the posts of the loop.
* Category 'Uncategorized' is excluded.
*
* Accepts the $category_arr, an array containing the initial categories.
*/
function amt_get_categories_from_loop() {
// Non persistent object cache
$amtcache_key = amt_get_amtcache_key('amt_cache_get_categories_from_loop');
$category_arr = wp_cache_get( $amtcache_key, $group='add-meta-tags' );
if ( $category_arr !== false ) {
return $category_arr;
}
$category_arr = array();
if (have_posts()) {
while ( have_posts() ) {
the_post(); // Iterate the post index in The Loop. Retrieves the next post, sets up the post, sets the 'in the loop' property to true.
$categories = get_the_category();
if( ! empty($categories) ) {
foreach( $categories as $category ) {
if ( ! in_array( $category->name, $category_arr ) && $category->slug != 'uncategorized' ) {
$category_arr[] = $category->name;
}
}
}
}
}
rewind_posts(); // Not sure if this is needed.
// Non persistent object cache
// Cache even empty
wp_cache_add( $amtcache_key, $category_arr, $group='add-meta-tags' );
return $category_arr;
}
/**
* Returns an array of the tag names that appear in the posts of the loop.
*
* Accepts the $tag_arr, an array containing the initial tags.
*/
function amt_get_tags_from_loop() {
// Non persistent object cache
$amtcache_key = amt_get_amtcache_key('amt_cache_get_tags_from_loop');
$tag_arr = wp_cache_get( $amtcache_key, $group='add-meta-tags' );
if ( $tag_arr !== false ) {
return $tag_arr;
}
$tag_arr = array();
if (have_posts()) {
while ( have_posts() ) {
the_post(); // Iterate the post index in The Loop. Retrieves the next post, sets up the post, sets the 'in the loop' property to true.
$tags = get_the_tags();
if( ! empty($tags) ) {
foreach( $tags as $tag ) {
if ( ! in_array( $tag->name, $tag_arr ) ) {
$tag_arr[] = $tag->name;
}
}
}
}
}
rewind_posts(); // Not sure if this is needed.
// Non persistent object cache
// Cache even empty
wp_cache_add( $amtcache_key, $tag_arr, $group='add-meta-tags' );
return $tag_arr;
}
/**
* Returns an array of URLS of referenced items in the post.
*
* Accepts a post object.
*/
function amt_get_referenced_items( $post ) {
if ( is_singular() ) { // TODO: check if this check is needed at all!
$referenced_list_content = amt_get_post_meta_referenced_list( $post->ID );
if ( ! empty( $referenced_list_content ) ) {
// Each line contains a single URL. Split the string and convert each line to an array item.
$referenced_list_content = str_replace("\r", '', $referenced_list_content); // Do not change the double quotes.
return explode("\n", $referenced_list_content); // Do not change the double quotes.
}
}
return array();
}
/**
* This is a helper function that returns the post's or page's description.
*
* Important: MUST return sanitized data, unless this plugin has sanitized the data before storing to db.
*
*/
function amt_get_content_description( $post, $auto=true ) {
// Non persistent object cache
$amtcache_key = amt_get_amtcache_key('amt_cache_get_content_description', $post);
$content_description = wp_cache_get( $amtcache_key, $group='add-meta-tags' );
if ( $content_description !== false ) {
return $content_description;
}
// By default, if a custom description has not been entered by the user in the
// metabox, a description is autogenerated. To stop this automatic generation
// of a description and return only the description that has been entered manually,
// set $auto to false via the following filter.
$auto = apply_filters( 'amt_generate_description_if_no_manual_data', $auto );
$content_description = '';
if ( is_singular() || amt_is_static_front_page() || amt_is_static_home() ) { // TODO: check if this check is needed at all!
$desc_fld_content = amt_get_post_meta_description( $post->ID );
if ( !empty($desc_fld_content) ) {
// If there is a custom field, use it
$content_description = $desc_fld_content;
} else {
// Else, use the post's excerpt. Valid for Pages too.
if ($auto) {
// The generated excerpt should already be sanitized.
$content_description = amt_get_the_excerpt( $post );
}
}
}
// Non persistent object cache
// Cache even empty
wp_cache_add( $amtcache_key, $content_description, $group='add-meta-tags' );
// Allow filtering of the final description
// NOTE: qtranslate-X needs to pass through __() at this point.
$content_description = apply_filters( 'amt_get_content_description', $content_description, $post );
return $content_description;
}
/**
* This is a helper function that returns the post's or page's keywords.
*
* Important: MUST return sanitized data, unless this plugin has sanitized the data before storing to db.
*
*/
function amt_get_content_keywords($post, $auto=true, $exclude_categories=false) {
// Non persistent object cache
$amtcache_key = amt_get_amtcache_key('amt_cache_get_content_keywords', $post);
$content_keywords = wp_cache_get( $amtcache_key, $group='add-meta-tags' );
if ( $content_keywords !== false ) {
return $content_keywords;
}
// By default, if custom keywords have not been entered by the user in the
// metabox, keywords are autogenerated. To stop this automatic generation
// of keywords and return only the keywords that have been entered manually,
// set $auto to false via the following filter.
$auto = apply_filters( 'amt_generate_keywords_if_no_manual_data', $auto );
$content_keywords = '';
/*
* Custom post field "keywords" overrides post's categories, tags (tags exist in WordPress 2.3 or newer)
* and custom taxonomy terms (custom taxonomies exist since WP version 2.8).
* %cats% is replaced by the post's categories.
* %tags% is replaced by the post's tags.
* %terms% is replaced by the post's custom taxonomy terms.
*/
if ( is_singular() || amt_is_static_front_page() || amt_is_static_home() ) {
$keyw_fld_content = amt_get_post_meta_keywords( $post->ID );
// If there is a custom field, use it
if ( ! empty($keyw_fld_content) ) {
// On single posts, expand the %cats%, %tags% and %terms% placeholders.
// This should not take place in pages (no categories, no tags by default)
// or custom post types, the support of which for categories and tags is unknown.
if ( is_single() ) {
// Here we sanitize the provided keywords for safety
$keywords_from_post_cats = sanitize_text_field( amt_sanitize_keywords( amt_get_keywords_from_post_cats($post) ) );
if ( ! empty($keywords_from_post_cats) ) {
$keyw_fld_content = str_replace("%cats%", $keywords_from_post_cats, $keyw_fld_content);
}
// Also, the %tags% placeholder is replaced by the post's tags (WordPress 2.3 or newer)
if ( version_compare( get_bloginfo('version'), '2.3', '>=' ) ) {
// Here we sanitize the provided keywords for safety
$keywords_from_post_tags = sanitize_text_field( amt_sanitize_keywords( amt_get_post_tags($post) ) );
if ( ! empty($keywords_from_post_tags) ) {
$keyw_fld_content = str_replace("%tags%", $keywords_from_post_tags, $keyw_fld_content);
}
}
// Also, the %terms% placeholder is replaced by the post's custom taxonomy terms (WordPress 2.8 or newer)
if ( version_compare( get_bloginfo('version'), '2.8', '>=' ) ) {
// Here we sanitize the provided keywords for safety
$keywords_from_post_terms = sanitize_text_field( amt_sanitize_keywords( amt_get_keywords_from_custom_taxonomies($post) ) );
if ( ! empty($keywords_from_post_terms) ) {
$keyw_fld_content = str_replace("%terms%", $keywords_from_post_terms, $keyw_fld_content);
}
}
}
$content_keywords .= $keyw_fld_content;
// Otherwise, generate the keywords from categories, tags and custom taxonomy terms.
// Note:
// Here we use is_singular(), so that pages are also checked for categories and tags.
// By default, pages do not support categories and tags, but enabling such
// functionality is trivial. See #1206 for more details.
} elseif ( $auto && is_singular() ) {
/*
* Add keywords automatically.
* Keywords consist of the post's categories, the post's tags (tags exist in WordPress 2.3 or newer)
* and the terms of the custom taxonomies to which the post belongs (since WordPress 2.8).
*/
// Categories - Here we sanitize the provided keywords for safety
if ( $exclude_categories === false ) {
$keywords_from_post_cats = sanitize_text_field( amt_sanitize_keywords( amt_get_keywords_from_post_cats($post) ) );
if (!empty($keywords_from_post_cats)) {
$content_keywords .= $keywords_from_post_cats;
}
}
// Tags - Here we sanitize the provided keywords for safety
$keywords_from_post_tags = sanitize_text_field( amt_sanitize_keywords( amt_get_post_tags($post) ) );
if (!empty($keywords_from_post_tags)) {
if ( ! empty($content_keywords) ) {
$content_keywords .= ", ";
}
$content_keywords .= $keywords_from_post_tags;
}
// Custom taxonomy terms - Here we sanitize the provided keywords for safety
$keywords_from_post_custom_taxonomies = sanitize_text_field( amt_sanitize_keywords( amt_get_keywords_from_custom_taxonomies($post) ) );
if (!empty($keywords_from_post_custom_taxonomies)) {
if ( ! empty($content_keywords) ) {
$content_keywords .= ", ";
}
$content_keywords .= $keywords_from_post_custom_taxonomies;
}
}
}
// Add post format to the list of keywords
if ( $auto && is_singular() && get_post_format($post->ID) !== false ) {
if ( empty($content_keywords) ) {
$content_keywords .= get_post_format($post->ID);
} else {
$content_keywords .= ', ' . get_post_format($post->ID);
}
}
/**
* Finally, add the global keywords, if they are set in the administration panel.
*/
//if ( !empty($content_keywords) && ( is_singular() || amt_is_static_front_page() || amt_is_static_home() ) ) {
if ( $auto && ( is_singular() || amt_is_static_front_page() || amt_is_static_home() ) ) {
$options = get_option("add_meta_tags_opts");
$global_keywords = amt_get_site_global_keywords($options);
if ( ! empty($global_keywords) ) {
// If we have $content_keywords so far
if ( ! empty($content_keywords) ) {
if ( strpos($global_keywords, '%contentkw%') === false ) {
// The placeholder ``%contentkw%`` has not been used. Append the content keywords to the global keywords.
$content_keywords = $global_keywords . ', ' . $content_keywords;
} else {
// The user has used the placeholder ``%contentkw%``. Replace it with the content keywords.
$content_keywords = str_replace('%contentkw%', $content_keywords, $global_keywords);
}
// If $content_keywords have not been found.
} else {
if ( strpos($global_keywords, '%contentkw%') === false ) {
// The placeholder ``%contentkw%`` has not been used. Just use the global keywords as is.
$content_keywords = $global_keywords;
} else {
// The user has used the placeholder ``%contentkw%``, but we do not have generated any content keywords => Delete the %contentkw% placeholder.
$global_keywords_new = array();
foreach ( explode(',', $global_keywords) as $g_keyword ) {
$g_keyword = trim($g_keyword);
if ( $g_keyword != '%contentkw%' ) {
$global_keywords_new[] = $g_keyword;
}
}
if ( ! empty($global_keywords_new) ) {
$content_keywords = implode(', ', $global_keywords_new);
}
}
}
}
}
// Non persistent object cache
// Cache even empty
wp_cache_add( $amtcache_key, $content_keywords, $group='add-meta-tags' );
return $content_keywords;
}
/**
* Helper function that returns an array containing the post types that are
* supported by Add-Meta-Tags. These include:
*
* - post
* - page
* - attachment
*
* And also to ALL public custom post types which have a UI.
*
*/
function amt_get_supported_post_types() {
// Non persistent object cache
$amtcache_key = amt_get_amtcache_key('amt_cache_get_supported_post_types');
$supported_types = wp_cache_get( $amtcache_key, $group='add-meta-tags' );
if ( $supported_types !== false ) {