Magento 2 / WordPress Integration Code Examples

First Published: October 22, 2015

This article explains how to work with the models, resources and collections offered by Magento WordPress Integration.

The code examples below will use the ObjectManager to simplify the examples but you can just as easily include the classes in your constructor and make use of dependency injection.

Please get in touch if there is anything that we have missed.

Posts (Posts, Pages & Custom Post Types)

The FishPig\WordPress\Model\Post object represents posts of all types. For example, a Page in WordPress is just a Post with the post_type field set to 'page'. Therefore a Post object can represent any post type, including custom post types.

To make use of custom post types, you will need to install the Post Types & Taxonomies add-on extension for Magento 2.

Load a Post

// This example uses the Object Manager but you should use DI to inject
// \FishPig\WordPress\Model\PostRepository in your class constructor
$objectManager = \Magento\Framework\App\ObjectManager::getInstance()

// Get the PostRepository class
$postRepository = $objectManager->get(\FishPig\WordPress\Model\PostRepository::class);

// Load the post by a specific ID
$post = $postRepository->get(123);
// If this fails, an exception will be thrown

// Get a post with post_type=page && ID=123
$post = $postRepository->getWithType(123, 'page');

// Get a post with post_type IN (post, page) && ID=123
$post = $postRepository->getWithType(123, ['post', 'page']);

Get Data from a Post

// Get the post_title field
echo $post->getName();

// Get the post_content field
echo $post->getContent();

// Get the post_excerpt field
echo $post->getPostExerpt();

// If no post excerpt is set, this code gets the post_content and shortens it to 50 words
echo $post->getPostExcerpt(50);

// Get the post's permalink/URL
echo $post->getUrl();

// Determine if the post is published
echo $post->isPublished() ? 'Published' : 'Not Published';

// Get the post date. You can $pass the date format as a parameter for a custom format
echo $post->getPostDate();

Get Images from a Post

// Get a the Featured Image from a Post object
if ($image = $post->getImage()) {

  // Show available image sizes (eg. thumbnail, medium, large etc)
  var_dump($image->getSizes());

  // Get first found image URL for array of codes
  echo $image->getImageUrl(['large', 'medium']);

  // Another way to call $image->getImageUrl($code) is to use the magic method:
  // $image->getMediumImage()
  // This is in the format $image->get{IMAGECODE}Image()
  // Here are some more examples
  echo $image->getThumbnailImage(); // $image->getImageUrl('thumbnail')
  echo $image->getMediumImage(); // $image->getImageUrl('medium')
  echo $image->getLargeImage(); // $image->getImageUrl('large')
  echo $image->getPostThumbnailImage(); // $image->getImageUrl('post_thumbnail')

  // Get the URL of the full size image
  // This will be the original uploaded image size
  echo $image->getFullSizeImage();

  // This gets the first image it finds
  // This is the same as:
  // $image->getImageUrl($image->getSizes())
  echo $image->getAvailableImage();

  // Get the image ALT text
  echo $image->getAltText();

  // Get the image description
  echo $image->getDescription();

  // Get the image title
  echo $image->getTitle();

  // Get the image caption
  echo $image->getCaption();
}

Get Related Objects (eg. Categories, Users etc) from a Post

// Get the User model that created the Post
// For more information on the User object, see the User section below
$user = $post->getUser();

// Get the child posts of $post if $post is from a hierarchical post type (ie. pages)
$childPosts = $post->getChildrenPosts();

// Get a collection of Categories related to the Post
$categoryCollection = $post->getTermCollection('category');

// Get a collection of Tags related to the Post
$tagsCollection = $post->getTermCollection('post_tags');

// Get a collection of terms from a custom taxonomy that are related to the Post
$customTaxonomyCollection = $post->getTermCollection('custom_taxonomy_type');

// Prints out a list of the terms as links (eg. Term1, Term2 & Term3)
echo $post->getTermCollectionAsString('category');

