Download the PHP package wp4laravel/wp4laravel without Composer
On this page you can find all versions of the php package wp4laravel/wp4laravel. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package wp4laravel
WP4Laravel - A headless Wordpress concept
Table of contents
- Table of contents
- Supported versions
- The concept
- Dependencies
- Installation
- Gitignore
- Composer
- Environment file.
- Database config
- Service provider
- Install Corcel
- Publish public data
- Storage
- Remove unused migrations
- Install WordPress
- Basic usage
- References
- Advanced Custom Fields
- Wordpress configuration
- Add plugins
- How do I use it?
- Yoast Premium
- Redirects
- Multilanguage
- Translatable models
- Translatable taxonomies
- Making translatable menu's
- Best practices
- Create your own models for each post type
- Register your post types
- Catch-all your pages
- Setup your homepage
- Get the url of a page
- Rendering \ tags
- Configuration
- Usage
- Using ImageFake in the styleguide
- Using the MenuBuilder to construct menus
- Example usage
- Translated menu's
- Activate WP preview function
- SEO tags for models
- Hosting assets on S3
- Requirements
- Usage
- RSS-feeds
- Example usage
The concept
WP4Laravel is by default a standard Laravel project. Instead of using a relational database it uses WordPress as Content Management System.
The benefits relative to a standard WordPress Setup:
- Use MVC-principles
- Better performance
- Flexibility
- Sustainability
- Security
The benefits relative to a standard Laravel project:
- No need to create a custom CMS
- Get the best of great WordPress plugins
- For commercial purposes, you can sell the customer a WordPress CMS.
Dependencies
The basis of WP4Laravel is just a fresh Laravel install. We add three open source projects in the mix:
- WordPress as a dependency (https://github.com/johnpbloch/wordpress)
- Corcel: Get WordPress data with Eloquent (https://github.com/corcel/corcel)
- Wordplate: Standard theme and plugin for WordPress (only for inspiration, not actually installed)
Installation
Start a fresh Laravel install: https://laravel.com/docs/10.x/installation
Gitignore
Add the following rules to your .gitignore
Composer
To use WordPress as a dependency, you need to extend your composer.json. Add a repositories section to the composer.json and ad the following repositories:
Add an 'extra' section to the composer.json, to determine where to install Wordpress and plugins.
Add the following packages to your installation by executing on the command-line:
Environment file.
- Add the WordPress salts to your .env file, with http://wordplate.github.io/salt/
- Make sure you added a database and added your database credentials to your .env file.
- Make sure the APP_URL environment variable, matches your local environment.
- Remove all settings that are not needed for your project, such as redis and email.
Database config
Copy the default mysql connection and name it 'wordpress'. Set the table prefix of the database connection to 'wp_' in config/database.php
.
Service provider
Note: Only if using Laravel 5.4 or below.
Add the Service Provider of the WP4Laravel package to your config/app.php
Install Corcel
Publish the corcel config file:
Open the app/corcel.php config file and define your database connection.
If you're using Laravel 5.4 or earlier, you need to configure the CorcelServiceProvider. Add the following line to your config/app.php under "Package Service Providers":
Publish public data
Unfortunately, the base theme and config of WordPress has to be inside the webroot. You can publish these from WP4LaravelServiceProvider.
Storage
All WordPress media will be saved in the location of the Laravel Public storage. To make this work, run the following Artisan command to make a symbolic link in your webroot.
Remove unused migrations
If you're only using tables managed by WordPress, it's recommended to remove the default migrations generated by Laravel. These files are in database/migrations/
.
Install WordPress
Go to /wp/wp-admin to setup your WordPress project.
Basic usage
Edit the default web route in your Laravel
Replace the 'Laravel' heading in resources/views/welcome.blade.php
by {{ $post->title }}
.
Open your project in the browser, you will see 'Hello World!' as heading.
References
- Read the docs of Corcel before you start: https://github.com/corcel/corcel
Advanced Custom Fields
What makes WordPress a real CMS? Right: Advanced Custom Fields. To implement this concept we use 2 packages
- The Advanced Custom Fields WordPress plugin
- The Corcel ACF plugin to fetch ACF data from a Corcel / Eloquent model.
The Corcel ACF plugin is a direct dependency of WP4Laravel and is automatically installed. To get the ACF 5 PRO plugin in WordPress using composer, follow the instructions on https://github.com/PhilippBaschke/acf-pro-installer. Alternatively, if you don't have a license for ACF Pro, you can use the free version:
Look at the docs of Corcel (https://github.com/corcel/acf) for the usage of Corcel with ACF.
Wordpress configuration
Within /public/themes/wp4laravel/library
you can update the WordPress configuration. Most used for configuring post types and taxonomies. Every post type kan be defined in the directory post types. En example is already included. For taxonomies, it works the same.
If you want to define your post types and taxonomies with a WordPress plugin, that's no problem.
Add plugins
Because WordPress and his plugins are dependencies, you can only use plugins which are available with composer.
WordPress Packagist comes straight out of the box with WP4Laravel. It mirrors the WordPress plugin as a Composer repository.
How do I use it?
Require the desired plugin using wpackagist-plugin
as the vendor name.
Plugins are installed to public/plugins
.
Please visit WordPress Packagist website for more information and examples.
Yoast Premium
WP4Laravel has some support for key features of Yoast Premium, mostly rendering SEO tags and following redirects.
Redirects
Redirect can be enabled by adding the included middleware to the middleware-stack. You probably want to do this in the web
middleware group in app/Http/Kernel.php
:
The middleware will automatically check if the request should be redirected, and return the redirect instead of handling the original request. Note that the redirect is handled in middleware and takes precedence over any existing routing. Take care not to define redirects over critical pages in your website.
Multilanguage
WP4Laravel contains various options to work with multilanguage-enabled websites. These solutions are based on using the free version of Poylang (plugin, wpackagist).
Translatable models
A Translatable trait is included for working with the Polylang plugin. Include this trait in your models to gain access to useful properties for working with translated versions of posts.
Including the trait with add a language
scope for use with Eloquent and a language
property.
It also includes a translations
property which yields a collection, keyed by the language code, of all available translations of a given post.
Translatable taxonomies
Similarly to translating models, WP4Laravel also supports translating taxonomies. For this, you must enable the taxonomy to be translated in WP-Admin > Languages > Settings > Custom post Types and Taxonomies. To use the translation information on the website, create a model for the taxonomy and add the TranslatableTaxonomy-trait:
The trait creates a scope on the model language(string)
which can be used to filter terms:
Making translatable menu's
The MenuBuilder has a utility function to work with menu's that have been translated using Polylang. First, configure your theme to have various menu locations. These are the slots on your website in which a menu is going to be displayed. Each entry has a location identifier and description:
Polylang will automatically make translated locations for every language you specify. Use the Wordpress admin interface to create a menu and assign it to a location. Than, call the MenuBuilder::menuForLocation($slot, $language)
method call to find the appropriate menu for a location. It returns a basic Corcel\Model\Menu
class. This method supports both translated and untranslated menu structures.
Best practices
Create your own models for each post type
If you want to take advantage of the power of Eloquent, we advise to create a Laravel model for each of your post types.
For example, you can add accessors to make life easier.
Register your post types
When you access a post type from a specific model, you have to register this. You can do this to match a post_type with the dedicated model in the config/corcel.php file. For example:
config/corcel.php
If you choose to create a new class for your custom post type, you can have this class be returned for all instances of that post type.
Catch-all your pages
First you have to make sure you define your catch-all route at the bottom of your routes file:
Route:
Create a PageController with the show method inside:
PageController:
Page Model:
Setup your homepage
Note: This feature is available since version 0.7
Use a specific controller for your homepage or use the index method in your PageController for the homepage. Select in WordPress in Settings/Reading the page which you want to use as Homepage.
Get the url of a page
Note: This feature is available since version 0.7
The Pageurl trait includes a getUrlAttribute method which generated the url of a page. This will include the path if a page has a parent.
Rendering \<picture> tags
WP4Laravel includes a helper template and ViewProvider to correctly render \<picture>-tags with crops, etc. This works correctly for both ThumbnailMeta and Image-classes.
Configuration
The included configuration file config/picture.php
can be adapted to your project configuration. Copy the file to your project by executing:
Note that this will copy the theme files, etc. as well. Change the included options to match your local URL, or the S3-setup.
Usage
Crops must be named 'header_desktop_1x', 'header_mobile_2x', 'header_mobile_1x', 'header_mobile_14x' etc. Configure in Wordpress as follows:
Use the following snippet in your blade views:
This results for example in the following output:
Configuring breakpoints is optional: not setting them will result in no
Note that using multiple \<source>-tags requires the use of media queries, so while the following example will generate output and not crash, the W3 Validator will throw an error on your generated HTML. Don't do this.
Using ImageFake in the styleguide
Images are complex objects in the WordPress/Corcel-environment, and mocking them is not trivial. This presents problems: if you design a component that renders some HTML and a inner image using WP4Laravel\Picture
, you need to create a pretty complex structure to have all the necessary fields available.
For this use case, we offer a fake class: WP4Laravel\ImageFake
. This fake class presents the necessary fields and methods to appear as valid option to WP4Laravel\Picture and can be used in the styleguide to render components that contain images. Note that ImageFake is only suitable for use with Picture, as it is a partial fake.
An example: suppose you have a component named "pretty_picture" that renders a single image + figure and caption. The component HTML looks like this:
You can use this component on the website as such, where $block->fields->image is an instance of either ThumbnailMeta or Image, and $captionText is a string:
In the styleguide, you can use ImageFake instead:
The alt-text is optional. ImageFake requires that you always specify at least the 'full' option, as that is the case for real images too. The minimum data you'll need to add is thus:
Using the MenuBuilder to construct menus
WP4Laravel supplies a MenuBuilder utility class that can calculate the correct menu for you. You can use the class in a ViewComposer for example. This class correctly deals with using the custom title of a menu item or the post title when none is set.
The MenuBuilder class has a single public method itemsIn($menu)
which returns a Collection of top-level items in the menu. Each entry has an id
(int), title
(string), active
(whether this item should be "selected", boolean) and url
(string) property. Additionally, each item has a target
property (boolean). If set, you should open the link in a new tab. Make sure to set rel=noopener too to prevent cross-site scripting and performance problems.
This class supports a single level of nesting (two levels in total). Root-level items have a children
(Collection) property with a list of their immediate child entries. Additionally, a root-level item has a boolean childActive
property which is true if any of its children have the active
flag set.
The MenuBuilder requires that your model has a url
property that contains the canonical URL of an instance of the model.
Example usage
Add a URL property on your model. For example, when using a custom slug in the URL and a multilanguage-based setup:
Add a view:
Add a ViewComposer for that view:
Alternatively, you can use the MenuBuilder-facade to gain a static interface:
Translated menu's
The MenuBuilder has support for translating menu's in various languages. See Making translatable menu's for instructions.
Activate WP preview function
Note: This feature is available since version 0.7
With a few simple steps you can activate the preview function of WordPress. Unfortunately the preview URL's are not secured!
-
Make sure you have a named route for a detail page of each post type, like:
-
Open config/corcel.php and append a preview array to map post types to named routes. Below an example:
- When you want to preview a post which is not yet published, the Wordpress endpoint for the preview is your homepage added with some GET parameters. To catch these parameters you have to append a specific middleware to your homepage route. When the middleware matches a preview, it will redirect to the defined route of the post type, like 'blog.show'. As slug will be used "__preview".
Note: You are free to implement the middleware on your own way, more info at the Laravel Docs
-
Append the Preview trait to you dedicated models:
- Make sure each model has a static method called current. This method will be used to select the current post based on the url. In most cases this method looks like:
Excepts for a page which can have a parent, use the following if your Page models uses the Pageurl trait.
- In your controller use the static method publishedOrPreview method to get your current post or a preview.
SEO tags for models
Creating the right SEO-tags depends on defining what the "primary" model instance is of this page. On the page of a news item, this is likely the news item itself. For an index page, you might want to create a specific page (with or without content) just so that you have place to configure Yoast.
The primary instance for a site is set on the Site. You usually do this in every controller action that renders a page.
Add the Seo-trait to your models:
This trait adds a seo-attribute $post->seo
which contains an array of all meta keys and their appropriate values. You can render all appropriate properties using:
Hosting assets on S3
The Corcel libraries doesn't support media posts from external storage like an S3 bucket. This wrapper adds this support to get url's of the original files but also the url's of the generated thumbnails.
Requirements
- Laravel configured with S3 storage
- WordPress configured with the S3 Offload plugin
Usage
Get the url of the featured image of a post
The same from the site container in a blade template
Get the url of the 'large' crop from the media object
Get the url of an ACF Image field
Because of the main usage in a blade template, the S3Media object does not generate exceptions. If something is wrong (bad input, file not exists) the url() and site() methods just returns null.
RSS-feeds
This feature requires WP4Laravel 0.8.0 or later
WP4Laravel has built-in rudimentary support for generating RSS-feeds. Use as follows:
The first argument is a (Eloquent) Collection of all items you want included in your feed (note: these items must be
instances or subclasses of Corcel\Model\Post
). The second parameter is the title included of the feed.
Example usage
Add a route in your routes/web.php
file:
and add a method to your controller:
All versions of wp4laravel with dependencies
jgrossi/corcel Version ^7.0.0
wp4laravel/corcel-acf Version ~0.1.0