PluginProbe
WPJAM Basic / trunk
WPJAM Basic vtrunk
wpjam-basic / extends / 301-redirects.php

301-redirects.php in WPJAM Basic trunk, at extends/301-redirects.php

74 lines 2.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /*
3 Name: 链接跳转
4 URI: https://mp.weixin.qq.com/s/e9jU49ASszsY95TrmT34TA
5 Description: 链接跳转扩展支持设置跳转规则来实现链接跳转。
6 Version: 2.0
7 */
8 class WPJAM_Redirect extends WPJAM_Model{
9 public static function get_handler(){
10 return wpjam_get_handler([
11 'primary_key' => 'id',
12 'option_name' => 'wpjam-links',
13 'items_field' => 'redirects',
14 'max_items' => 50
15 ]);
16 }
17
18 public static function get_fields($action_key='', $id=0){
19 if($action_key == 'update_setting'){
20 return [
21 'redirect_view' => ['type'=>'view', 'value'=>'默认只在404页面支持跳转,开启下面开�
22 �后,所有页面都支持跳转'],
23 'redirect_all' => ['class'=>'switch', 'label'=>'所有页面都支持跳转'],
24 ];
25 }
26
27 return [
28 'type' => ['title'=>'匹�
29 �设置', 'class'=>'switch', 'label'=>'使用正则匹�
30 �'],
31 'request' => ['title'=>'原地址', 'type'=>'url', 'required', 'show_admin_column'=>true],
32 'destination' => ['title'=>'目标地址', 'type'=>'url', 'required', 'show_admin_column'=>true],
33 ];
34 }
35
36 public static function add_hooks(){
37 add_action('template_redirect', function(){
38 $url = wpjam_get_current_page_url();
39
40 if(is_404()){
41 str_contains($url, ($k = 'feed/atom/')) && wp_redirect(str_replace($k, '', $url)) && exit;
42
43 $k = array_find(['page/', 'comment-page-'], fn($k)=> str_contains($url, $k));
44 $k && wp_redirect(wpjam_preg_replace('/'.preg_quote($k, '/').'(.*)\//', '', $url)) && exit;
45 }
46
47 if(is_404() || self::get_setting('redirect_all')){
48 foreach(self::parse_items() as $redirect){
49 $r = $redirect['request'] ?? '';
50 $d = $redirect['destination'] ?? '';
51
52 if($r && $d){
53 $r = set_url_scheme($r);
54 $d = !empty($redirect['type']) ? preg_replace('#'.$r.'#', $d, $url) : ($r == $url ? $d : '');
55
56 $d && $d != $url && wp_redirect($d, 301) && exit;
57 }
58 }
59 }
60 }, 99);
61 }
62 }
63
64 wpjam_add_menu_page('redirects', [
65 'plugin_page' => 'wpjam-links',
66 'title' => '链接跳转',
67 'summary' => __FILE__,
68 'function' => 'list',
69 'model' => 'WPJAM_Redirect',
70 'list_table' => ['title'=>'跳转规则', 'plural'=>'redirects', 'singular'=>'redirect', 'update_setting'=>true]
71 ]);
72
73
74