• Stars
    star
    309
  • Rank 132,367 (Top 3 %)
  • Language
    PHP
  • License
    GNU General Publi...
  • Created over 10 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Integrate Symfony with WordPress and WordPress with Symfony

EkinoWordpressBundle

Build Status SensioLabsInsight

This bundle is used to bring some Symfony services into Wordpress and manipulates Wordpress using Symfony.

Here are some features:

  • Use custom Symfony services into Wordpress,
  • Use Symfony to manipulate Wordpress database,
  • Create custom Symfony routes out of Wordpress,
  • When authenticated on Wordpress, authenticated on Symfony too with correct user roles. (requires ekino-wordpress-symfony Wordpress plugin)
  • Catch some Wordpress hooks to be dispatched by Symfony EventDispatcher (requires ekino-wordpress-symfony Wordpress plugin)

Installation

Idea of this installation tutorial is to have WordPress rendered by web root with the following architecture:

project
|-- wordpress (web root)
|-- symfony (not available over HTTP)

1) Install Symfony and WordPress

Install your Wordpress project in a wordpress directory by unzipping the latest WordPress sources from https://www.wordpress.org. Install Symfony using composer (for instance, or new Symfony Installer tool) in a symfony directory:

$ php composer.phar create-project symfony/framework-standard-edition symfony/

2) Install ekino/wordpress-bundle into Symfony's project

Edit symfony/composer.json file to add this bundle package:

"require": {
    ...
    "ekino/wordpress-bundle": "dev-master"
},

Run php composer.phar update ekino/wordpress-bundle

Then, add the bundle into symfony/app/AppKernel.php:

<?php
    public function registerBundles()
    {
        $bundles = array(
            ...
            new Ekino\WordpressBundle\EkinoWordpressBundle(),
        );

        ...

        return $bundles;
    }

Add the WordpressBundle routing file in your symfony/app/config/routing.yml, after your custom routes to catch all Wordpress routes:

...
ekino_wordpress:
    resource: "@EkinoWordpressBundle/Resources/config/routing.xml"

Edit your configuration and specify the following options in your app/config.yml:

ekino_wordpress:
    globals: # If you have some custom global variables that WordPress needs
        - wp_global_variable_1
        - wp_global_variable_2
    table_prefix: "wp_" # If you have a specific Wordpress table prefix
    wordpress_directory: "%kernel.root_dir%/../../wordpress"
    load_twig_extension: true # If you want to enable native WordPress functions (ie : get_option() => wp_get_option())
    enable_wordpress_listener: false # If you want to disable the WordPress request listener
    security:
        firewall_name: "secured_area" # This is the firewall default name
        login_url: "/wp-login.php" # Absolute URL to the wordpress login page

Also optionally, if you want to use UserHook to authenticate on Symfony, you should add this configuration to your symfony/app/security.yml:

security:
    providers:
        main:
            entity: { class: Ekino\WordpressBundle\Entity\User, property: login }

    # Example firewall for an area within a Symfony application protected by a WordPress login
    firewalls:
        secured_area:
            pattern:    ^/admin
            access_denied_handler: ekino.wordpress.security.entry_point
            entry_point: ekino.wordpress.security.entry_point
            anonymous: ~

    access_control:
        - { path: ^/admin, roles: ROLE_WP_ADMINISTRATOR }

3) Update your WordPress index.php file to load Symfony libraries

<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Retrieves or sets the Symfony Dependency Injection container
 *
 * @param ContainerInterface|string $id
 *
 * @return mixed
 */
function symfony($id)
{
    static $container;

    if ($id instanceof ContainerInterface) {
        $container = $id;
        return;
    }

    return $container->get($id);
}

$loader = require_once __DIR__.'/../symfony/var/bootstrap.php.cache';

// Load application kernel
require_once __DIR__.'/../symfony/app/AppKernel.php';

$sfKernel = new AppKernel('dev', true);
$sfKernel->loadClassCache();
$sfKernel->boot();

