-
Notifications
You must be signed in to change notification settings - Fork 0
/
kntnt-category-blog-urls.php
64 lines (50 loc) · 2 KB
/
kntnt-category-blog-urls.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
<?php
/**
* @wordpress-plugin
* Plugin Name: Kntnt Category Blog URLs
* Plugin URI: https://github.com/Kntnt/kntnt-blog-url
* Description: Changes the URL structure of a category with the slug `blog`. Remember to flush permalinks (e.g. by just visiting the permalink settings) after activating or deactivating this plugin.
* Version: 1.0.1
* Author: Thomas Barregren
* Author URI: https://www.kntnt.com/
* License: GPL-3.0+
* License URI: http://www.gnu.org/licenses/gpl-3.0.txt
*/
namespace Kntnt\Category_Blog_URLs;
defined( 'ABSPATH' ) && new Plugin;
class Plugin {
public function __construct() {
add_filter( 'term_link', [ $this, 'blog_link' ], 10, 3 );
add_filter( 'post_link', [ $this, 'blog_post_link' ], 10, 3 );
add_action( 'generate_rewrite_rules', [ $this, 'rewrite_rules' ] );
}
public function blog_link( $permalink, $term, $taxonomy ) {
if ( ! empty( $category_slug = $term->slug ) && $category_slug == 'blog' ) {
$permalink = $this->blog_url();
}
return $permalink;
}
public function blog_post_link( $permalink, $post, $leavename ) {
if ( ! empty( $category = get_the_category( $post->ID ) ) && $category[0]->slug == 'blog' ) {
$permalink = $this->blog_url( "{$post->post_name}/{$post->ID}" );
}
return $permalink;
}
public function rewrite_rules( $wp_rewrite ) {
$new_rules['^investors/(blog)/?$'] = 'index.php?category_name=$matches[1]';
$new_rules['^investors/(blog)/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
$new_rules['^investors/(blog)/[^/]+/(\d+)/?$'] = 'index.php?p=$matches[2]';
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
return $wp_rewrite;
}
private function blog_url( $slug = '' ) {
$path = '/investors/blog';
if ( $slug ) {
$path = "$path/$slug";
}
if ( substr( get_option( 'permalink_structure' ), - 1 ) == '/' ) {
$path = "$path/";
}
return home_url( $path );
}
}