12

I want to use the get_option() function of wordpress in one of my theme's files, which is not related to WP, it is just located in the same directory of the other theme files. I need this file because of some extra IPN paypal related actions, but I need some values from the options table that exists in WP to be called in this page in order for it to work. I know I can't just use get_option() as this file is overlooked by wordpress. Is there any approach by including some parts of wordpress in my theme to make this functionality only work?

2
  • I retagged your question. Hint: Just take a look inside wp-load.php.
    – kaiser
    Oct 14 '12 at 19:40
  • Have you thought about getting these values out of the database using a custom mysql query? Loading the entire WordPress system for a couple of option values might be overkill. For maintainability I recommend Abdussamads answer (build it into a plugin)
    – Erik J.
    Dec 11 '17 at 19:13
10

The shortest way is to load wp-load.php and abort the loading of the template engine (Note: You couldn't do that, if you'd be loading the header file, like you see it on many sites in the interweb).

# No need for the template engine
define( 'WP_USE_THEMES', false );
# Load WordPress Core
// Assuming we're in a subdir: "~/wp-content/plugins/current_dir"
require_once( '../../../wp-load.php' );
2
7

The simplest way is include wp-load.php file. This file will loads all WP core, so you can use WP functions such as get_option in your PHP file:

include 'path/to/wp-load.php';

echo get_option( 'option_name' );
2
  • +1 But by above answer, you can delete "the simplest" ;)
    – kaiser
    Oct 14 '12 at 19:48
  • 2
    One line (including wp-load.php) vs. multiple lines (plugin comments in the beginning), that's the simplest, lol.
    – Anh Tran
    Oct 15 '12 at 1:16
4

Turn your external file into a WordPress plugin. That way you'll have full access to WP core functions.

1
  • 1
    This would make your life much easier in the long run. Oct 14 '12 at 17:31
1

This should work on any WordPress installation:

<?php
function load_wp_load() {
  $wp_did_header = true;
  require_once($_SERVER['DOCUMENT_ROOT'] . '/index.php');
  $matches = preg_grep('/wp-blog-header.php/', get_included_files());
  if (!empty($matches)) {
    $abspath = dirname(reset($matches)) . '/';
    define('ABSPATH', $abspath);
    require_once(ABSPATH . 'wp-load.php');
  }
}
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.