1. Home
  2. Docs
  3. Filters & Hooks
  4. How to set custom permalinks programatically?

How to set custom permalinks programatically?

Permalink Manager provides a few useful API functions that could be used to save/update the custom permalink programatically.

Most importantly, you will need to provide the custom permalink value. It can be either a default URI based on your current permastructures settings or a different string generated with your code snippet.

How to generate the default URI (optional)?

Please skip this step, if you would like to set the custom permalink with your own code.

To generate the custom permalink based on your current permastructures settings you will need to use a single function:

  • Permalink_Manager_URI_Functions_Post::get_default_post_uri() for posts
  • Permalink_Manager_URI_Functions_Term::get_default_term_uri() for terms

As you can see below, only one argument is needed ($post or $term). You can use either the full object (WP_Post() or WP_Term()) or just its ID (as integer)

// A. [Posts, Pages, CPT items]
$new_uri = Permalink_Manager_URI_Functions_Post::get_default_post_uri($post);

// B. [Categories, Tags, custom taxonomy terms]
$new_uri = Permalink_Manager_URI_Functions_Tax::get_default_term_uri($term);

How to save the default URI in the database?

Now, when the variable with new URI is set you will need to save it in the custom permalinks array. To do so you will need to use Permalink_Manager_URI_Functions::save_single_uri() function.

Permalink_Manager_URI_Functions::save_single_uri($post_or_term_id, $new_uri, $is_term, $save_in_database);

The function requires four arguments:

  • $post_or_term_id (integer)
    ID of affected post/term
  • $new_uri (string)
    a new custom permalink
  • $is_term (bool)
    set “true” for posts, “false” for terms
  • $save_in_database (bool)
    set “true

Full example

 * A. [Save Posts, Pages, CPT items permalinks]
$post = ...
$post_id = ...

// A1. Generate the URI (optional)
$new_uri = Permalink_Manager_URI_Functions_Post::get_default_post_uri($post);

// A2. Save the URI in DB
Permalink_Manager_URI_Functions::save_single_uri($post_id, $new_uri, false, true);

 * B. [Save Categories, Tags, custom taxonomy terms permalinks]
$term = ...
$term_id = ...

// B1. Generate the URI (optional)
$new_uri = Permalink_Manager_URI_Functions_Tax::get_default_term_uri($term);

// B2. Save the URI in DB
Permalink_Manager_URI_Functions::save_single_uri($term_id, $new_uri, true, true);