WordPress and CodeIgniter

Integrating WordPress with CodeIgniter

After a long time since my last post, I’m going to start writing again. My focus on the next articles will be CodeIgniter. The first thing I want to show is how to integrate CodeIgniter with WordPress. More precisely, I’m going to show how to use WordPress users inside CodeIginter. The motivation for this is that you won’t need to handle user authentication inside your application.

Introduction

CodeIgniter is a PHP framework with a small footprint desgned to aid the development of customized web applications. It is a MVC framework that provides the main structure in which we build our custom logics. But if you already have a WordPress website and you want to create, for example, a CRM application using CodeIgniter, it would be good to reuse some features from WordPress. One of these features is the user management. In WordPress we have user details, authentication, user levels, etc. So, in this article I’m going to show how to do this.

In this article I’m using CodeIgniter 2.0.2 and WordPress 3.2.

Preparing our CodeIgniter Application

If you haven’t downloaded CodeIgniter yet, please do it in this link. Extract the file contents to your WordPress root and rename the CodeIgniter_2.0.2 folder to your desired name. As it will be inside WordPress, it will be accessed like www.youdomain.com/wordpress/codeigniter. You need to take care of the name you choose because it may collide with WordPress categories. You may need to customise your .htaccess file in order to make your application accessible.

You probably could create your CodeIgniter application outside your WordPress folder. But you would need to customize the users cookie path in a way that WordPress functions would work.

Now let’s start coding.

WP Integration Library

There are different ways to achieve what we want. One of them would be to create a Helper file and define different functions inside that helper. The other option is to create it using the object oriented approach which requires a library file that defines a class. The last one is the option I’m going to show here. So, let’s build the library step by step.

Step 1 – File and Class Declaration

First thing we need to do is to create a new file called Wpintegration.php inside the folder application/libraries. Then we need to define our class inside this file:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
* WordPres Integration Class
*
* This class enables the use of wordpress functions
*
* @author		Oscar Dias
* @link		http://oscardias.com/codeigniter/integrating-wordpress-with-codeigniter
*/
class Wpintegration {

    //
    // Our code goes here!!!
    //

}
/* End of file Wpintegration.php */

Step 2 – Class Constructor

We are going to define a constructor for our class. This constructor will define some global variables (used by WordPress functions) and will include the wp-load.php file. This file will initiate the entire WordPress application. I left some additional variables that I found during my tests commented inside the method. I’m not sure, but I think that if you use different functions you will need different variables…

    public function __construct() {
        global $table_prefix, $wp_embed, $wp_widget_factory, $_wp_deprecated_widgets_callbacks, $wp_locale, $wp_rewrite;
        // Additional WordPress global variables
        //$wpdb, $current_user, $auth_secure_cookie, $wp_roles, $wp_the_query, $wp_query, $wp, $_updated_user_settings,
        //$wp_taxonomies, $wp_filter, $wp_actions, $merged_filters, $wp_current_filter, $wp_registered_sidebars,
        //$wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_widget_updates, $_wp_deprecated_widgets_callbacks,
        //$posts, $post, $wp_did_header, $wp_did_template_redirect, $wp_version, $id, $comment, $user_ID;

        require_once '../wp-load.php';
    }

Step 3 – Methods for User Management

In order to complete our class, we are going to define some methods to return user information. What we want to get from WordPress is if the user is logged in, if the user is super admin and the following links: login, logout, blog and WordPress admin section.

  • The first method we’re creating is the isLoggedIn(). It is a very simple method that will just return the WordPress function is_user_logged_in(). As you can imagine, it will be true or false.
        public function isLoggedIn()
        {
            return is_user_logged_in();
        }
    
  • Next, we need a method to say when a user is super admin. We are using the function wp_ge_current_user() and returning true when the user level is greater than 10. You could simply return the user level and handle the different user levels inside your CodeIgniter application. In my case I was only interested in knowing if the user is a super admin.
        public function isSuperAdmin()
        {
            if(wp_get_current_user()->user_level >= 10)
                return true;
            else
                return false;
        }
    
  • The methods loginLink() and logoutLink() will return the login and logout links for our website. These links will take you to the WordPress login and logout pages, but they have a redirect_to query string, which will contain the link to our application. So, after you login (or logout), you will be redirected back to the CodeIgniter app. Notice that in these methods we use the CodeIgniter instance to load a helper. The helper is ‘ci_url’, which is a copy of the original CodeIgniter URL helper with a few changes that I’m going to explain later. The function current_url() is defined inside this helper.
        public function loginLink()
        {
            $CI = & get_instance();
            $CI->load->helper('ci_url');
            $redirect = current_url();
    
            return wp_login_url()."?redirect_to=$redirect";
        }
    
        public function logoutLink()
        {
            $CI = & get_instance();
            $CI->load->helper('ci_url');
            $redirect = current_url();
    
            return wp_logout_url()."&redirect_to=$redirect";
        }
    
  • The next two methods are quite the same. They will return the links for our WordPress blog and for the admin section. This would be useful to link directly to them from our application.
        public function blogLink()
        {
            return get_option('siteurl');
        }
    
        public function adminLink()
        {
            return get_option('siteurl') . "/wp-admin";
        }
    

Changes in CodeIgniter

