How can I get a link path to use for my resources such as JS scripts?

This is kind of a hacky way to do this; but unfortunately, there is not a WP function that will do both (theme and/or plugin). It’s only an either/or proposition.

On the surface, you’d think it wouldn’t be difficult. You could just get the path and compare it with the site URL or something like that. But you run into problems when WP is installed somewhere other than the root (such as in a directory).

If you look at my setup in the function, the “else” condition is the simple. If WP was always in the root, that would be all you need to do. Everything else is done to handle the other possibility (that WP is in a directory – or lower).

In that case, it explodes the site URL to determine if there is more than just the root domain (an array bigger than 3). If so, it loops through the parts of the URL we got from the explode() process. We can skip the first three elements of the array as those should be the root of the domain (https://example.com). Then it builds the path (in case it’s more than just one directory below).

Using that it strips out everything below the root URL so you get just a clean URL you can use. Then it appends the path to the file.

function my_get_file_url_path() {

    // Account for WP being installed in a directory.
    $path_info = '';
    $site_url  = site_url();
    $url_parts = explode( "https://wordpress.stackexchange.com/", $site_url );

    if ( array_count_values( $url_parts ) > 3 ) {
        $x = 0;
        foreach ( $url_parts as $this_part ) {
            if ( $x > 2 ) {
                $path_info = $this_part . "https://wordpress.stackexchange.com/";
            }
            $x++;
        }

        $site_actual_url = str_replace( $path_info, '', trailingslashit( $site_url ) );

        return $site_actual_url . trim( str_replace( $_SERVER['DOCUMENT_ROOT'], '', __DIR__ ), "https://wordpress.stackexchange.com/" );

    } else {
        return str_replace( $_SERVER['DOCUMENT_ROOT'], $site_url, __DIR__ );
    }
}