Problem with dinamic add_rewrite_rule()

enter image description here

today i am trying to make a plugin for wordpress that allow change the url of a post to whatever you want, i am added a new custom field called post_permalink_replace in that custom field the user save a new slug, for example in this example thanos/fight my purpose is that the permalink of the post:

it will transform in:

http://localhost/pruebas/index.php/thanos/fight/

My problem is with the function to add the new rules

function url_replace_plugin_rewrite_rule() {

    $args = array(
        'post_type'  => 'post',
        'meta_query' => array(
            array(
                'key'     => 'post_permalink_replace',
                'compare' => 'EXISTS'
            ),
        )
    );

    $postsList = get_posts($args);

    foreach($postsList as $post) {

        $id = $post->ID;
        $link = get_post_permalink($id);
        $permalink = get_the_permalink($id);
        $site_url = trailingslashit(get_site_url());

        $link = str_replace($site_url, '', $link);
        $permalink = str_replace($site_url, '', $permalink);
        $permalink = convert_to_new_post_url($permalink, get_post_meta($id, 'post_permalink_replace', true));

        add_rewrite_rule($permalink, 'index.php' . $link,'top'); 

        debug('1. index.php' . $link);
        debug('2. ' . $permalink);
    }

    //add_rewrite_rule('(.?.+?)/type/([^/]*)/page/([0-9]{1,})/?$','index.php?pagename=$matches[1]&type=$matches[2]&paged=$matches[3]','top');    
}

add_action('init', 'url_replace_plugin_rewrite_rule', 999999);

post_permalink_replace in this example have the value: thanos/fight

this is the output of the function debug:

I have saved after create the rule in settings -> permalinks

My problem is that add_rewrite_rule require a regex in it first parameter, and a have the relative url, i dont know how cast that in a regex.

Thank you for your help,My english is no enough good, sorry if i explain my problem bad.

Read more here:: Problem with dinamic add_rewrite_rule()

Leave a Reply

Your email address will not be published. Required fields are marked *