Quantastical Quantastical - 7 months ago 15
PHP Question

WordPress doesn't save my custom setting in permalink section

I have created many custom settings in WordPress using their Settings API, but for some reason I am having trouble with one in particular.

I want to include a custom URL shortener using WordPress's shortlink feature, so I added a custom setting to store the URL shortener's domain name. This allows it to be customizable.

function urb_admin_init_shortlink_domain()
{
$option_group = 'permalink';
$option_name = 'shortlink_domain';
$sanitize_callback = null;

register_setting( $option_group, $option_name, $sanitize_callback );

$id = 'shortlink_domain';
$title = 'Shortlink Domain';
$callback = 'urb_shortlink_domain';
$page = 'permalink';
$section = 'optional';
$args = null;

add_settings_field( $id, $title, $callback, $page, $section, $args );
}

function urb_shortlink_domain()
{
$option = 'shortlink_domain';
echo '<input type="text" name="' . $option . '" id="' . $option . '" value="' . get_option( $option ) . '" class="regular-text ltr" />';
}

add_action( 'admin_init', 'urb_admin_init_shortlink_domain' );


For some reason, it doesn't save the value. The
get_option('shortlink_domain')
function returns
false
.

Answer

Wordpress permalink settings only provide settings sections and fields but it doesn't save values custom fields same as others page like Media, Reading etc.

I think you need to another way to save custom fields values on permalink page.

Below sample code of save setting on permalink page.

add_action( 'admin_init', 'save_your_permalink_settings' );

function save_your_permalink_settings(){

  if( isset($_POST['permalink_structure']) && isset( $_POST['shortlink_domain'] ) ){

    $short_domain = wp_unslash( $_POST['shortlink_domain'] );
    update_option( 'shortlink_domain',  $short_domain );

  } 
}