0

working on my first plugin where a user can select an option from a dropdown and this selection gets saved in a code that gets written into the footer. That works, but the problem is, my default selection (as in the HTML) gets ignored.

The selection

<select id="location_select" name="location_select">
    <option selected value="ch" <?php selected(get_option('location_select'), 'ch'); ?>><?php _e('CH', 'pluginName') ; ?></option>
    <option value="de" <?php selected(get_option('location_select'), 'de'); ?>><?php _e('DE', 'pluginName') ; ?></option>
</select>

The code

public function print_code(){
    $location   =   get_option('location_select');
    $url        =   'https://' . esc_html($location) . '.domain.com/js/script.js';
    wp_enqueue_script('myID', $url, array('jquery'), null, true);
}

public function additional_attrs($tag, $handle, $src){
    if ($handle === 'myID'){
        $tag = '<script data-host="https://domain.com" data-dnt="false" src="' . esc_url( $src ) . '" id="myID" async defer></script>';
    }
    return $tag;
}

How is it possible to have the first selection <option selected ... as a default selection in the code? Because right now, if a user does not save his selection, nothing gets written in the output code.

Thanks for any help!

1 Answer 1

0

Solved by updating the second value in get_option like

$location   =   get_option('location_select', 'ch');

Codex Reference: https://developer.wordpress.org/reference/functions/get_option

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.