Search code examples
wordpressadvanced-custom-fields

Remove http/https for ACF URL field


I was trying the snippet below. I'm trying to remove "http" and "https" for the URL field in order to make the output look nicer, but I can't really get it working. I can't tell what is going wrong here.

<?php if ( $site = get_field( 'vendor_website' ) ) : ?>
    <?php
    $site = str_replace(array('http://', 'https://'), '', $site);
    $site = rtrim($site, '/');
    echo '<a class="vendor-link" href="' $site '">' $site 'target="_blank">' '</a>';
    ?>   
<?php endif; ?>

Solution

  • if you’re trying to just show the host of the URL, you may give parse_url a try:

    $host = parse_url( $site, PHP_URL_HOST );
    

    https://www.php.net/manual/en/function.parse-url.php

    Edit as per comments

    Let me expand the example, imagine get_field( 'vendor_website' ) returns something like https://example.org/test, and you want to just show "example.org", while leaving the link to the original URL. The code should be something like this:

    <?php if ( $site = get_field( 'vendor_website' ) ) : ?>
        <?php $host = parse_url( $site, PHP_URL_HOST ); ?>
        <a class="vendor-link" href="<?php echo $site ?>" target="_blank">
            <?php echo $host ?>
        </a>
    <?php endif; ?>