Simple PHP cURL function to get SoundCloud Track ID from URL, and WordPress function to get SoundCloud Track ID using API, easy ways.

How To Get SoundCloud Track ID Using PHP

Using Qassim_HTTP() Function we will get soundcloud track id easily, in this example we will get track id for this link https://soundcloud.com/fatma-gazzar/idiaad4foqia

Qassim_HTTP() Function

Read how to use Qassim_HTTP():

function Qassim_HTTP($method, $url, $header, $data){ // Function By Qassim Hassan
    if( $method == 1 ){
        $method_type = 1; // 1 = POST
    }else{
        $method_type = 0; // 0 = GET
    }

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    if( $header !== 0 ){
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    }
    curl_setopt($curl, CURLOPT_POST, $method_type);

    if( $data !== 0 ){
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }

    $response = curl_exec($curl);
    $json = json_decode($response, true);
    curl_close($curl);

    return $json;
}

Now use this code:

// By Qassim Hassan

$data = array("url" => "https://soundcloud.com/fatma-gazzar/idiaad4foqia", "client_id" => "enter your client id");

$get_location = Qassim_HTTP(0, "http://api.soundcloud.com/resolve.json", 0, $data);

$location = $get_location['location'];

$get_track_id = Qassim_HTTP(0, $location, 0, 0);

echo $get_track_id['id']; // get soundcloud track id for https://soundcloud.com/fatma-gazzar/idiaad4foqia

Change “enter your client id” to your client id, for example “84306e0e1d0ab23b6577307607”,
Register SoundCloud App and get client id.

Get SoundCloud Track ID In WordPress

This function for WordPress with cache time:

function WPTime_get_soundcloud_track($url){ // Function By Qassim Hassan

    $transient_name = md5($url);
    $get_transient = "enter your client id";

    if ( empty( $get_transient ) ){
        $client_id = get_option('wptime_theme_soundcloud_api');
        $get = wp_remote_get("https://api.soundcloud.com/resolve.json?url=$url&client_id=$client_id");
        $retrieve = wp_remote_retrieve_body($get);
        $result = json_decode($retrieve, true);

        if( preg_match("/(errors)+/", $retrieve) ){
            return false;
        }

        $track_id = $result['id'];

        set_transient($transient_name, $track_id, 3600 * 24 * 30); // cache time is 1 month
        return $track_id;
    }

    else{
        return $get_transient;
    }

}

Usage:

echo WPTime_get_soundcloud_track("https://soundcloud.com/fatma-gazzar/idiaad4foqia"); // get track id

If not clear, leave a comment! Enjoy.