skip to Main Content

How can redirect the users whenever they trying to edit a post from the frontend to /$post-type/$post-id/edit

2

Answers


  1. Chosen as BEST ANSWER

    I've found an answer by using the

    add_rewrite_rule()
    

    example:

    add_action('init', function() {
      add_rewrite_rule(
          'checklists/([a-z0-9-]+)/(edit)/?$',
          'index.php?checklist_slug=$matches[1]&checklist_action=$matches[2]',
          'top'
      );
    });
    

    and then pass the parameters to the query_var by applying a filter using query_var hook

    add_filter('query_vars', function( $query_vars ) {
      $query_vars[] = "checklist_slug";
      $query_vars[] = "checklist_action";
      return $query_vars;
    });
    

    and lastly, assign a custom template to the query_var using the template_include hook

    add_action( 'template_include', function( $template ) {
      if ( (get_query_var( 'checklist_slug' ) == false || get_query_var( 'checklist_slug' ) == '') && (get_query_var( 'checklist_action' ) == false || get_query_var( 'checklist_action' ) == '')) {
          return $template;
      }
      if ( get_query_var( 'checklist_action' ) == 'edit' ) {
        return get_template_directory() . '/includes/checklist_edit.php';
      } 
      if ( get_query_var( 'checklist_action' ) == 'new-checklist' ) {
        return get_template_directory() . '/includes/checklist_create.php';
      }
    });
    

    WordPress documentaion: add_rewrite_rule()

    if you have a better solution please share it here with us <3 have a nice day


  2. You mean like this?

    global $post;
    $type = $post->post_type;
    $id = $post->ID;
    echo '<a href="/' . $type . '/' . $id . '/edit' . '">Edit post</a>';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search