Run PHP Results inside WP Shortcode

If I understand correctly, you have a shortcode called wp_charts that accepts a pramaeter datasets, and you want to create a new shortcode that runs a database query and embeds the results of the query as the value of datasets?

If so, there are several ways to do this, but I think the easiest – especially if you didn’t write wp_charts yourself – is to create a new shortcode that runs the query and then calls the wp_charts shortcode.

For example:

function my_charts_with_data_shortcode_impl($atts, $content = null) {
    $sql_query = ...
    $results = $wpdb->get_results($sql_query, ARRAY_A );
    $datasets = [];
    foreach ($results as $row) {
        if (endsWith(get_site_url().''.$row['uri'], 'http://universitycompare.com/universities/the-uni-of-westminster/')) {
            $datasets[] = $row['count'];
        }
    }

    return do_shortcode('[wp_charts '.
        'title="linechart" canvaswidth="976px" canvasheight="244px" relativewidth="4" '.
        'width="976px" height="244px" type="line" align="alignright" '.
        'datasets="'. join(",",$datasets) . '"]');
}