添加_重写_规则不会在插件中添加自定义URL

时间:2018-07-04 作者:tdan

我正在尝试在插件中添加几个自定义URL。

然而,它一直在显示404 Not Found 当我访问它们时。

我不确定我在这里做错了什么。谁能告诉我正确的方向吗?

/**
 * The code that runs during plugin activation.
 * This action is documented in includes/class-plugin-name-activator.php
 */
function activate_gs_mls() {
    require_once plugin_dir_path( __FILE__ ) . \'includes/class-gs-mls-activator.php\';
    GS_MLS_Activator::activate();
}
register_activation_hook( __FILE__, \'activate_gs_mls\' );
这是我的class\\u gs\\u mls\\u activator。php:

class GS_MLS_Activator {

/**
 * Short Description. (use period)
 *
 * Long Description.
 *
 * @since    1.0.0
 */
public static function activate() {
    add_action(\'init\', \'GS_MLS_Activator::custom_urls_rules\');
    add_filter(\'query_vars\', \'GS_MLS_Activator::custom_query_vars\');
    add_action(\'template_redirect\', \'GS_MLS_Activator::custom_template_redirect\');

    GS_MLS_Activator::flush_rewrite_rules();
}

public static function custom_urls_rules() {
    error_log(\'Adding custom url rules\');
    // properties archive url
    add_rewrite_rule(
        \'^properties-2/?$\',
        \'index.php?pagename=my-properties\',
        \'top\'
    );

    // single property url
    add_rewrite_rule(
        \'^single-property-2/([a-zA-Z0-9]+)/?$\',
        \'index.php?pagename=single-property-2&property_id=$matches[1]\',
        \'top\'
    );
}

public static function custom_query_vars() {
    error_log(\'Adding custom query\');
    $query_vars[] = \'property_id\';
    return $query_vars;
}

public static function custom_template_redirect() {
    if(get_query_var(\'property_id\')) {
        add_filter(\'template_include\', function() {
            return  GS_MLS_PLUGIN_DIR . \'/public/partials/single-property-2.php\';
        });
    }
}

public static function flush_rewrite_rules() {
    error_log(\'Flush rewrite rule\');
    global $wp_rewrite;
    $wp_rewrite->flush_rules(true);
}

}

1 个回复
最合适的回答,由SO网友:Milo 整理而成

你需要打电话custom_urls_rules() 直接在激活功能中添加规则。这个init 操作不会在插件激活的上下文中发生,因此在刷新之前不会添加规则。

另一个过滤器和操作也不需要在激活时发生,它们只需要连接到所有后续请求。

结束