Magento WordPress Shortcodes & Widgets Code Examples

« Back to Magento WordPress Shortcodes & Widgets

WordPress shortcodes entered directly into a WordPress post or page will be automatically converted into HTML. For shortcodes else where on Magento, you will need to use some PHP to get the shortcode to display. The WordPress code for this is the do_shortcode function but you should never use this directly in Magento. Instead you should use one of the equivalent pieces of code below.

Using a Shortcode in Magento 1

The code below can be used in any Magento class or template file. The shortcode used is for the Gravity Forms plugin but any shortcode should work fine.

echo Mage::helper('wordpress/filter')->doShortcode('[gravityforms id="1"]');

Using a Shortcode in Magento 2

In Magento 2, if you're in a WordPress block/template, the renderShortcode method will be available to you as part of the block, making it really easy to use shortcodes.

echo $this->doShortcode('[gravityforms id="1"]');

If the above doesn't work, you're probably in a block/template that doesn't inherit from FishPig\WordPress\Block\AbstractBlock. In this case, you will need to get the ShortcodeManager object. This example uses the Object Manager to simplify the code but the same could be achieved using constructor injection.

// Get the Object Manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

// Get the ShortcodeManager class
$shortcodeManager = $objectManager->get('FishPig\WordPress\Model\ShortcodeManager');

// You can call doShortcode or renderShortcode, both do the same
echo $shortcodeManager->doShortcode('[gravityforms id="1"]');

Using a Shortcode in a Magento 2 WYSIWYG Editor

If you're adding content to a WYSIWYG editor, you won't be able to use PHP. Instead, you can use the pre-made block to add shortcodes.

{{block class="FishPig\WordPress\Block\Shortcode" shortcode="[contactform7 id=\"123\"]"}}

One important thing to note is that any " in the shortcode must be escaped using a slash (eg. \") so id="123" becomes id=\"123\"

Magento WordPress
Shortcodes & Widgets
Documentation Articles

Post your comment

FishPig Ltd