PluginProbe
Yoast SEO – Advanced SEO with real-time guidance and built-in AI / 28.3
Yoast SEO – Advanced SEO with real-time guidance and built-in AI v28.3
28.5 28.4 28.3 28.2 28.1 28.0 27.9 27.8 27.7 27.6 27.5 trunk 18.0 18.1 18.2 18.3 18.4 18.4.1 18.5 18.5.1 18.6 18.7 18.8 18.9 19.0 All 129 releases
wordpress-seo / src / integrations / primary-category.php

primary-category.php in Yoast SEO – Advanced SEO with real-time guidance and built-in AI 28.3, at src/integrations/primary-category.php

74 lines 2.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Yoast\WP\SEO\Integrations;
4
5 use stdClass;
6 use WP_Error;
7 use WP_Post;
8 use WPSEO_Primary_Term;
9 use Yoast\WP\SEO\Conditionals\Primary_Category_Conditional;
10
11 /**
12 * Adds customizations to the front end for the primary category.
13 */
14 class Primary_Category implements Integration_Interface {
15
16 /**
17 * Returns the conditionals based on which this loadable should be active.
18 *
19 * In this case only when on the frontend, the post overview, post edit or new post admin page.
20 *
21 * @return array The conditionals.
22 */
23 public static function get_conditionals() {
24 return [ Primary_Category_Conditional::class ];
25 }
26
27 /**
28 * Registers a filter to change a post's primary category.
29 *
30 * @return void
31 */
32 public function register_hooks() {
33 \add_filter( 'post_link_category', [ $this, 'post_link_category' ], 10, 3 );
34 }
35
36 /**
37 * Filters post_link_category to change the category to the chosen category by the user.
38 *
39 * @param stdClass $category The category that is now used for the post link.
40 * @param array|null $categories This parameter is not used.
41 * @param WP_Post|null $post The post in question.
42 *
43 * @return array|object|WP_Error|null The category we want to use for the post link.
44 */
45 public function post_link_category( $category, $categories = null, $post = null ) {
46 $post = \get_post( $post );
47 if ( $post === null ) {
48 return $category;
49 }
50
51 $primary_category = $this->get_primary_category( $post );
52 if ( $primary_category !== false && $primary_category !== $category->cat_ID ) {
53 $category = \get_category( $primary_category );
54 }
55
56 return $category;
57 }
58
59 /**
60 * Get the id of the primary category.
61 *
62 * @codeCoverageIgnore It justs wraps a dependency.
63 *
64 * @param WP_Post $post The post in question.
65 *
66 * @return int Primary category id.
67 */
68 protected function get_primary_category( $post ) {
69 $primary_term = new WPSEO_Primary_Term( 'category', $post->ID );
70
71 return $primary_term->get_primary_term();
72 }
73 }
74