// Add Symfony container as a global variable to be used in Wordpress
$sfContainer = $sfKernel->getContainer();

if (true === $sfContainer->getParameter('kernel.debug', false)) {
    Debug::enable();
}

symfony($sfContainer);

$sfRequest = Request::createFromGlobals();
$sfResponse = $sfKernel->handle($sfRequest);
$sfResponse->send();

$sfKernel->terminate($sfRequest, $sfResponse);

4) In the case you expose Symfony only

To avoid problem with some Wordpress plugin, you need to wrap web/app.php code inside a function like this:

<?php
use Symfony\Component\HttpFoundation\Request;

// change for app_dev.php
function run(){
    $loader = require_once __DIR__.'/../var/bootstrap.php.cache';

    require_once __DIR__.'/../app/AppKernel.php';

    $kernel = new AppKernel('dev', true);
    $kernel->loadClassCache();
    Request::enableHttpMethodParameterOverride();
    $request = Request::createFromGlobals();
    $response = $kernel->handle($request);
    $response->send();
    $kernel->terminate($request, $response);
}
run();

5) Edit .htaccess file on your WordPress root project directory

Put the following rules:

DirectoryIndex index.php

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]

    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule ^index\.php(/(.*)|$) %{ENV:BASE}/$2 [R=301,L]

    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule .? - [L]

    # Rewrite all other queries to the front controller.
    RewriteRule .? %{ENV:BASE}/index.php [L]
</IfModule>

<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        RedirectMatch 302 ^/$ /index.php/
    </IfModule>
</IfModule>

You're ready to go.


Use in Symfony

You can call Wordpress table managers in Symfony by calling the following services:

Service identifier Type
ekino.wordpress.manager.comment Wordpress comment manager
ekino.wordpress.manager.comment_meta Wordpress comment metas manager
ekino.wordpress.manager.link Wordpress link manager
ekino.wordpress.manager.option Wordpress option manager
ekino.wordpress.manager.post Wordpress post manager
ekino.wordpress.manager.post_meta Wordpress post metas manager
ekino.wordpress.manager.term Wordpress term manager
ekino.wordpress.manager.term_relationships Wordpress term relationships manager
ekino.wordpress.manager.term_taxonomy Wordpress taxonomy manager
ekino.wordpress.manager.user Wordpress user manager
ekino.wordpress.manager.user_meta Wordpress user metas manager

So in custom Symfony controllers, you can create / update / delete data in Wordpress database, like that:

# Here an example that sets user #2 as author for post #1
$postManager = $this->get('ekino.wordpress.manager.post');
$userManager = $this->get('ekino.wordpress.manager.user');

$user = $userManager->find(2);

$post = $postManager->find(1);
$post->setAuthor($user);

$postManager->save($post);

Use in WordPress

Call a service from Symfony container

Simply use the symfony() method and call your custom service like that:

$service = symfony('my.custom.symfony.service');

Override

Entities

For every Wordpress entities, you can override the default classes. To do so, just add the following configuration in your config.yml (for Post entities):

ekino_wordpress:
    services:
        post:
            class: MyApp\AppBundle\Entity\Post

In order to avoid further troubles when creating a new instance (for example), remember to always use the manager to create a new entity ($container->get('ekino.wordpress.manager.post')->create()).

Managers

You can use your own managers too. To customize it, register yours as services β€” should be marked as privates β€” as follow :

ekino_wordpress:
    services:
        comment:
            manager: my_custom_comment_service

Your manager will now be reachable using the usual command, IE from a controller : $this->get('ekino.wordpress.manager.comment')

Repositories

Implementing your custom repository classes is as simple as follow :

ekino_wordpress:
    services:
        comment_meta:
            repository_class: MyApp\MyBundle\Repository\ORM\CustomCommentMetaRepository

Extra

Enable cross application I18n support

If you already have a wordpress plugin to handle I18n, EkinoWordpressBundle allow to persist language toggle between Symfony and wordpress. To do so, just grab the cookie name from the wordpress plugin used and provide its name in the configuration as follow :