// Get the previous post
$previousPost = $post->getPreviousPost();

// Get the next post
$nextPost = $post->getNextPost();

Post Collections

The \FishPig\WordPress\Model\ResourceModel\Post\Collection object is used for post collections and includes posts of any post_type.

// This example uses the Object Manager but you could just
// include FishPig\WordPress\Model\ResourceModel\Post\CollectionFactory in your constructor
$objectManager = \Magento\Framework\App\ObjectManager::getInstance()

// Get the CollectionFactory class
$collectionFactory = $objectManager->get(
    \FishPig\WordPress\Model\ResourceModel\Post\CollectionFactory::class
);

// Create an empty Post Collection object
$postCollection = $collectionFactory->create();

// Filter by a single post_type
$postCollection->addPostTypeFilter('page');

// Filter by multiple post_type values
$postCollection->addPostTypeFilter(['post', 'page']);

// Allow any post_type value
$postCollection->addPostTypeFilter('*');

// Filter the posts by a single category (ID=4)
$postCollection->addTermIdFilter(4, 'category');

// Filter the posts by multiple category IDs
$postCollection->addTermIdFilter([4, 5], 'category');

// Filter the posts by the ID of a custom taxonomy
$postCollection->addTermIdFilter([7, 12], 'your_custom_taxonomy');

// Filter the posts by a term slug
// This example filters the posts by the category slug 'uncategorized'
$postCollection->addTermFilter('uncategorized', 'category', 'slug');

// Filter the posts by a term name
// This example filters the posts by the category slug 'Uncategorized'
$postCollection->addTermFilter('Uncategorized', 'category', 'name');

// Filter by a parent ID. Works for posts of an hierarchical post_type
$postCollection->addPostParentIdFilter(96);

// Adds the is_sticky value to each post in the collection
// You can then call $post->isSticky()
$postCollection->addStickyPostsToCollection();

// Filter the posts so only viewable (published and public) posts are included
$posts->addIsViewableFilter();

// Limit the collection of posts
$posts->setPageSize(30);

// Load the collection. Call $posts->load(true) to see the SQL query
$posts->load();

// Check if collection has posts and then loop through
if (count($posts) > 0) {
    foreach ($posts as $post) {
        echo sprintf(
            '%d: %s (%s)%s',
            $post->getId(),
            $post->getName(),
            $post->getPostType(),
            '<br/>'
        );
    }
}

Back to top

Terms (Categories, Tags and Custom Taxonomies)

In WordPress, categories and tags are stored using the term and taxonomy system. The taxonomy part represents the type of data and each data record is stored as a term. Using categories as an example, the taxonomy type is 'category' and the individual categories are all terms. By default, the two main taxonomy types in WordPress are 'category' (ie. post categories) and 'post_tag' (ie. post tags) but you can create your own.

In Magento WordPress Integration, all terms are represented by the \FishPig\WordPress\Model\Term class and have their 'taxonomy' field set accordingly.

To make use of custom taxonomies, you will need to install the Post Types & Taxonomies add-on extension for Magento.

Load a Term

// This example uses the Object Manager but you could just
// include FishPig\WordPress\Model\TermRepository in your constructor
$objectManager = \Magento\Framework\App\ObjectManager::getInstance()

// Get the TermFactory class
$termRepository = $objectManager->get(\FishPig\WordPress\Model\TermRepository::class);

// Load the Term by a specific ID
$term = $termRepository->get(123);
// This throws an exception is it fails

// Get a term where taxonomy=category && term_id=123
$term = $termRepository->getWithTaxonomy(123, 'category');

// Get a term where taxonomy IN (category, post_tag) && term_id=123
$term = $termRepository->getWithTaxonomy(123, ['category', 'post_tag']);

Get Data from a Term

// Get the Term name
echo $term->getName();

// Get the current taxonomy type (eg. category)
echo $term->getTaxonomy();

