1

I have a control/setting in my WordPress Customizer that takes an address input by the user and enters it into the url of a Google Map embeded on the page. I'm using esc_html to convert the address (Example: 123 Main Street) into the proper format (Example: 123%20Main%20Street) but it's also prepending http:// before it, which I do not need in this case. How do I remove the http://?

This is the code I have in my template file:

<?php echo esc_url( get_theme_mod( 'address' , __( '123 Main Street', 'myTheme' ) )); ?>

This is the code I have in my customizer.php:

$wp_customize->add_setting( 'address', array(
    'default'           => __( '123 Main Street', 'myTheme' ), 
) );    
$wp_customize->add_control( 'address', array(
    'label'             => __( 'Address', 'myTheme' ),
    'type'              => 'text',
    'section'           => 'map'
) );
Troy Templeman
  • 275
  • 1
  • 14
  • Possible duplicate of [How to properly URL encode a string in PHP?](http://stackoverflow.com/questions/4744888/how-to-properly-url-encode-a-string-in-php) – Alexander O'Mara Dec 10 '16 at 23:13
  • 1
    I don't have much experience with wordpress, but after reading the documentation, it looks like `esc_url` returns an escaped URL afterwards. If that's the case, are you able to just remove the `http://` from the URL? `substr("http://123%20Main%20Street", 7);`. You could also, if possible and fits your needs, encode the text to be used in a URL rather than using Wordpress's built in function: `rawurlencode("123 Main Street");` – robere2 Dec 10 '16 at 23:18
  • @bugfroggy `rawurlencode` worked beautifully. If you want to put it in as an answer I'll gladly accept it as the correct answer. Thanks! – Troy Templeman Dec 10 '16 at 23:21

1 Answers1

2

There's two options you could use here: urlencode() and rawurlencode().

urlencode():

Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs.

rawurlencode():

Returns a string in which all non-alphanumeric characters except -_.~ have been replaced with a percent (%) sign followed by two hex digits.

Therefore, urlencode("123 Main Street") will return 123+Main+Street and rawurlencode("123 Main Street") will return 123%20Main%20Street. Choose whichever is best for you.

If it is necessary to use esc_url() as provided from WordPress, you could also just remove the http:// from the string using substr("http://123%20Main%20Street", 7);. In this case, it will return an identical string to rawurlencode().

robere2
  • 1,689
  • 2
  • 16
  • 26