ekino_wordpress:
    i18n_cookie_name: pll_language # This value is the one used in "polylang" WP plugin

Also, you can implement your own language switcher in Symfony that work cross application. For instance :

<?php

namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;

class LanguageController extends Controller
{
    /**
     * @param Request $request
     * @param string $locale
     *
     * @return RedirectResponse
     */
    public function toggleLocaleAction(Request $request, $locale)
    {
        $response = new RedirectResponse($this->generateUrl('homepage'));
        $response->headers->setCookie(new Cookie($this->getWpCookieName(), $locale, time() + 31536000, '/', $request->getHost()));

        return $response;
    }

    /**
     * @return string
     */
    protected function getWpCookieName()
    {
        return $this->container->getParameter('ekino.wordpress.i18n_cookie_name');
    }
}

Handling password protected posts

If you use password protected posts and you have defined your own COOKIEHASH constant, you can provide it using the cookie_hash parameter in your config.yml file. You will then be able to use the wp_post_password_required twig function that behave exactly like post_password_required Wordpress function.

Display Wordpress theme into a Symfony Twig-rendered route

You can display the WordPress header (with administration menu bar if available), sidebar and footer into your Symfony's Twig templates by using the following Twig functions available in this bundle:

{{ wp_get_header() }}
{{ wp_get_sidebar() }}

<div id="main">
    Your Twig code comes here
</div>

{{ wp_get_footer() }}

More Repositories

1

EkinoNewRelicBundle

Add NewRelic support to Symfony
PHP
280
star
2

phpstan-banned-code

Detect banned code through PHPStan
PHP
194
star
3

veggies

✨ πŸš€ Veggies is an awesome cucumberjs library for API/CLI testing. Great for testing APIs built upon Express, Koa, HAPI, Loopback and others. It's also the perfect companion for testing CLI applications built with commander, meow & Co.
JavaScript
89
star
4

EkinoDrupalBundle

Integrate Symfony2 with Drupal 7 and vice-versa.
PHP
72
star
5

php-mirroring

[deprecated] Packagist and Github mirroring
PHP
55
star
6

docker-buildbox

Docker images for GitLab CI's jobs
Dockerfile
55
star
7

ekino-wordpress-symfony

PHP
43
star
8

docker-neo4j-cluster

🐳 Up & Running Neo4j cluster in no time
Shell
41
star
9

php-hal-client

HalClient is a lightweight PHP library to consume HAL resources.
PHP
33
star
10

php-metric

This library provides base classes to collect and publish metrics.
PHP
33
star
11

drupal-debug

Alternative Kernel for Drupal 8 to improve the Developer eXperience during the development process.
PHP
31
star
12

docker-wiremock

🐳 WireMock is a flexible library for stubbing and mocking web services
25
star
13

jcv

JSON Content Validator (JCV) allows you to compare JSON contents with embedded validation.
Kotlin
21
star
14

docker-monitoring-stack

🐳 Full monitoring stack : Collectd > InfluxDB > Grafana
Shell
19
star
15

node-logger

A Lightweight logger that combines debug namespacing capabilities with winston levels and multioutput
JavaScript
18
star
16

EkinoMetricBundle

Integrate Ekino PHP Metric into Symfony2
PHP
14
star
17

ek-winjs-kinect

Kinect V2 project for javascript web application
PowerShell
13
star
18

webpack-cheatsheet

πŸ”· Ekino Webpack Cheat Sheet Project
JavaScript
13
star
19

golisten

Listen and notify on files change
Go
9
star
20

spring-boot-starter-errors

Opiniated Spring Boot starter that handles common exceptions and returns them in a standardize json format
Kotlin
9
star
21

ekino-tools-version

Scala
8
star
22

node-config

Lightweight config module based on yaml that supports overrides based on environment (prod, dev ..) and environment values
JavaScript
8
star
23

