Как создать пользовательскую постоянную ссылку на плагин


Я написал простой плагин , который перенаправит пользователей на страницу в определенную дату. (в данном случае это для отключения электричества против SOPA здесь, в США)

Прямо сейчас я использую строку wp_redirect(plugins_url( 'simple-sopa-blackout/blackout.php'),302 ); для перенаправления пользователей на указанную дату.

Проблема в том, что это создает неприятный URL-адрес, такой как http://example.net/wp-content/plugins/simple-blackout/blackout.php Было бы здорово просто сделать это http://example.net/blackout

Я следовал тому, что я считал правильным кодексом Я попробовал это:

add_filter( 'rewrite_rules_array','my_insert_rewrite_rules' );
add_action( 'wp_loaded','my_flush_rules' );

// flush_rules() if our rules are not yet included
function my_flush_rules(){
    $rules = get_option( 'rewrite_rules' );

    if ( ! isset( $rules['blackout/?$'] ) ) {
        global $wp_rewrite;
        $wp_rewrite->flush_rules();
    }
}

// Adding a new rule
function my_insert_rewrite_rules( $rules )
{
    $newrules = array();
    $newrules['blackout/? $'] = plugins_url( 'simple-sopa-blackout/blackout.php');
    return $newrules + $rules;
}

Любая помощь было бы здорово, полный источник здесь

ИЗМЕНИТЬ:

Вот что у меня есть сейчас, это работает, если получить доступ к странице с запросом vars index.php?blackout=stop-sopa, но не если я перейду к blackout/stop-sopa, также кажется, что создается цикл и время ожидания, если дата верна

    //create your rewrite rule
add_action( 'init', 'wpse38978_init' );

function wpse38978_init() {
     add_rewrite_rule('blackout/(\d*)$', 'index.php?blackout=$matches[1]', 'top');
}

// add blackout to the whitelist of variables it wordpress knows and allows
function my_plugin_query_vars($query_vars) {
    $query_vars[] = 'blackout';
    return $query_vars;
}
add_filter('query_vars', 'my_plugin_query_vars');


function my_plugin_parse_request($wp) {
    if (array_key_exists('blackout', $wp->query_vars) 
            && $wp->query_vars['blackout'] == 'stop-sopa') {
        include( dirname( __FILE__ ) . '/blackout.php' );
exit();
    }

}
add_action('parse_request', 'my_plugin_parse_request');

if(!function_exists('wp_redirect')) { 
    require(ABSPATH . WPINC . '/pluggable.php');
}

$current_time =  current_time('mysql', '0'); //get current blog time
$ts =strtotime($current_time); //parse the sql blog time to a php useable format
$check_date = date('m/d/Y', $ts);  // put the date in a format we can check
$check_hour = date('H', $ts);  // put the date in a format we can check
$blackout_day = "01/15/2012"; // should we black out the site?
$blackout_day_time_start = "08"; // when should we start (hour in 24 hour format)
$blackout_day_time_end = "20"; // should we black out the site?

if((!is_admin()) && ($check_date == $blackout_day && ($check_hour >= $blackout_day_time_start || $check_hour < $blackout_day_time_end))){
    wp_redirect(get_bloginfo('url').'/blackout/stop-sopa',302 );
      exit();

}
Author: Brooke., 2012-01-15

2 answers

Я думаю, что этот ответ мог бы вам помочь. Создайте пользовательский шаблон страницы в своем плагине, а затем создайте страницу с этим шаблоном под названием Blackout и перенаправьте пользователей в плагине на эту страницу.

Помощь от: Создание пользовательских шаблонов страниц с помощью плагинов?

Редактирование с помощью примера кода:

Допустим, у вас есть страница под названием Blackout, слизняк blackout.

add_filter( 'page_template', 'your_custom_page_template' );
function your_custom_page_template( $page_template ) {

    if ( is_page( 'blackout' ) ) {
        $page_template = plugin_dir_path( __FILE__ ) . 'your-custom-page-template.php';
    }

    return $page_template;
}

До тех пор, пока вы можете заставить перенаправление работать должным образом, когда это необходимо, этот приведенный выше код должен работайте совместно с ним, чтобы отображать шаблон страницы при каждом посещении этой страницы. Теперь вы можете настроить your-custom-page-template.php или как бы вы его ни называли, из папки плагинов вместо темы.

Редактировать, у меня это работает:

function blackout_redirect(){
    $page = get_page_by_path( 'blackout' );

    if( isset( $page ) && !is_null( $page ) ) {
        if( !is_page( 'blackout' ) && !is_admin() /* && $check_date stuff */ ) {
            wp_redirect( get_permalink( $page->ID ), 302 ); exit;   
        }
    }
}
add_action( 'wp', 'blackout_redirect' );

function blackout_template() {

    if( is_page( 'blackout' ) ) {
        include plugin_dir_path( __FILE__ ) . 'blackout.php'; exit;
    }

}
add_filter( 'template_redirect', 'blackout_template' );

В теме "Двадцать одиннадцать" активна только пара других плагинов.

 1
Author: Jared, 2017-04-13 12:37:54

Попробуйте следующее: (URL-адрес должен быть http://site.com/blackout/anti-sopa)

//create your rewrite rule
add_action( 'init', 'wpse38978_init' );
function wpse38978_init() {
     add_rewrite_rule('blackout/(\d*)$', 'index.php?blackout=$matches[1]', 'top');
}

// add blackout to the whitelist of variables it wordpress knows and allows
add_action( 'query_vars', 'wpse6891_query_vars' );
function wpse38978_query_vars( $query_vars )
{
    $query_vars[] = 'blackout';
    return $query_vars;
}

// If this is done, we can access it later
// This example checks very early in the process:
// if the variable is set, we include our page and stop execution after it
add_action( 'parse_request', 'wpse38978_parse_request' );
function wpse6891_parse_request( &$wp ){
    if ( array_key_exists( 'blackout', $wp->query_vars ) &&  $wp->query_vars['blackout'] == 'anti-sopa') {
        include( dirname( __FILE__ ) . '/blackout.php' );
        exit();
    }
}


if(!function_exists('wp_redirect')) { 
    require(ABSPATH . WPINC . '/pluggable.php');
}

$current_time =  current_time('mysql', '0'); //get current blog time
$ts =strtotime($current_time); //parse the sql blog time to a php useable format
$check_date = date('m/d/Y', $ts);  // put the date in a format we can check
$check_hour = date('H', $ts);  // put the date in a format we can check
$blackout_day = "01/18/2012"; // should we black out the site?
$blackout_day_time_start = "08"; // when should we start (hour in 24 hour format)
$blackout_day_time_end = "20"; // should we black out the site?

if((!is_admin()) && ($check_date == $blackout_day &&($check_hour >= $blackout_day_time_start || $check_hour < $blackout_day_time_end))){
      wp_redirect(get_bloginfo('url').'/blackout/anti-sopa',302 );
      exit();

}
 1
Author: Bainternet, 2012-01-15 12:50:39