// Get the taxonomy label (eg. Categories or Tags)
echo $term->getTaxonomyLabel();

// Get the parent ID of the term
echo $term->getParentId();

// Get the term URL
echo $term->getUrl();

Get Related Objects

// Get the parent term. Returns false if no parent
$parentTerm = $term->getParentTerm();

// Get the child terms for a hierarchical term
$childTerms = $term->getChildrenTerms();

// Get all posts that belong to $term
$posts = $term->getPostCollection();

// Get the number of posts that belong to $term
echo $term->getItemCount();

Term Collections

The FishPig\WordPress\Model\ResourceModel\Term\Collection object is used for term collections and includes terms of any taxonomy.

// This example uses the Object Manager but you could just
// include FishPig\WordPress\Model\ResourceModel\Post\CollectionFactory in your constructor
$objectManager = \Magento\Framework\App\ObjectManager::getInstance()

// Get the CollectionFactory class
$collectionFactory = $objectManager->get(
    \FishPig\WordPress\Model\ResourceModel\Term\CollectionFactory::class
);

// Create an empty Term Collection object
$termCollection = $collectionFactory->create();

// Filter the collection by slug
$terms->addSlugFilter('some_slug');

// Filter the collection by a taxonomy
$terms->addTaxonomyFilter('category');

// Filter the collection by a parent ID
$terms->addParentIdFilter(93);

// Filter a collection by a post so that all terms related to post are included
$terms->addPostIdFilter(95);

Back to top

Users

The FishPig\WordPress\Model\User object represents a user. This includes Admin users as well as frontend users setup in WordPress.

Load a User

// This example uses the Object Manager but you could just
// include FishPig\WordPress\Model\UserFactory in your constructor
$objectManager = \Magento\Framework\App\ObjectManager::getInstance()

// Get the UserFactory class
$userRepository = $objectManager->get(\FishPig\WordPress\Model\UserRepository::class);

// Load the user by a specific ID
$user = $userRepository->get(123);

// Load a user by their nicename
$user = $userRepository->getByNicename('joebloggs');

// Load a user by an email
$user = $userRepository->getByField('joe@bloggs.com', 'user_email');

// Load a user by username
$user = $userRepository->getByField('admin', 'user_login');

Get Data from a User

// Get the users username
echo $user->getUserLogin();

// Get the users email
echo $user->getUserEmail();

// Get the users level
echo $user->getUserLevel();

// Get the users first name
echo $user->getFirstName();

// Get the users last name
echo $user->getLastName();

// Get the users nickname
echo $user->getNickname();

// Get the URL of the users Gravatar image
// You can pass a pixel size. Defaults to 50 - echo $user->getGravatarUrl(150);
echo $user->getGravatarUrl()

// Get the users description
echo $user->getContent();

Back to top

Custom Meta Values (Custom Fields)

WordPress provides meta functionality for Post, Term and User objects and this allows you to store extra data against the object in the related meta table.

Get a Meta Value

// Get a meta value from a Post object
echo $post->getMetaValue('your_meta_field_name');

// Get a meta value from a Term object
echo $term->getMetaValue('your_meta_field_name');

// Get a meta value from a User object
echo $user->getMetaValue('your_meta_field_name');

Meta Field and Object Collections

Post collections, Term collections and User collection all have access to the Meta methods listed below.

// Add a meta field to the columns part of the SELECT query
$collection->addMetaFieldToSelect('your_meta_field_name');

// Add a filter for a Meta field to the WHERE part of the query
$collection->addMetaFieldToFilter(
  'your_meta_field_name',
  'Change this to the value you want to match'
);

// You can use standard filter values from addAttributeToFilter
$collection->addMetaFieldToFilter(
  'your_meta_field_name',
  ['like' => '%Some Value%']
);

// Add a meta field to the ORDER part of the query
$collection->addMetaFieldToSort('your_meta_field_name', 'asc');

Back to top