Working with Laravel 4 or 5 and WordPress together

Hi everybody!

Updated Mar 3rd 2015: Are you using Laravel 5? Check these changes!

Updated May 11th 2014: Using Corcel project

Currently I am working on a project where I had to make some choices about technologies and how work with them together. First this project will be developed using WordPress only. It’s a College Group site, where we had to work with 13 schools around the world and each one must has the control of your own content.

This could be made with WordPress, but I think when the site is not so small maybe you can use another CMS or Framework, because I particularly prefer to work with MVC. So because some decisions inside the company we decided to use WordPress Admin Panel, that is a very good, use its architecture and its database. So WordPress will be used to the application back-end, with user control, user permission, etc.

To the front-end we decided to work with Laravel. To query information from the WordPress database we’ve used the WordPress functions inside Laravel, so it’s much better to work with a MVC WordPress.

Installing WordPress and Laravel

Let’s install Laravel first using Composer. This will take some while.

composer create-project laravel/laravel

So we have now our Laravel folder structure with everything installed. Now let’s install a fresh installation of WordPress inside Laravel. Here you have to options:

    1. Install WordPress as a sub-dir of public Laravel folder, like /public/WordPress. So to access your WordPress Admin you have to go to something like http://example.com/WordPress/wp-admin.
    2. Install WordPress as a sub-dir of the Laravel’s root, like /WordPress. So you will have /app and /WordPress in the same position. For this you have to create another VirtualHost to point to WordPress installation. You can setup a subdomain lik wp.example.com and poit it to /laravel/folder/WordPress. This way you can access the Admin going to http://wp.example.com/wp-admin.

Removing the WordPress front-end

For security issues go to /WordPress/index.php file and put this first, to redirect to the Admin login page:

header("Location: ./wp-admin");
exit();

So, when you visit http://wp.example.com or http://example.com/WordPress you are redirected to the WordPress Admin login page.

Connect Laravel to WordPress

Now we have to include WordPress inside Laravel. It’s easier than you think. Just edit the public/index.php Laravel file and include the follow before anything:

/*
|--------------------------------------------------------------------------
| WordPress
|--------------------------------------------------------------------------
|
| Integrate WordPress with Laravel core
|
*/

define('WP_USE_THEMES', false);
require __DIR__.'/../WordPress/wp-blog-header.php';

Now you can use WordPress functions with Laravel. Yes, like a piece of cake!!!

Querying Posts

Let’s suppose you need to get some posts and show to the view file:

// app/controllers/SchoolController.php

class SchoolController extends BaseController
{
    public function index()
    {
        $query = new WP_Query(array(
            'post_type' => 'school',
            'posts_per_page' => 20,
            'order' => ASC,
            'orderby' => 'post_title',
        ));

        $posts = $query->get_posts();

        return View::make('school.index')->with('schools', $posts);
    }
}

Laravel 5 changes

If you’re using Laravel 5 when you create a WP_Query instance you should receive the error Call to undefined function App\Http\Controllers\WP_Query(). This is because you’re inside App\Http\Controllers namespace, made by default by Laravel 5. Just use new \WP_Query (with the backslash), forcing to call the class without any namespace.

…Continuing…

Maybe you need some WordPress features but you have to use it from your theme’s folder. If you don’t know how to create a WordPress Theme, check this post.

For example, in my project I had to create a “About” page for each school. So I create pages with taxonomies called “SchoolName”. After, I create a page with the “About” title and select the “São Paulo’s School” term in my taxonomy “SchoolName”. But all schools will have the same page structure, right? So I have to create a template page inside my WordPress theme’s folder. This way I can have custom fields to this page and all schools will have the About page looking like the same.

So, create a custom theme, adding a style.css file and a index.php file and activating it from the WordPress panel. After that create a new file called about.php. Inside it put:

<?php /* Template Name: About page */ ?>

So I created a Template called “About page” and when creating the “About” page I select the “About page” template name too. Now my page has a custom taxonomy and a template name.

Now let’s query some pages.

Getting Pages

Now if you have to get information about some page, like “About” page. Remember here that the permalinks from WordPress won’t be used. We are going to use only the Laravel routes and URL’s. We are using WordPress only to fill the database and use its Admin Panel.

/**
 * Getting page from WordPress
 */

// Getting page by ID
$page = get_post(1234);

// Getting page by slug
$query = new WP_Query(array(
    'post_type' => 'page',
    'posts_per_page' => 1,
    'name' => 'about', // here the 'about' is the page slug you stored in WordPress when creating the page
));
$page = array_shift($query->get_posts()); // first post returned

// Getting page by template name
$templateFileName = 'about.php'; // here you must use the PHP FILE we've created in the theme folder
$query = new WP_Query(array(
    'post_type' => 'page',
    'my-taxonomy-name-here' => 'my-term-slug-here',
    'posts_per_page' => 1,
    'meta_key' => '_wp_page_template',
    'meta_value' => $templateFileName,
));
$page = array_shift($query->get_posts());

So, that’s it. Now you can use the power of Laravel with the facilities of WordPress. So, if you’re creating a website and need more organisation to your files you have use both to make your life easier.

You can too use custom database tables to work only with Laravel, using Models, etc. You can join both worlds and have a better final result.

Using WordPress Corcel

Some time ago I started to create a project based on Eloquent ORM (from Laravel) and WordPress. The project is hosted at Github and you can get more info here.

You can install it using Composer. Just add jgrossi/corcel in your composer.json file and be happy.

There are much work to do but currently you can use some cool features, like:

Getting posts

// All published posts
$posts = Post::published()->get();
$posts = Post::status('publish')->get();

// A specific post
$post = Post::find(31);
echo $post->post_title;

Working with custom post types

// using type() method
$videos = Post::type('video')->status('publish')->get();

// using your own class
class Video extends Corcel\Post
{
    protected $postType = 'video';
}
$videos = Video::status('publish')->get();

Custom post type and custom fields (meta data)

// Get 3 posts with custom post type (store) and show its title
$stores = Post::type('store')->status('publish')->take(3)->get();
foreach ($stores as $store) {
    $storeAddress = $store->address;
}

Pages

// Find a page by slug
$page = Page::slug('about')->first(); // OR
$page = Post::type('page')->slug('about')->first();
echo $page->post_title;

If you want to contribute with this project you’re very welcome. Ideas are welcome too.

Thank you for reading.

Published by

Junior Grossi

senior software engineer & stutterer conference speaker. happy husband & dad. maintains Corcel PHP, elePHPant.me and PHPMG. Engineering Manager @ Paddle

