0

I'm trying to add a couple of custom urls in my plugin.

However, it keeps showing 404 Not Found when I access them.

I'm not sure what I've done wrong here. Can somebody show me to the right direction?

/**
 * 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' );

Here is my class_gs_mls_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
  • did you regenerate permalinks by flushing them/resaving?
    – Tom J Nowell
    Commented Jul 4, 2018 at 21:11

1 Answer 1

1

You need to call custom_urls_rules() directly in your activation function to add the rules. The init action doesn't happen in the context of plugin activation, so the rules never get added before the flush.

The other filter and action also don't need to happen on activation, they just need to be hooked on all subsequent requests.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.