Including WordPress in RESTful API

The credit for this answer really goes to @Wyck who correctly identified the source of the problem. Thank you very much. The reason for the problem is:

There is a variance between an import statement in the mainline code versus within a function. In WP or in in any of the plugins if variables aren’t explicitly set to global then they become locally scoped to the function they are being imported into.

It’s a shame there’s no import directive to explicitly direct variables to a particular namespace but in absence of this you can simply claim all the global variables as being “global” in the function. Using the same demonstration file from my original problem statement, this now works:

<?php
function do_that_wordpress_thing() {
    global $domain, $path, $base, $admin_page_hooks, $ajax_results, $all_links, $allowedposttags, $allowedtags, $authordata, $bgcolor, $cache_categories, $cache_lastcommentmodified, $cache_lastpostdate, $cache_lastpostmodified, $cache_userdata, $category_cache, $class, $comment, $comment_cache, $comment_count_cache, $commentdata, $current_user, $day, $debug, $descriptions, $error, $feeds, $id, $is_apache, $is_IIS, $is_macIE, $is_winIE, $l10n, $locale, $link, $m, $map, $max_num_pages, $menu, $mode, $month, $month_abbrev, $monthnum, $more, $multipage, $names, $newday, $numpages, $page, $page_cache, $paged, $pagenow, $pages, $parent_file, $preview, $previousday, $previousweekday, $plugin_page, $post, $post_cache, $post_default_category, $post_default_title, $post_meta_cache, $postc, $postdata, $posts, $posts_per_page, $previousday, $request, $result, $richedit, $single, $submenu, $table_prefix, $targets, $timedifference, $timestart, $timeend, $updated_timestamp, $urls, $user_ID, $user_email, $user_identity, $user_level, $user_login, $user_pass_md5, $user_url, $weekday, $weekday_abbrev, $weekday_initial, $withcomments, $wp, $wp_broken_themes, $wp_db_version, $wp_did_header, $wp_did_template_redirect, $wp_file_description, $wp_filter, $wp_importers, $wp_plugins, $wp_taxonomies, $wp_the_query, $wp_themes, $wp_object_cache, $wp_query, $wp_queries, $wp_rewrite, $wp_roles, $wp_similiesreplace, $wp_smiliessearch, $wp_version, $wpcommentspopupfile, $wpcommentsjavascript, $wpdb;
    global $load_sections; // for pagelines theme
    include "AddWordpress.php";
}
do_that_wordpress_thing();
$terms = get_terms("actions"); // I have a custom taxonomy named "actions"
echo json_encode($terms);

It’s also worth noting that if use autoloaders in your plugin; you should make them namespace compliant. For instance, instead of:

spl_autoload_register (  'autoloader_function_name' );

use this:

spl_autoload_register (  __NAMESPACE__ . '\\autoloader_function_name' );

Leave a Comment