267 thoughts on “Working with Laravel 4 or 5 and WordPress together”

    1. you can have another installation of wordpress pointing to the same database, just use a different host, like admin.example.com. they will be two different wordpress installations but pointing to the same db.

  1. Can any one help me to print all the taxonomy of the posts? I have loop of all post and I need tow show the post_tag. I tried to this way but it is not working at my end?

    $taxonomies = Post::find($post-ID)->taxonomies; // collection of Taxonomy classes
    $taxonomy = $taxonomies->first()->term->title; // Term instance
    print_r( $taxonomy);

  2. Hi, nice tutorial – I was not aware of it!
    I’ve just opened a WordPress plugin that does a similar thing: integrates laravel into wordpress run-time.

    If you wanna give any feedback, it’s super welcome.
    https://github.com/thiagof/wp-laravel

    My approach was to keep the separation for both environments since it can be used for legacy and already large projects.

    I have integrated WordPress into Laravel as well, with a bit more boilerplate for the separation. But I don’t recommend that actually, it is costly for the Laravel bootstrapping. So I’d actually created a singleton that can load WP only when necessary (for legacy reusage purposes).

    Still, I’d rather recommend Corcel over booting WP inside Laravel core. The other way around (laravel inside wp) is pretty stable and works like a champ.

  3. i need to get post thumbnail image in laravel.
    I use your code :-
    $query = new WP_Query(array(
    ‘post_type’ => ‘post’,
    ‘posts_per_page’ => 20,
    ‘order’ => ASC,
    ‘orderby’ => ‘post_title’,
    ));
    $posts = $query->get_posts();

    after this i used foreach on laravel blade file and want to get the_title();, the_content() or the_post_thumbnail().
    But i m not able to get.
    please help .

    1. Hi, thanks for commenting. If you want to use functions like the_title() you need to include WP inside Laravel. The post already explains how you can do that. Otherwise, if you are using Corcel, it works directly in the database, so you don’t have those functions, you have to recreate them or format the data yourself. Thanks.

  4. Hi,
    Thanks for this tutorial.
    I just have a question : is it possible to find Custom Post by acf tags ?
    exemple : i have 2 custom posts : singers and songs
    and i need to find all songs belong to a singer and i link song to singer by acf field (‘singer_id) .

    Thanks.

    1. You can use WordPress for the blog stuff and than integrate inside your Laravel app, just a normal Laravel workflow, but using Corcel libraries.

      1. Hi Grossi, I have a wordpress website and wanted to do more with laravel in it, could you please tell me how to order the folders and the .htaccess to get prettyURLs?
        Thanks!

        1. Hey, if you want to use Laravel inside WordPress just install composer on it and start using the Laravel packages you want to. Corcel is about using Laravel to access WordPress data 😉

  5. // All published posts
    $posts = Post::published()->get();
    $posts = Post::status(‘publish’)->get();

    // A specific post
    $post = Post::find(31);
    echo $post->post_title;

    Where i use this code

  6. Hi!, Thanks for this tutorial, i just have one issue, once i access the wordpress/wp-admin and click any link in menu (e.g Posts), it returns page not found, because wp-admin was removed from the url how do i fix that? Thanks!

    1. Hey, this seems to be a rewrite issue. This has nothing to do with using Laravel or something else. Once you are installing WP in a subdirectory you have to set the .htaccess rules according that. The WP documentation can help 😀 Anything just let me know. Thanks for reading.

  7. Hi @juniorgrossi:disqus . I currently working on legacy code that runs with Laravel 4.2. And then I try to require jgrossi/corcel:1.0.0. I got an error about dependency:

    `Problem 1
    – Installation request for jgrossi/corcel 1.0.0 -> satisfiable by jgrossi/corcel[v1.0.0].
    – Conclusion: remove laravel/framework v4.2.19
    – Conclusion: don’t install laravel/framework v4.2.19
    – jgrossi/corcel v1.0.0 requires illuminate/database >=5.0.0 -> satisfiable by illuminate/database[v5.0.0, v5.0.22, v5.0.25, v5.0.26, v5.0.27, v5.0.28, v5.0.33, v5.0.4, v5.1.1, v5.1.13, v5.1.16, v5.1.2, v5.1.20, v5.1.22, v5.1.25, v5.1.28, v5.1.30, v5.1.31, v5.1.41, v5.1.6, v5.1.8, v5.2.0, v5.2.19, v5.2.21, v5.2.24, v5.2.25, v5.2.26, v5.2.27, v5.2.28, v5.2.31, v5.2.32, v5.2.37, v5.2.43, v5.2.45, v5.2.6, v5.2.7, v5.3.0, v5.3.4].
    – don’t install illuminate/database v5.0.0|don’t install laravel/framework v4.2.19
    – don’t install illuminate/database v5.0.22|don’t install laravel/framework v4.2.19


    – Installation request for laravel/framework (locked at v4.2.19, required as 4.2.*) -> satisfiable by laravel/framework[v4.2.19].
    `

    Still Corcell can work with Laravel 4?

    1. Sorry but there’s no release that works well with Laravel 4. Since the first release 1.0.0 the requirements are L5, sorry! Corcel worked with L4 but a long time ago and then we did not create any release. The first one is 1.0.0. Cheers, JG.

  8. Great work JG, does Corcel just deal with the DB directly instead of pulling in all the WP cruft? One reason I’m using Laravel is for a leaner quicker website, so pulling in all of WP seems like a step backwards (albeit a super easy one!). Is using Corcel to pull posts a much lighter weight and faster approach? Thanks!

    1. Hey thanks for the comment. Corcel gets the data directly from the database, without formatting, nothing, just the data. It’s a little faster than using WordPress because the amount of SQL queries it does. WP does a lot of SQL queries before getting the data. Cheers, JG

  9. Hi!
    I’m a noob on this stuff of WordPress development and I have a client who has his site all in Laravel and decided to move to WordPress.
    It’s a train ticket reservation site and he wants to keep the booking app.
    Can I use this to connect the new WP site with his old Laravel app?

    Thank you so much for your response =)

    1. Hi Fran! If the base website is Laravel you should migrate the database to WordPress , maybe is better to include the “wp-blog-header.php” of the new WP site inside Laravel “bootstrap/autoload.php” and so you can create some Artisan command that reads from the database and then use WP functions to create posts and custom fields. Remembering you have to create all post_type with all custom fields before saving the new posts. Any question contact me through email and I can help you more. Best!

  10. Hello, I just wanted to thank you for this great tutorial. I had a site on which I didn’t install wordpress but was using the wp loop to fetch posts from a subdomain on which wp was installed. Everything was fine until I decided to implement laravel, to which i’m relatively new. I looked up for tutorials on how to achieve this for 2 days but couldn’t find any. I’m glad I finally found yours. Thanks again 🙂

    1. Hi Vee! Thank you for the message. It’s very good to know the post helped you. Welcome to the blog. Cheers.

  11. Hello Junior,

    i really like your solution. I used it in one small project once for a customer of mine.

    At the moment I try to figure out, what the real advantages are over simply using the REST API of WordPress. There are several plugins and (as far as I understood the news a few months ago correctly) there is a REST API in WordPress itself.

    Please don’t get my wrong: I appreciate your work, as I said before, I used it in one small project months ago.

    Thank you very much for your work and response.

    Kind regards

    Christoph

    1. Hey Christoph! Thanks for you message.

      Corcel was created before the REST API. It’s from 2013. I think you have some things you can do using the REST API, but using Corcel you can have some functionalities you should do by hand using the API. Both solutions are good, and you can choose what’s is the best for you.

      Corcel already has all the WP database mapped, so you can easily use its data, getting the data directly from the database. REST API is an API, you have requests, etc. It’s a different approach.

      Any question just ask. You’re welcome.

      1. Hey Junior,

        I think I understood, whats the point. As you’re saying, one has to choose, what’s the best solution for which project.

        Thank you again.

        1. Exactly, that’s the point. I was working on a project with “The Events Calendar” plugin, which has a lot of use of frontend part. So it’s not interesting to use Corcel there, because the plugin uses a lot of features WP already has ready to go 🙂

  12. Hello Junior,

    How we can change the ‘Page not found’ page title for the external WP Pages?

    Thank you.

    1. Hi Alex. If you are using Laravel you can create routes/views according the error code you found, in this case 404. If it’s not Laravel you can customize the page you want according the error too. Cheers.

      1. Thanks for your reply. I’m referring to the issue with Page title in external WP pages. Yes I’m facing the page title issue in Laravel pages where I have the WP Header included in these pages.

        The page itself are already loading fine no problem at the routes or views level.

        If you are not getting my point, it is something related to: https://wordpress.org/suppo

        1. Hey, I tried to commend in the forum post but it’s already closed. Any question just ask. Best.

  13. Hello Junior,

    Can we query Woocommerce categories and products tables using the WordPress Corcel package?

    Thank you.

    1. Hi Alex! Sure you can. Just map the WooCommerce database using models (with custom post type) and it will work 🙂

  14. Hi Mr Grossi, is it possible to use Woocommerce plugin to add a shopping cart & paypal feature still using the Corcel package?? I’m about to build an ecommerce app using Laravel for the backend but i’m thinking of using Corcel.
    Is it possible/wise to also have another custom backend with some features that the WordPress backend doesn’t have??

    1. Hi @Umi. Well, you can, sure, but Woocommerce has some conventions and you should be using a theme to everything work well. Using Corcel you’ll not use a WordPress theme, so you can still use Woocommerce, but only the backend part, like the admin panel, products management, etc. You can get the products list using Corcel and echo them in your view, without problem. And sure, you can have a complete different system using Laravel and use only WordPress where is necessary. You can use both apps without problem. Best regards.

  15. Hi Junior,

    I’m in situation where I need to use/embed a Laravel view that contains form in a WordPress web page, as a result the WordPress website visitors would be able to use (Fill, submit the form same as if they are on the Laravel app) what would be the best solution for this?

    Thank you.

    1. Hi @Alex,

      You need the inverse, right? You can include composer inside WordPress and start blade template engine, from Laravel, for example. You will have to use another composer packages to be able to use this view inside WP but there’s no big problem using this.

      Best.

      1. Thanks for your reply.

        Actually, I already have the Form built in the Laravel app and I just want to be able to open it for the WordPress website visitors to use it. So I don’t want to replicate the work on both sides.

        Do you think using iframes is fine and has no security issues?

        1. I don’t see problems using iframe in this case, but you have to think that when users use the form (in the Laravel app) the data will be stored in the Laravel application, not WP.

          I suggest you, in this case, to create a simple form page in Laravel according the layout of the WordPress website and redirect the WP user to there, and after redirect back to WP page.

          Best.

  16. Hi Junior. Thanks for this article.I have laravel application. I have built wordpress for posts,articles,forums.How I Can make a user to be able to make comments who logs into laravel application.Both systems should use single laravel users table. How can i make wordpress to use laravel table.

    1. Hi @satya! Thanks for the comment.

      You can create different connections in Laravel config/database.php. So the model classes you want to use WordPress tables set protected $connection = ‘the_wordpress_connection_name”, and the model classes you want Laravel do not include this and it will use the default connection.

      Best!

  17. Hi Junior. Thanks for this article.

    I’m not a coder or even a beginner in any computer languages. I do now I want to run my network of different sites, which will all share the same admin area.

    I want to use WP themes for their front-end functionality rather than build from scratch, but run it on Laravel to make any coding and customization easier and smoother and for it to run faster.

    Is that something that can be done easily enough, once set up?

    Thanks,

    John

    1. Hi John! Thanks for the comment! I never tested Corcel or even including wp-blog-header.php in WordPress network, so I’m not able to tell you if this will work or not. I think in this case using Corcel maybe will be easier, because it will connect to the database, not the WordPress logic, so you can map all tables and databases you have inside configuration files.

      Any question just ask! Best regards!

      1. Hi, Junior, just got start with Corcel, which is a good one I gonna say. Just got stuck at trying to get the post author name displayed on the posts listing page. {{ $post->post_author }} can get the author id there. I am using Laravel 5.2, putting the wordpress under the public directory by the way. Any ideas? Cheers.

        1. Hi Homer! Thanks for using Corcel 🙂
          You can get author name using $post->author->display_name. Using $post->author you can get any info you want from wp_users table.
          Any question just ask. Cheers.

  18. Hi Junior, Is there any special variable that I can decide from if I’m browsing WP page?

    Actually, there is a section in the WP Footer, I need to show it only on the WP pages and not on the Laravel views where the WP Footer is included as well.

    Thanks in advance.

    1. Hi Alex. You have to choose what router you want to use. If you are using wp inside Laravel so the URLs will point to Laravel router. So you should use views. Using Laravel components inside WordPress you are using wp router so you use wp themes. Cheers.

    1. Hey! You have to include Composer inside Laravel and call the Eloquent classes. You can use Eloquent without Laravel. I’m away from computer now but tomorrow I can give you an example.

      1. Thanks a lot for your efforts. I have followed your example but WP page showing only the header and the rest of the page is blank.

        Is it possible to refer and include the Eloquent, Composer from the Laravel app directory instead of having them again in the WP?

        Thanks again.

        1. Alex, you should not include Laravel folders inside your app. You should not have the app folder. You only need to include Composer and call what you want. You won’t use Laravel framework but a Laravel component through Composer. Ok?

          1. Alex, you have 2 options: first is use Laravel and include WordPress, what the blog post does. Second is use WordPress and use Laravel features, what I’ve told you. If you are using Laravel and you want to include WordPress features just include wp-blog-header.php file or use Corcel package to get data from WordPress database. If you want to use WordPress you only have to include Composer with the Laravel packages you want, like database, for example, configure them and call one by one. Which one are you using?

          2. Actually at the moment I’m using both options.

            The first option, I have already done and it’s working great – so I included the WordPress theme header and footer into the Laravel application.

            For the second option, what I only want is querying one of the Laravel application tables and show it’s content in one of WordPress pages.

            Thanks for your help.

          3. So, you have 2 different apps, right? One using Laravel (including WP) and another WordPress (including Laravel DB tables). So, in the second app (WP) you should follow all instructions inside the Gist: https://gist.github.com/jgr…. You have to inform the database details of your Laravel app (the database where the tables you want to query are stored). So, WP will connect the Laravel DB table and using the Models (see gist) you can qhery everything you want. 🙂

          4. Thank you a lot Junior for your help and following up.

            I have followed what is there in gist and it works as expected.

            Best Regards,

  19. Hi Junior,

    Thanks for this great article.

    I’m in situation where I need to integrate WP header and footer into a Laravel website.

    Could you direct me with the needed steps, to get both of them in place?

    Updated: I was able to get them in place, following your point above by editing the Laravel “public/index.php” – Then I included the theme header and footer php files into my blade master layout.

    Thanks.

    Best Regards,

    1. Hi Alex! Nice to have you here. I think the easiest form is include wp-blog-header.php inside some Laravel php file. Thus you have all wordpress functions availables inside Laravel, including header and footer ones. Any question just ask. Best regards.

      1. Thanks for your reply. Yes this is what I have done and it works without any issues.

        Another query: I’m in a situation where I need to query a Laravel DB table from WordPress page.

        I found many packages to do the opposite way.

        Could you suggest me a solution? Thanks.

  20. Hello Grossi,

    Hope you are good.

    I am working on lgoin and comment system and want the wordpress user can login and do comment and other activities. Please advise.

    Thanks
    Haroon

    1. Hi @Haroon 🙂

      The user will login in your website and make comments? Is that? What your question?

      Thanks 🙂

      1. Hello Junior,

        Yes but using all the wordpress features if it possible else i am working on laravel for login.

        Thanks 🙂

        1. Well, if you are working with Laravel you can create login screens using Laravel and its routes and views. To make comments you can insert the comment direct in the database or use WP functions (including the wp-blog-header.php file inside Laravel), it’s your choice 😉

    2. Hey did you find any solution?? ‘cauz I don’t want to create login system, is there any way we can use wordpress login functions (like get_currentuserinfo( ) ) in laravel straighforward??

      1. Hi! To use WP functions you have to include wp-blog-header.php file. This allows you to have all WP functions inside Laravel, like the post says. We have plans (soon) in Corcel package to allow login and manage users sessions using Corcel classes, not WP functions, but using WP database structure 🙂

        1. thanks!!!….for now I added which is working perfectly fine!! 😀 (taking method 1 of integrating wordpress with laravel into consideration)

          setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire,’/laravel/public/’, COOKIE_DOMAIN, $secure_logged_in_cookie, true);

          in file wp-includes/pluggable.php at line 955 (after do_action(set_logged_in_cookie))

          after this…..i can now use any wordpress logged-in function like get_current_user_id() with laravel…cheers!!

    1. Hi @btistaa! Yes, you can, BUT, this way you have to include Laravel bootstrap file inside WordPress environment.

      This post is about including WordPress inside Laravel, so, the routes will be dispatched by Laravel, that calls WP.

      In your case you will get WP as website and using Laravel to update the WP database, for example, but you will have to create a page like /admin to redirect WP to your Laravel application.

      Any question just ask 🙂

  21. How do you feel about moving the first step:

    define(‘WP_USE_THEMES’, false);
    require __DIR__.’/../wordpress/wp-blog-header.php’;

    into the top of the start.php file? It’s almost the same except (since start.php is already the first thing in index.php) my ‘php artisan …..’ commands were throwing errors due to WP functions being in app.php , and since I think artisan executes starting at the start.php file, it was missing the WP include!

    1. Hi! Very nice contribution! You can include the WP files inside start.php or bootstrap.php file (this last one is included first). Using that you always will have WP inside web files and using Artisan too. Very nice suggestion! Thanks for the support.

  22. Hello There,

    Thanks for this article it’s great and worked for me. I have some question

    I install Laravel like this

    Public_html/laravel
    Public_html/wp-content

    etc
    and this is working for me but I want to access laravel like laravel.mywebsite.com and also want to satys on this domain not on my main domain. if i will update the wp_home and wp_siteurl it’s not working for me.

    how i can achieve that Please help me thanks

    1. Hi @Haroon! Thanks for the comment.

      If you want to use laravel.example.com you have to create a new virtual host in your Apache or Nginx pointing to public_html/laravel/public. The public folder is where laravel.example.com has to point to.

      Inside wp-config.php you have to point to public_html/wordpress, not Laravel folder.

      Any question just ask. Cheers.

        1. Hi @Haroon!

          Virtual Host is the folder that will answer for some domain call, like test.example.com. You have to point it to a folder inside your server. If you are using shared host you have just one virtual server pointing to public_html for example.

          To use subdomain you have to create them and point to a specific folder. You can try to use Laravel inside shared host but is not recommended. I have a blog post about that http://blog.grossi.io/2012/….

          Search for “virtual host apache” on Google to get more details about it.

          Thanks for the comment. Cheers.

  23. Hello there,

    I need some light about what is explained here because it’s not full clear for me.

    Imaginate I create multiple page from WP-Admin.

    How to get them dynamically managed by Laravel using maybe a route like :

    http:///host/Page/… where … is the dynamic page to display.

    Thanks for help and this great tutorial !

    1. Hi Thierry! Thanks for the comment.

      About your question, when you’re using Laravel with WordPress (WP inside Laravel) you are using Laravel route system, so if you create a new page inside WP admin you have to recreate that page on Laravel route system.

      You can get_pages (WP function) and make a loop inside routes.php to create the routes dynamically, so all pages you create inside wp admin will exist inside Laravel routes file.

      Any question just ask. Thanks again for the comment.

      Cheers!

  24. Hi Junior, can you add here how you setup your local environment on both laravel and wordpress. Urls like /wordpress/contacts always redirects to 404 of laravel. Thanks

    1. Hi @Jordan!

      Why are you trying to get /wordpress/contacts? The goal of using both php projects is to use Laravel for frontend and Wordpres for backend, so using wordpress URL would be disabled, without themes 😉

      I think you cannot use both route systems. I’d like to use Laravel route and WordPress for backend (admin panel only). That’s why we include WordPress files inside Laravel.

      Thanks for the comment 😉

  25. Hi, i’m using Corcel successfully in my project, but I am running some default Laravel Eloquent queries after the WP queries, and it is trying to prepend the tables with wp_

    How can I revert back to the default connection/settings please?

    1. Hi @pavsid! You can customize connections to use with Corcel and Eloquent. For example, you can have a connection called “corcel” where you set the table prefix and more options, so you’ll use it with Corcel models like Post. To use Eloquent alone you can set other connection inside your models to load without table prefix. Let me know if that worked 🙂 Thanks for the comment.

  26. Hi @juniorgrossi:disqus – this is exactly what I need for a new project i’m working on. One question for now though, is how would this work if the client wants to enable comments on a WP post?

    1. Hi! You can create a form and save the comment in the database. After you can use WP functions to retrieve the comments and show in your view file.

  27. I went through this entire tutorial and can only access native WordPress functions from Controllers but I can’t get them to work through Artisan. What do you think the issue is?

  28. Hey, great work you are doing! I would like to use Corcel.

    I’m
    running Laravel 4.2 and am currently not planning to update to 5.x. Can I
    use the newest Corcel anyway or do I have to switch back to an older
    version of it?

    Thanks,
    Alex

      1. Thanks for all your hard work on this!

        I am unable to install the current version via composer due to PHP ver (5.4.11)

        illuminate/hashing v5.2.7 requires php >=5.5.9
        illuminate/support v5.2.7 requires php >=5.5.9
        hautelook/phpass 1.0.0 requires php >=5.6.0
        illuminate/database v5.2.7 requires php

          1. Is it possible for you to use PHP >= 5.5.9? The Corcel composer.json is requiring illuminate/hashing = 5.0.0, so it is installing the version 5.2.7 which required PHP >= 5.5.9.

            One solution is to upgrade your PHP to this version and other is to change Corcel’s composer file to restrict the version, but I think this is not a good ideia for now.

            I strongly suggest you to upgrade your PHP.

            Another option is to clone the Github repo, change the composer.json file of Corcel and “composer install”.

            Regards.

          2. I strongly recommend that hehe. You can install Corcel using an older version but at least 5.5.9 shoud be fine 🙂 Best regards

  29. Hi, I have a problem, my controller works fine but when I enter a WordPress function, sends me to Error 500 Internal Server Error. What it happens?

    1. Hi Danny! Maybe this can be a namespace error. Laravel 5 uses namespaces to define a controller so, maybe using WordPress you have to go back to the default namespace. Any questions just ask. Thanks 😉

  30. Great job! very good post. I love Larvel, the way it deals with difficult scenarios quite easily, such as database handling, routes, filters(now middle-wares). WordPress is also great, combining both is awesome!

  31. I was following your tutorial but i got this error:
    Failed opening required ‘C:xampphtdocstestpublic/../wordpress/wp-blog-header.php’ (include_path=’.;C:xamppphpPEAR’)

    Cause for the error:
    require __DIR__.’/../wordpress/wp-blog-header.php’;

    When i change it to:
    require __DIR__.’/wordpress/wp-blog-header.php’;

    It worked just fine and i don’t know why. I am running laravel using “php artisan serve” on my local server.
    I am using Laravel 5.1 and WordPress 4.2.2

    1. Hi @Krisna!

      Thanks for the comment. You have to check what’s the right path for your. If you are inside public directory and wordpress too you only have to include __DIR__.’/wordpress’. When you include ‘/../’ you are going back one folder (root project), so you had to include ‘/../public/’ again. So, __DIR__.’/wordpress’ is correct.

      Regards.

  32. Interesting post. I’m currently learning both Laravel and WordPress and this idea of using them together came to my mind as well. I looked at your Github project on the Eloquent wrapper for WordPress. Very cool stuff indeed. I’m gonna give this a try once I familiarize myself more with Laravel.

    1. Thanks for the comment @Isuru! I appreciate your words and good luck with your study. Any question just ask. Regards.

  33. Great tutorial Junior 🙂

    I’m trying to implement this tutorial in a new project. Everything you explain on it is working very good. My client needs WP Admin Bar in frontend for toggling a post between backend and frontend.

    I’m trying to load WP_Query with requested post but in this moment always loads the first post and then Laravel should render admin bar of this first post.

    The problem is that the admin bar doesn’t show never. I’ve included wp_header and wp_footer in my laravel layout view and it loads well other functionalities.

    I think is because in Laravel the user is not logged when in WordPress backend is logged. Do you know how to show admin bar?

    Thank you

    1. Hi @Sergio!

      I did not have to show admin bar on the frontend, but it’s possible. You can check if the user is logged using WP functions. Maybe you will need to force the user login to show de WP admin bar or you can try to use `show_admin_bar` function.

      If I can help you more let me know. Thanks!

      1. Hi Junior, thanxs for reply. If I use “is_user_logged_in()” function, it returns false but at the same time I’m logged for wp-admin. I think, due to this, show_admin_bar doesn’t print nothing.
        In other hand, it’s possible use plugins as All in One SEO in frontend? Because when I use it and call wp_head in blade view, it render some commented plugin lines but any code between open/close comment lines.
        Actually, if I show the current WP_Query and make the loop in Laravel, it shows me the first wellcome default post.
        Thank you 😉

        1. Sorry man, but I really don’t know about this Admin menu bar 🙂

          About the plugins, I think (it’s not tested) all plugins that uses the WP frontend structure won’t work because it assumes the default theme directory and a lot of pre fixed rules. But give it a try, because I’m just thinking hehe

          Thanks for the comment. Welcome.

          1. Thank you Junior, I’ll investigate about it and if I have good results I’ll comment here. Best

          2. Hey!

            You can use WP functions to show admin bar inside Laravel views, for example, like you use inside WP themes.

            When you include WP inside Laravel using wp-blog-header.php file you can call any WP function you want 🙂

            Thanks for the comment.

  34. Hi Junior,

    what are you using with member management for wordpress with Laravel. How are you connecting logins with each other?

    1. Hi @Flash! Do you mean login using the front-end side? As we’re using Laravel on the front-end we have to login using Laravel with WP database or you can use WP functions to login the user and so you can user others WP functions you like. Thanks for the comment. Cheers.

  35. Hey. I am using Laravel 5 and WordPress 4.1.1
    I created a new laravel project. Then downloaded wordpress and put it inside the public folder.

    /public/wordpress

    My problem is that even if I put this
    header(“Location: ./wp-admin”);
    exit();
    at the top of this file – /public/wordpress/index.php, I am not redirected to the admin page of wordpress.
    Please help. Thank you.

      1. I am running on a local server. In the root of the server is a folder ‘jigyaasa’ inside which are all the folders of laravel like ‘app’, ‘public’ etc.

        So, to check out the website, I go to ‘http://server.mbt/jigyaasa/public/’ which shows the laravel welcome screen. (All well and good till here.)

        Now inside the public folder is the wordpress folder.
        When I go to ‘http://server.mbt/jigyaasa/public/wordpress/wp-admin’, I get redirected to ‘http://server.mbt/wordpress/wp-admin’. (Redirect problem)

        1. Hi @Mriyam! I think it’s much better for you to create a virtual host for /public folder. This will allow you to have more control from your app, both WP and Laravel.

          Any question just ask. Thanks for the comment.

  36. Hi! I have a problem on the server of our hosting company and they use PHP 5.4. Someone have a solution?

    FastCGI: comm with server “/var/www/fcgi-bin/php-fpm-54-oblivio” aborted: error parsing headers: duplicate header ‘Content-Type’

  37. Hi! Great article! But I’m getting an NotFoundHttpException if I want to access single post. I have a route
    Route::get(‘/wordpress/{slug}’, ‘PostsingleController@index’), configured wp permalinks and I have created a view but still nothing. Any Idea? Thanks

    1. Hi @Krex!

      Thanks for the comment. About your question, when you start to use Laravel routes you cannot use WP permalinks anymore. The post goal is to use only the admin panel from WP. So for your route you have to call new WP_Query or get_posts inside the Laravel controller. Changing the WP permalinks will not affect your Laravel routes.

      Any question just ask. Cheers.

  38. Why can’t you have wordpress running in the background as a management system for your post and use laravel ORM to call the post table so that you can use it?

    1. Hi @Kaps!

      That’s exactly what Corcel project does. It’s a Eloquent wrapper to WordPress database. The post covers Corcel here.

      The Corcel source code you can get here.

      Thanks for the comment. Cheers.

        1. Welcome! We have used Corcel in production with some projects. If you want to contribute with the project will be nice too. Thanks!

          1. No, but when can implement that 🙂
            I think the best option for you for know is include “wp-blog-header” so you will have “do_shortcode” function to use.

            Thanks for the comment.

          2. yeah that was the reason I dropped the Corcel halfway through dev. My work around is to copy and paste the shortcode parser within my code before the output. I didn’t have time to 1) run the SQL to check for addon shortcode and 2) implement it within corcel. Found it easier to include two function from WP to just parse the normal shortcodes.

            If I get time to figure out the SQL query for the addon shortcode I’ll let you know.

          3. Nice, but as there are some WP plugins that uses shortcodes they should “listen” to actions/filters and make some change, so this won’t work in Corcel, because the action/filter hooks doesn’t work.

            Maybe we can find a better solution to parse these shortcodes 😉 Let’s think about it.

            Thanks for the comment.

          4. Maybe connect straight to the DB and run it? I’m not sure how the apps add the shortcode, i’d assume DB?

          5. Yes but I really don’t know how shortcodes work. I’ll google about that and let you know 😉 thanks for the comment

  39. great article! I am in desperate need of connecting laravel to wp, but NOT disablling wp. Laravel must be a separate application that will only communicate with wp for things like create/update wordpress users….Do you think i could just do it by includin the lines in laravel’s index.php file? They will reside in differenr directory structure (wp and laravel)

    1. Hi @Elias!

      You can do that inside Laravel controllers, what is more appropriate. You should create the routes you want and call WP functions and classes to manage the users the way you want.

      Thanks for the comment and any questions just ask.

      Cheers.

  40. Greetings,

    i found your blog post very interesting and very helpful.

    i am not sure if i archive what i want so i ask for your help .

    I wanna use WordPress for front-end and for backend, but i wanna use laravel to call API-s and do some logical operations before i store those data to wordpress database.
    I did following :
    i install wordpress in root of my folder. Than inside root folder i install laravel. That look something like this:
    /root
    /wp-admin
    /wp-content
    /wp-include
    /other wordpress files and folder
    /laravel
    Than i can access to laravel on url :
    domain.com/laravel/public – and that is perfectly fine by me because only me ( or some other admin) will user laravel to some external API-s.

    I install your package and it work very well (i am not sure if i can store those data), but i am using woocommerce theme and i need to insert post with wordpress functions.
    Anyway what i wanna to archive is this :
    I call api with laravel, than i need to call wordpress functions to store those data. Is this possible?
    I get some errors because wordpress is using a lot of globals. Did i miss something ?

    Can i use all wordpress functions inside laravel ? and how ? That is my main question.

    Please explain to me in great detail if you can, because i am not so good with wordpress.

    And one more question :
    Will you make package for laravel 5 and when ? Laravel 5 should come out this week, so maybe it should be best ( for me ) to make that plugin with Laravel 5 because i plan to use wordpress + laravel on my 10 next projects.

    Best regards

    1. Hi @Ivan!

      Thank you for the comment. I suggest you to include the WP file wp-blog-header.php inside your laravel/public/index.php. This way you can have access to all WP functions inside Laravel, like the article says.

      I suggest you to use separated directory for Laravel and WP like /laravel and /wordpress. So you must create 2 virtual hosts for /laravel/public and /wordpress. This way you can prevent illegal access to Laravel configuration files and more (like cache, db, etc).

      Welcome to the blog and nice code 😉

      1. Thanks for replay, i will try that soon.
        Just one more question. Are you sure if i make that way ( two virtual host ), that i can use all wordpress functions inside laravel?
        And one more question:
        Can i make “laravel” plugin? with all wordpress + laravel functionality?
        That way i can use laravel on every wp site. And if i need to load laravel in wordpress admin i can use iframe? Correct me if i am wrong.

        Thanks in advance.

        Best regards

        1. Hi @Ivan,

          I’m sure you can use all WP functions inside Laravel using 2 (or more) virtual hosts.

          About Laravel plugin I suggest you create your Composer packages, with your own namespace and classes and use it inside Laravel using WP functions. Pay attention only to load WP functions (“wp-header”) before Laravel loads the Composer autoload to make sure you can use WP functions inside your classes.

          🙂

  41. Also, what’s the purpose in this case of using Laravel? Why don’t you just make use of wodpress templates so you can modify them as you want and this way, you won’t have to deal with the URL routes and so on with Laravel? Just to be able to deal with the MVC ?

    1. @Alvaro,

      WordPress is a very useful CMS, but there are some practices that it does not use, like MVC, for example. We have experience creating with Laravel, so its architecture is very handful and allow ud to do more together with WP.

      Furthermore using Laravel you are using Composer, Design Patterns and more. What we did was use Laravel for the project front-end and WordPress Panel to the back-end. This allow us to be more productive instead of using only WordPress. It would be possible to be made using only WP but the final result was much more professional.

      Moreover we had developed a big portal, joining 13 schools around the world, so using Laravel with MVC, routes, Eloquent (you can use more databases for example, with custom models and custom tables) and more advantages Laravel has, we could delivery a better project to our customer.

      Thanks for the comment and any question just ask.

  42. Hi, great article! But I have one question.
    Why do you have to make use of Wodpress templates? Why don’t you just use the Laravel views instead?

    1. Hi @Alvaro!

      Thanks for the comment. You do not have to use WP themes, but using them you can control more your application, for example, using functions.php. WordPress will read its own files, so functions.php is a good way to put WP code to change things.

      Furthermore with WP themes you can filter some pages but template file, for example, I have some pages with some template file, and using Laravel I can filter these pages by template, like a taxonomy but more simpler.

      Thanks for the comment.

  43. Is there any way we can access the WP functions from artisan as well ?
    I would like to run a cron function that requires wp users

    1. Hi again!

      I think yes. Artisan is a command, and it is a PHP file but without php extension. You can find it inside Laravel root folder called “artisan”.

      I don’t whink it will ne good to include WordPress inside Artisan file, but you can create custom commands using Laravel and so you will have WP funcions including wp-header inside public/index.php.

      The best option is to create custom commands using Artisan and inside the command classes you call the WP functions you need.

      Thanks for the comment 😉

  44. Hi, Thanks for this awesome tutorial. It works fab !!
    One question though. I am still using users from the wordpress site and have made facilty for laravel to access the WordPress users object in the BaseController.
    The question is where do i add the wp header include so that i can use all wordpress functions through CLI or artisan

    1. Hi @Jagad!

      Thank you for the comment. You can include the `wp-header.php` as I wrote on the post, inside public/index.php file in Laravel.

      Adding it you will have all the WP functions inside Laravel.

      Thanks! Regards.

  45. Hi Grossi. Fantastic work with Corcel. I need a tip. I’ve got a PostController that has standard CRUD ops routes. Currently I have to make the call to Database::connect() prior in every single route method otherwise . I’m trying to figure out how to make my code better and make it so that Database::connect() is only called once in my Laravel application. Or maybe you have some other suggestion for clean code.

    EDIT:
    Actually, your answer to another question here helped me see what I was doing wrong. It works perfectly now.

    Once again, excellent work Grossi, thank you!

    1. Hi @Faisal!

      First thank you for the comment. About your question you do not need to call `Database::connection` again, because you’re using Laravel. Using Laravel you already have the Eloquent models working so just extend `CorcelPost` and everything will work.

      Thank you again. Best regards.

  46. Hi @Junior Grossi
    Thank you for the great tutorial. I’m looking for a solution like this for my project.
    I have few questions:
    – As your project use WP admin for the backend part and laravel for front end, and it serves up to 13 schools around the world and each one must has the control of your own content. How can you archive that, I mean, how can a single wordpress install can be used to 13 schools. Do you use wordpress multisite (http://codex.wordpress.org/… ), and if yes, on the front end, how can laravel know which content to get for each school.
    – user authentication: how can you authenticate the user between laravel and wordpress.
    If possible, pls provide more info regarding to the hierarchical/architecture of your project for reference.
    Thank you very much.

    1. Hi @Nguyen!

      First, thanks for the comment. About your question, we setup a project joining 8 schools around Brazil. We’ve configured some taxonomy like “School Name”, and every page must has this taxonomy set.

      So I can get a page by its slug, for example, and filtering by the taxonomy “School Name”. This is a simple way to do that. We have used some plugins to manage user access to these pages. In other words, a user from School A can only see and access pages from School A, nothing more.

      To login a user, as we where using WordPress just for the backend we had not to login a user using Laravel, because all the logic is inside WordPress Admin Panel, what make the development faster.

      Any question, just ask 😉

      Thanks for the comment.

  47. hello and thanks for this interesting tutorial.
    I get the following error (in the console) when trying to install wordpress:

    PHP Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0
    PHP Fatal error: Unknown: Failed opening required ‘server.php’ (include_path=’.:’) in Unknown on line 0

    any ideas?
    thanks again

    1. Hi @kilinkis!

      How are you trying to install WordPress? I suggest you first to install Laravel. After that copy a fresh installation of WordPress into `/public/wordpress` and after go to http://youraddress/wordpress to install WordPress and create the database.

      It’s the easiest way 😉

      Thanks for the comment and welcome to the blog.

      1. thanks for your reply Junior.
        I’m doing as you said.

        and after wordpress asks for the database credentials
        when moving to step 2 of the installation
        I see a blank screen

        and those errors on the console

        1. Hi @kilinkis!

          I think you’re using the `php artisan serve` command, right? Because you’re getting the “PHP Fatal error: Unknown: Failed opening required ‘server.php'” error I think maybe you can start a new web server inside `/public/wordpress`.

          For example, in the terminal go to the WP folder and `php -S localhost:8001` for example. So go to http://localhost:8001 in the browser.

          I think this maybe can solve your problem. Let me know.

          Thanks!

      2. that’s how I did it, and I see the first step of the installation, but then, when moving to step 2 all I see is a blank screen. And see this error on the console:

        PHP Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0
        PHP Fatal error: Unknown: Failed opening required ‘server.php’ (include_path=’.:’) in Unknown on line 0

        1. @kilinkis,

          You’re using the Laravel PHP server to access the WordPress installation process. Start a new PHP server inside WordPress in a different port like 8001 e access it outside Laravel.

          []s

          1. great! so I ran: php -S localhost:8008

            and it worked, thanks a lot about that.

            one more thing though.

            I get the error about connecting to the database. (Error establishing a database connection)
            I created the database with MAMP’s phpmyadmin (running on port 8888).

            maybe this was wrong.

            how should I do it?

            thanks and sorry for the newbies questions

          2. @kilinkis, no problem 😛

            You have to chance Laravel config `app/config/database.php` and `wordpresswp-config.php`. I don’t know if MAMP changes the MySQL port but I think it does not. I think you connect `phpmyadmin` using port 8888 but MySQL port does not change.

            Thanks again. And any question, just ask 😉

    1. Hi Khalsa! Thanks for the comment. I have plans to start to record screencast and I contact you when available.

      Thanks again for the comment.

  48. Hello,
    I work with laravel and WP including the flowing code:
    define(‘WP_USE_THEMES’, false);
    require DIR.’/wp-blog-header.php’;

    It works fine in all of my hosting except in one that give me the following fatal error:

    Fatal error: Cannot redeclare mb_substr() (previously declared in /var/www/htdocs/xxxx/public_html/wp-includes/compat.php:17) in /var/www/htdocs/xxxx/vendor/patchwork/utf8/class/Patchwork/Utf8/Bootup/mbstring.php on line 38

    I don’t know why in the last hosting not run

    Thanks!

    1. Hi! Thanks for the comment!

      I guess this is a PHP version error. What’s the PHP version you are using? I saw this error in the past and I think this is a PHP 4 issue.

      Thanks for the comment 😉 Welcome!

  49. I have a question…I keep getting this error: Class ‘ControllersFrontendWP_Query’ not found, any idea how I should solve this?

    Thank you!

      1. i have the same problem in Laravel 5. I’m trying to make basic query.

        FatalErrorException in NewsController.php line 8:
        Call to undefined function AppHttpControllersWP_Query()

        class NewsController extends Controller {
        public function index()
        {
        $query = new WP_Query(array(
        ‘post_type’ => ‘news’,
        ‘posts_per_page’ => 20,
        ‘order’ => ‘DESC’,
        ‘orderby’ => ‘post_date’,
        ));

        $posts = $query->get_posts();

        //return View::make(‘news’)->with(‘news’, $posts);
        return “123123”;
        }
        }

        Test of connection with WordPress is successful:

        Route::get(‘/’, function()
        {
        return get_bloginfo(‘name’);
        });

        But in Controllers in have errors.

        Thank You for help.

        1. Hi! That’s because you are inside another namespace (AppHttpControllers). Try to call “new WP_Query” (with backslash) and it will work!

          Thanks for the comment!

          1. After all i have small problem with View::make
            Simple “return view(‘news’)…” works fine, but View:make reurnin error:

            FatalErrorException in NewsController.php line 17:
            Class ‘AppHttpControllersView’ not found

            UPDATE:

            I am fixed it with backslash return View::make
            Thanks for all.

          2. http://pastebin.com/vSMrUWbj

            This didnt work as you said in the post. But what I did for making it working is,

            I have created a helper, then linked the class,

            require “/../public/”. DIRECTORY_SEPARATOR . ‘blog’. DIRECTORY_SEPARATOR . ‘wp-blog-header.php’;

            on top. then it got worked.

            Thanks

          3. Hi @Amjith! Yes, you were including the wrong path to wp-blog-header.php. Any question just ask. Cheers! 😉

          4. Its not because of the path of blog header file. new Wp_Query will always show error when calling from controller.

          5. Wow, that’s weird! I call WP_Query inside controller in both L4 and L5 without problemas.

            What error message do you have?

          6. Call to undefined function WP_Query()

            I have tried different cases, but still this error. This may be because of the namespace defined in each controller to AppHttp

            Thanks

          7. Well, but WP_Query is not a function, it’s a class! There is wp_query (lowercase) function.

  50. I want to ask you if is this really very helpful to use Laravel in WordPress from what I could see after reading the article your project can be completed easily with wordpress alone why bother with Laravel? If possible can you layout some technical points behind it?

    Thanks

    1. Hi Muhammad!

      First thank you for the comment. Laravel is a amazing MVC framework, which has Dependency Injection, an excellent ORM, custom restful routes, and much much much more. WordPress has a great community and a lot of plugins, but it is developed in the “PHP old way”. So joining both worlds you can work with a powerful framework (Laravel) with many Composer packages you need, using WordPress as your backend (your admin interface).

      So, using them together you have a powerful tool with a very very fast development.

      Thank you! Regards.

  51. Hi All,

    I would like to start a basic test with connecting wp and laravel.

    I am more or less good with wordpress but never did anything with laravel.

    what would you guys suggest on how to get the ball rolling?

    any idea / thought / input is highly appreciated.

    Michael

    1. Hi Michael!

      Thank you for the comment. I think before start with both together you have to study Laravel and develop at least a small app to understand hot it works.

      My post suggest to use WordPress inside Laravel, but all routes stuffs are made inside Laravel, so study it before to join both.

      Thank you for the comment 🙂

  52. Interesting. I work a lot with WordPress and love Laravel, but never used them together. I understand the frustration of working with WordPress frontend using WordPres standard way, that’s the reason why I build Cortex. Regarding installation process you can install WordPress via composer too, thanks to WordPress mirror maintained by Joh P Bloch, search johnpbloch/wordpress-core-installer on github. Moreover thanks to composer installers plugin and wpackagist you can install your hybrid setup using only one composer json and put there laravel, wordpress and wordpress plugin, if you need. Finally I want to say that for me that approach is not very sane: I bet that the too much globals in WordPress will impact first or later with Lavarel (at least I would use a SHORTINIT initialization for WordPress). If you like Laravel and you like the “easyness” of WP backend have a look to October to me it’s a more sane approach using a native CMS for Laravel.

  53. Hi!

    Hi!

    This is a great article, but I have a reverse issue.
    I want to use wordpress as my front site, and Laravel as my app.

    So index.php in public folder should be handled by wordpress.
    But I still want the laravel routes functional if no page is found on the wordpress side. Any Idea on how to approach this?

    Basically both of them should live together on the same main domain.
    Users create their “minisites” on laravel and the routes file directs to them but only if wordpress has no pages and “is about to serve a 404” or something like that…

    Thanks!!

    1. Hi Ben!

      I think you can use WordPress like a normal install, but inside WP index.php you can include the public/index.php Laravel file.

      About the routes I really don’t know, but this way I THINK WP will try to render the page, if not found it will render 404.php inside your theme. Maybe if the 404.php file does not exist Laravel will activate its routes system.

      Maybe it is a solution 🙂

      Thanks for the comment.

  54. Accessing WP users information from Laravel

    We stumbled across a problem where we couldn’t preview articles via the WP admin. So we setup a getPreview method within BlogController (/blog/preview), but could not access the WordPress user information within Laravel.

    The reason the user information is not available within the Laravel installation is that the cookies where set on (domain)/wordpress/ and not the root.

    Simple Fix:
    Download and install the Root Cookies plugin here:
    http://wordpress.org/suppor

    Logout of your wp-admin and log back in. The WordPress user information (cookie) will not be available to your Laravel application.

    Cheers,
    Team Brain Box

    P.S. Thanks again Junior!

    1. Hi Kris!

      Thank you for sharing. And you are right! This type of information, like post preview, user data, this is important 🙂

      Thanks again!

  55. Thanks for the wonderful post Junior, it was very helpful.

    I was wondering if anyone has had any success with pagination? I’m trying to use Laravel’s Paginator::make method by passing in my posts that I retrieved using WP_Query. So far, I haven’t been able to get it working yet.

    Any tips or experience with custom pagination?

    Thanks!

    1. Hey all,

      Actually just figured it out. Here’s what I did if anyone is interested:

      // Getting Posts
      $query = new WP_Query(array(
      'post_type' => 'post',
      'posts_per_page' => -1,
      ));
      $posts = $query->get_posts();

      // Pagination
      $perPage = 5;
      $page = Input::get('page', 1);
      if ($page > count($posts) | $page < 1) {
      $page = 1;
      }
      $offset = ($page * $perPage) - $perPage;
      $sliced_posts = array_slice($posts, $offset, $perPage);
      $paginator = Paginator::make($sliced_posts, count($posts), $perPage);

      $this->layout->content = View::make('blog.index' , array(
      'posts' => $paginator
      ));

      1. Hey Mark!

        Thank you for the contribution.

        I think you can use Laravel paginator of many different ways. Personally my experience with Laravel and WordPress together, I used the WordPress pagination, but you can use the Laravel one and your solution works great.

        Thanks for sharing!

  56. Hi,

    First I just want to say thank you Junior Grossi, this is a best of both worlds solution for me.

    I have a question though, would it be possible to use WordPress’ routes instead of laravel in one instance? I’m trying to embed a form from WordPress into a Laravel template via iframe using Gravity forms and https://github.com/bradyver….

    So my question is would it be possible to allow WordPress to handle routing instead of laravel for this url only: cms/gfembed?f=1 (my wordpress directory is cms)

    1. Hi Jeremy!

      Thank you for your comment. When you’re using the Laravel as front-end framework (like I used on the post), you’re using the Laravel routes, but I THINK because we included the WordPress inside Laravel you can use WordPress routes too, but in some way you must disable the Laravel routes OR the Laravel routes must match the WordPress routes (for each page, for example).

      Another solution will be do the inverse, using Laravel inside WordPress. This way you wan use Composer to include only Laravel components you want, like Eloquent or even the entire framework.

      I like to use WordPress inside Laravel just to use the Laravel routes, that are awesome with the MVC architecture.

      Any questions, just ask! Thank you again.

      1. Hi,
        Thanks for the ideas. I would really like to use laravel as the frontend but it would be nice to use the wordpress admin panel and store form entries there with the gravity forms plugin.
        Gravity forms has web API support, so I should be able to POST json data from a form in laravel into the entries section of a gravity forms form, the the routes work like mysite.com/gravityformsapi/… (and so forth).
        For some reason I can hit the route mysite.com/gravityformsapi/… with a GET request and it will return a list of forms but if I try to go any deeper (like mysite.com/gravityformsapi/… I get an error 401 “Not authorized”. I’m not sure if this has anything todo with the routes but I think it might since the GF API access requires pretty permalinks to be enabled. I’ve been trying to modify Laravel’s .htaccess to just ignore all wordpress routes but haven’t had any success.

  57. Hi Junior,

    I’ve been using wordpress for a while, and now I have decided to use learn more from Laravel and all its capabilities. I have a question, regarding routes. I’m new to Laravel

    I followed the instructions as you mentions

    Created a laravel project in my localhost
    Added wordpress on the public directory inside laravel
    Added the headers in the laravel/public/index.php and to the laravel/public/wordpress/index.php

    Now the problem is that when I trying to access wordpress to this URL

    localhost/laravel/public/wordpress

    I get an 404 and redirected to

    localhost/wordpress

    Just in case I’m using MAMP. How do I configure the routes on laravel to take care of wordpress?

    Thx for you help and for you post, hopefully It will help me a lot 🙂

    1. Hi Gabriel!

      I think this is not a problem joining Laravel and WordPress. You have to configure your WordPress with the correct URL to it inside wp-config.php. And for Laravel I suggest you to use the PHP built-in web server.

      To do that go to your Laravel folder and type php artisan serve. After that checkout on your browser http://localhost:8000 to get the Laravel website and http://localhost:8000/wordpress to get the WordPress one. You can too start a new server just for WordPress, going to WordPress folder and php -S localhost:8001, with a different port.

      I hope to help! Thanks for the comment.

    2. Hi Gabriel,

      I had a same problem when after wordpress login I was redirected to 404.
      Problem is in laravel/public/.htacceess

      I just add these linse in laravel/public/.htaccess after RewriteEngine On
      RewriteCond %{REQUEST_URI} ^.*/wordpress/.*
      RewriteRule ^ – [L]

      if your wordpress is in laravel/public/wordpress
      It worked for me

      1. Hi @rumo!

        Thats right! You must change your .htaccess file to inform WordPress where it is located based on your document root. So, using /public/wordpress you have to change the file to /wordpress instead of / only.

        Thanks for the comment. Cheers.

  58. Hi,

    I have added more functionality to the package. Sorry, been waiting to find time to send a pull request. But in the mean time may be this will be useful!

    https://github.com/rajivsee

    I have added Categories, Tags and thumbnail_url of a post.

    Thanks

    1. Hi Rajiv!

      Great job! I read some of your code and that’s great!

      Send me a pull request, because I did not receive nothing.

      Thank you so much. Cheers!

  59. Hey junior, I’m working on a package with wordpress ORM implementions using laravel’s eloquent model classes. take a look! https://github.com/dadleyy/…. There’s still a lot of work to do but I think there is a bit of demand out there for something like this.

      1. feel free to hop in and help out with the code, I need help. wordpress’ database schema has some tricky relationships

  60. The error is inside:
    wp-includes/kses.php

    function wp_kses_named_entities($matches) {
    global $allowedentitynames;

    if ( empty($matches[1]) )
    return '';

    $i = $matches[1];
    return ( ( ! in_array($i, $allowedentitynames) ) ? "&$i;" : "&$i;" );

    }

    1. Carlos the wp_head shows files from your themes folder. Maybe you have to create a fake theme to make it working. I suggest you to debug your app to find why this functions is receiving a null instead of an array. Cheers

  61. I tried with wp_head() but I get this error:

    in_array() expects parameter 2 to be array, null given (View: /Applications/XAMPP/xamppfiles/htdocs/syscover.local/app/views/www/conocimiento/show.blade.php)

  62. hello!
    your work is very interesting, congratulations.

    I have a question, how can you include css and js files of wordpress plugins activated within a blade laravel template?

    Could you help me?

    1. Hi Carlos. Shure! You can use wp_head function without problem. Just call it inside blade. Thanks!

  63. please i’m really confused, been battling with this for too long…
    where do i put these config options… this is just whats left

    $params = array(
    ‘database’ => ‘database_name’,
    ‘username’ => ‘username’,
    ‘password’ => ‘pa$$word’,
    );
    CorcelDatabase::connect($params);

    is it on the
    app/start/global.php file
    or app/config/database.php
    or boostrap/start.php

    i dont know the file to append that script to.. would really need your guide.. and also the part that says

    ” require DIR . ‘/vendor/autoload.php’; “…

    i’m stuck, i’ve not been able to set this config elements..

    i need ur help tanks..

    1. Hi Andaeii. Corcel is based in Laravel Eloquent. If you are already using Laravel 4 you only have to call the class, with no config. Use the Laravel config, just it. Laravel already uses composer and Eloquent.

      If you are using with another framework or pure PHP you have to configure the database.

      Cheers.

      1. if that’s the case, then i suppose i’m on the right path,
        but the problem now is..

        i have i’m trying to output a wordpress post with post_id = 4

        $post = Post::find(4);
        pr($post);

        and it seems not to be working..for get the pr().. i stole that function from cakephp.. i prefer it to laravels dd()…

        what am i not getting right, thanks.

        1. Andaeiii,

          The Post model was created by Corcel, inside it’s namespace. Try to get the post data using CorcelPost::find(4);. It will work, but I suggest you to create your own Post model extending CorcelPost.

          Best regards.

  64. Back for more!

    Have ambitious plans for integrating woocommerce along with everything else.
    If anybody has a solution or ideas please email me @ info [[at]] p-i-x-c-e-l dot com

  65. Damn Grossi you pretty much changed my life. I got my Laravel on my left, my ninjas on my right, and WordPress wherever I want it now. Thanks a mil!

    Andrew

    1. Hi Andrew! I’m glad to help! Thank you for the great comment and welcome to the blog! Cheers!

  66. Hi there,
    I just found your page on google when querying for laravel and wordpress, impressive that you are doing this..best of all worlds I’d say 😉

    I’d be interesting to hear of your progress,
    Pio

    1. I’m glad to hear that Pio! Thank you so much for the comment. I’m currently working on some new features to work with Laravel and WordPress. Thanks! Cheers

  67. Hey – great post! Any advice on how to integrate existing wordpress themes into Laravel Views?

    1. Hi! Thanks!

      The logic is the same! You can get your theme inside Laravel views and work with queries. The only thing I don’t know how to do (yet) is to get the post info automatically inside the Laravel view file, but I will work on it.

      Using Laravel with WordPress brings MVC to WP and you can have more control over your project.

      Thank you for the comment and welcome to the blog. Cheers 😉

      1. I’m trying to figure out from step
        $page = get_post(1234);

        This object has a property, post_content.
        Is there a function that will generate the desired HMTL with header, all the associated widgets and corresponding CSS/JS?

        1. Hi Eugene!

          Thank you for your comment. You can change the way get_header() works or you can use Laravel Blade engine to use layouts, for example.

          To show the post_content you can use the function wpautop. To render JS and CSS files I think the best option is to use the Laravel and not WordPress, but it’s possible too.

          Thank you for the comment and welcome to the blog.

  68. Great idea!

    I tried and start with ‘php artisan serve’. Laravel site is workable, but when I try to access wordpress site, I frequently got

    ( ! ) Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0

    ( ! ) Fatal error: Unknown: Failed opening required ‘server.php’ (include_path=’.:/usr/local/Cellar/php54/5.4.28/lib/php’) in Unknown on line 0

    Then I resort to nginx, it’s all OK. Any idea on php server?

    1. Hi!

      Thank you for commenting on my blog 😉

      When using Laravel and WordPress together you have two options: (1) put WordPress dir inside Laravel public dir /public/wordpress or (2) put WordPress in another place and create another Virtual Host on Apache/Nginx to it, like /wordpress in the same level as Laravel /app, for example.

      To access both WP and Laravel with PHP built in server you have to choose the first option, so you can reach WordPress by http://localhost:8000/wordpress. When using the second option you must access it like http://wordpress.mysite.dev, so Nginx or Apache is required.

      You can start two PHP servers on different ports to work with the second option: So, go inside /wordpress and php -S localhost:8000 and after to go Laravel /public and php -S localhost:8001, for example. Your WordPress will be on http://localhost:8000 and Laravel on http://localhost:8001.

      Any question just ask!

      Cheers!

  69. Good post. I would recommend dropping using WP’s native query and instead let Eloquent handle that. Below is a simple example:
    Set your table prefix to ‘wp_’ in your database.php or simply remember to set the table in your model as show below (Assuming this is your User model).

    protected $table = 'wp_users';

    protected $hidden = array('user_pass');

    public function setUserPassAttribute($pass)
    {
    $this->attributes['user_pass'] = wp_hash_password($pass);
    }

    We add the setUserPassAttribute method so when a user gets saved the system knows to use WP’s hashing algorithm instead of Laravel’s.

    We can now do something like:

    User::all(); // retrieves all users

    which seems simple enough, but get’s really handy when you realize we can also do:

    $post = Post::find($id)
    $user = $post->user()->get();

    1. Hi Marshall!

      Thank you for the excellent contribution. I agree with you Eloquent is much better to use than WordPress native query methods.

      I started a project some time ago exactly to use Eloquent with WordPress. Check it out on GitHub. There are a lot of work to do, but it’s working well at the moment. It allows you to use:

      Post::type('custom_type')->meta->some_meta_key;

      I will update this post and insert some information about it too.

      Thank you again. Best regards.

  70. NICE!!!! I like the part “require DIR.’/../wordpress/wp-blog-header.php’;” that way it’s easy to get the wordpress posts on laravel controllers!!! Very good idea!

    Thanks for sharing!

    1. Thank you Emerson!Working with both WordPress and Laravel you have a powerful tool, using the power of WordPress Admin and Laravel!

      Nice to have you here!

    2. hello guys please i’d be glad if someone showed me how to get Laravel Corcei working.

      $params = array(
      ‘database’ => ‘database_name’,
      ‘username’ => ‘username’,
      ‘password’ => ‘pa$$word’,
      );
      CorcelDatabase::connect($params);

      i’m having serious troubles getting around this part, where do i fix this code, to get it working…

      please, i’d really be glad.

        1. Help me!
          Your requirements could not be resolved to an installable set of packages.

          Problem 1
          – Installation request for jgrossi/corcel ^2.7 -> satisfiable by jgrossi/corcel[v2.7.0].
          – Conclusion: remove laravel/framework v5.4.36
          – Conclusion: don’t install laravel/framework v5.4.36
          – jgrossi/corcel v2.7.0 requires illuminate/filesystem 5.7.* -> satisfiable by illuminate/filesystem[v5.7.0, v5.7.1, v5.7.2, v5.7.3, v5.7.4, v5.7.5, v5.7.6, v5.7.7].
          – don’t install illuminate/filesystem v5.7.0|don’t install laravel/framework v5.4.36
          – don’t install illuminate/filesystem v5.7.1|don’t install laravel/framework v5.4.36
          – don’t install illuminate/filesystem v5.7.2|don’t install laravel/framework v5.4.36
          – don’t install illuminate/filesystem v5.7.3|don’t install laravel/framework v5.4.36
          – don’t install illuminate/filesystem v5.7.4|don’t install laravel/framework v5.4.36
          – don’t install illuminate/filesystem v5.7.5|don’t install laravel/framework v5.4.36
          – don’t install illuminate/filesystem v5.7.6|don’t install laravel/framework v5.4.36
          – don’t install illuminate/filesystem v5.7.7|don’t install laravel/framework v5.4.36
          – Installation request for laravel/framework (locked at v5.4.36, required as 5.4.*) -> satisfiable by laravel/framework[v5.4.36].

          Installation failed, reverting ./composer.json to its original content.

Leave a Reply to Alex Mansour Cancel reply

Your email address will not be published. Required fields are marked *