jcv-idea-plugin

IntelliJ IDEA plugin for an enhanced coding experience on JCV based projects.
Kotlin
7
star
24

git-hooks

git hooks used in our PHP team
Shell
7
star
25

wiremock-unused-stubs-junit

Kotlin
7
star
26

devbox

Shell
6
star
27

jcv-db

JSON Content Validator for Database (JCV-DB) allow you to compare database contents against a JSON with JCV validators.
Kotlin
6
star
28

ekino_drupal_symfony2

A drupal module which integrates the EkinoDrupalBundle
PHP
6
star
29

knex-extra

A set of helpers to be used with knexjs
TypeScript
6
star
30

hands-on-react

hands-on-react
CSS
6
star
31

golang-hands-on

Go
5
star
32

rendr

A SSR toolkit for Headless CMS and more.
PHP
5
star
33

hibernate-crypto-types

Provides new hibernate column types to encrypt your column data before being stored in your database
Kotlin
5
star
34

docker-elk-stack

🐳 A decoupled ELK stack using docker : Elasticsearch Logstash on one side / Kibana on the other
Shell
5
star
35

gradle-quality-plugin

Quality plugin applying some configuration for your builds (checkstyle, jacoco, sonarqube)
Kotlin
5
star
36

wp-oam-renderer

Allows and renders OAM (Adobe Edge Animate) files in your Wordpress posts
PHP
5
star
37

gradle-java-plugin

Java plugin applying some configuration for your builds (mavenPublish, testSets, etc ...)
Kotlin
5
star
38

node-api-toolkit

A set of Node.js modules to ease Node.js API development
TypeScript
5
star
39

oh-my-mustache

Kotlin
4
star
40

sonata

PHP
4
star
41

kotlin-quality-plugin

Gradle quality plugin for kotlin projects
Kotlin
4
star
42

EkinoDataProtectionBundle

A Symfony bundle to protect data through encryption
PHP
4
star
43

docker-newman

🐳 Docker image to easily start Newman, the command-line collection runner for Postman
3
star
44

godim

Golang Dependency Injection Management
Go
3
star
45

jcv-examples

Examples of the JCV library usages (see: https://github.com/ekino/jcv )
Kotlin
3
star
46

docker-symfony-wordpress

PHP
3
star
47

phpstan-sonata

PHP
3
star
48

docker-gcsfuse

Docker image that contains gcsfuse. Can be used as a side container to mount a GCS bucket
Dockerfile
3
star
49

NewsFakeToken

An NFT for tracing Fake News
TypeScript
3
star
50

docker-compose-elk

🐳 Up&Running elasticsearch+logstash+kibana application (official images)
Shell
3
star
51

test-end2end-jmeter

JavaScript
2
star
52

webpack-plugin-assets-to-map

Create a Json or TOML or YAML file with webpack chunks
JavaScript
2
star
53

docker-rp-lb

🐳 Reverse Proxies and Load Balancers inside containers
Shell
2
star
54

behat-helpers

Helpers for Behat
PHP
2
star
55

starfight

Java
2
star
56

gradle-docker-plugin

Docker plugin applying some configuration for your builds
Kotlin
2
star
57

JTrans4mers

JTrans4mers : A Java tool to easily map an Object to an Enum.
Java
1
star
58

docker-nginx-brotli

Provide a nginx with brotli support
Python
1
star
59

expresso

TypeScript
1
star
60

post-3-nlp

The repository for an Ekino blog post on NLP
Jupyter Notebook
1
star
61

docker-chefdk

🐳 Docker image with ChefDK
Vim Script
1
star
62

spring-reactive-perf

HTML
1
star
63

EkinoTinyPngSonataMediaBundle

A Symfony bundle to optimize sonata media images through tinyPNG API
PHP
1
star
64

terraform-provider-greseller

Terraform provider to add Google Reseller resources
Go
1
star
65

smuggler

A simple interface to manipulate Nock HTTP mocks.
TypeScript
1
star