In the moment that we include wp-load.php, several functions are included with it. So we need to take care with possible conflicts caused by function redefinition. As an example of conflicts, I’m going to use the CodeIgniter URL helper. This helper has the functions site_url() and base_url(), which also exists inside WordPress. So, I just copied the complete helper to the helper folder inside our application. Then I changed the functions that were conflicting, renaming them to ci_site_url() and ci_base_url(). We also need to change where these two functions are used, inside the anchor(), anchor_popup() and redirect() functions. I used the URL helper as an example of the changes needed to make it work. But depending on what you need, you may need to customize different functions.

Conclusion

This integration is not natural and clean, as WordPress and CodeIgniter are obviously not built to work together. But it is quite interesting to be able to create a web application with the possibility of reusing WordPress features. Hope it helps someone. If you have any ideas or comments, leave your message.

When I wrote this article, WordPress 3.2 was not available. So I needed to do some changes inside WordPress to make the integration work. After downloading version 3.2 it became easier to do the integration. So I updated the article accordingly.


  • tpk

    I can’t figure how to make it working. The whole configuration is ok but i get a

    Fatal error: Call to a member function register() on a non-object in C:\xampp\htdocs\wordpress\wp-includes\widgets.php on line 431

    when i load de wpintegration library, even if in autoload. in that file (widgets.php) there’s a reference to $wp_widget_factory which is globally loaded. Any ideas? 🙂

    btw, great tutorial! is helping me understanding how ci works thanks!

    • Hey tpk,
      In the constructor of the Wpintegration class there is a declaration of several globals, one of them is $wp_widget_factory. Can you double check if it is there? When I remove this variable from the declaration I get the same error… So my guess is that it’s not there… Let me know how it goes!

      • tpk

        hi oscar, thank u for the quick reply!

        it seems that ci doesn’t load none of the global wp variables, not only the wp_widget_factory. This is my constructor:
        {
        global $table_prefix, $wp_embed, $wp_widget_factory,
        $_wp_deprecated_widgets_callbacks, $wp_locale, $wp_rewrite;
        require_once ‘../wp-load.php’;
        }
        CI directory is located under the wp one so the require_once is correct.
        I load the wpintegration in the autoload[‘libraries’] array.
        thanks in advance! 🙂

        • tpk

          my mistake, i was using an old wp version, it works! thanks again :))

  • Great article. I am using CodeIgniter to launch WordPress as a desktop version of my site. I am using CodeIgniter for my mobile version.

    As the site I worked on is unilingual, it used the qtranslate plugin. That messed up the CI routing so here is a quick fix:

    public function __construct() {
    global $table_prefix, $wp_embed, $wp_widget_factory, $_wp_deprecated_widgets_callbacks, $wp_locale, $wp_rewrite;
    // Additional WordPress global variables
    //$wpdb, $current_user, $auth_secure_cookie, $wp_roles, $wp_the_query, $wp_query, $wp, $_updated_user_settings,
    //$wp_taxonomies, $wp_filter, $wp_actions, $merged_filters, $wp_current_filter, $wp_registered_sidebars,
    //$wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_widget_updates, $_wp_deprecated_widgets_callbacks,
    //$posts, $post, $wp_did_header, $wp_did_template_redirect, $wp_version, $id, $comment, $user_ID;

    $request_uri = $_SERVER[‘REQUEST_URI’];

    require_once ‘../wp-load.php’;

    // restore the normal REQUEST_URI
    $_SERVER[‘REQUEST_URI’] = $request_uri ;

    }

    Here is a function I am using in my main controller for non mobile users to launch the desktop WP version of the site.

    /**
    * This is a wordpress hack.
    *
    */
    private function loadwordpress(){

    // these variables need to re re-globalized.
    global $post, $q_config, $wp;
    global $wp_rewrite, $wp_query, $wp_the_query;

    define(‘WP_USE_THEMES’, true);

    /** Loads the WordPress Environment and Template */
    require(‘./wp-blog-header.php’);

    }

  • Thanks for making it so clear and exceptional guidance about codeIgniter Application.

  • I blog frequently and I truly thank you for your information.
    This great article has really peaked my interest. I’m going to bookmark your site and keep checking for new information about once a week. I subscribed to your RSS feed as well.

  • ruo

    I’m developing a survey system need both as stand alone script and wordpress plugin.
    Thank you very much for your great article, I think I can use codeigniter to develop it, just need to add a wordpress bridge as a wordpress plugin.

  • LPH

    Please clarify: “Extract the file contents to your WordPress root.” Please list the directories. Is this what you mean?

    /htdocs/index.php
    /htdocs/wp-content
    /htdocs/wp-admin
    /htdocs/wp-include
    /htdocs/ci

    • Yes, that’s it! Please consider that this post is old, so you need to check whether this technique still works. If you have any problems let me know.

      • jean

        Hello I m new for WordPress but I must quickly need (codeIgniter + WordPress). I teak this tutorial step by step and i work but now I need the IHM of admin site like (http://yourdomain.com/wp-admin) but it will return 404 error can you help me 🙁

        • I’m not sure if I got your problem… YOu’re getting a 404 when going to your WordPress wp-admin, right? What is your folder structure?
          Can you try going to http://www.yourdomain.com/wp-login.php instead? Could be an issue with your .htaccess.

  • Pingback: Integrasi Wordpress dengan CodeIgniter | Mohammad Rian Arif Prakoso()

  • How to include codeigniter app in root directory??

  • Yr

    If my url codeigniter(contain form input) like myurl.com/index.php/controller1/form/ showing in admin panel, how to make it real? How should I do?