How do I read values (PHP defined constants) from wp-config.php?

I would just include the file then I would have access to the variable in it varibales.

<?php
  require_once('wp-config.php');
  echo DB_NAME;
?>

This is assuming you're on the same server and you can access wp-config.php through the file system.

If you're doing this for a plugin, these values are already available. You won't need to include the file again.


I have even defined my own constants in in wp-config.php and managed to retrieve them in theme without any includes.

wp-config.php

define('DEFAULT_ACCESS', 'employee');

functions.php

echo "DEFAULT_ACCESS :".DEFAULT_ACCESS;

outputs DEFAULT_ACCESS :employee


Here's some same code.

// ...Call the database connection settings
require( path to /wp-config.php );

// ...Connect to WP database
$dbc = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if ( !$dbc ) {
    die( 'Not Connected: ' . mysql_error());
}
// Select the database
$db = mysql_select_db(DB_NAME);
if (!$db) {
    echo "There is no database: " . $db;
}

// ...Formulate the query
$query = "
    SELECT *
    FROM `wp_posts`
    WHERE `post_status` = 'publish'
    AND `post_password` = ''
    AND `post_type` = 'post'
    ";

// ...Perform the query
$result = mysql_query( $query );

// ...Check results of the query and terminate the script if invalid results
if ( !$result ) {
    $message = '<p>Invalid query.</p>' . "\n";
    $message .= '<p>Whole query: ' . $query ."</p> \n";
    die ( $message );
}

// Init a variable for the number of rows of results
$num_rows = mysql_num_rows( $result );

// Print the number of posts
echo "$num_rows Posts";

// Free the resources associated with the result set
if ( $result ) {
    mysql_free_result( $result );
    mysql_close();
}

You can get all the global constants from wp-config.php simply echo the const like that:

<?php
  echo DB_HOST;
  echo DB_NAME;
  echo DB_USER;
  echo DB_PASSWORD;