File is outside WordPress Scope after enqueue

Viewed 21

I got a file that includes some CSS but its extension is .php because I need to write PHP inside it, let's called this file styling.php. I enqueue styling.php in the main PHP file called main.php inside the plugin folder with the hook wp_enqueue_scripts.

Inside the styling.php, I need to use the $wpdb but the file is outside the WordPress scope because it's already enqueued to the frontend, therefore the $wpdb won't work (undefined).

The only way I could think of is to manually include the wp-config.php inside the styling.php, but I have read many articles that say this is a bad practice for calling WordPress instead of WordPress calling the plugin like here: https://wordpress.stackexchange.com/questions/159347/best-way-to-include-wp-config-php

But I couldn't think of a better way, is there any better solution?

For reference, here is the code for main.php:

add_action( 'wp_enqueue_scripts', 'styling_1' );

function styling_1() {
   wp_register_style( 'product_css', plugins_url( 'Testing/Styling/styling.php' ) );
   wp_enqueue_style( 'product_css' );
}

Here is the code for styling.php:

<?php
$table_name = $wpdb->prefix . 'newdata';
$results = $wpdb->get_var($wpdb->prepare("SELECT name FROM $table_name WHERE id = 1"));

header("Content-type: text/css; charset: UTF-8");
?>

.single_button {
   background-color: <?php echo $results; ?>;
}
0 Answers
Related