Magento WordPress Integration Code ExamplesWordPress Integration

« Back to Magento WordPress Integration

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 could just
// include FishPig\WordPress\Model\PostFactory in your constructor
$objectManager = \Magento\Framework\App\ObjectManager::getInstance()

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

// Use PostFactory to create an empty Post model
$post = $postFactory->create();

// You can set any post type here or you use * to select from all post types
// If not set, this defaults to post
$post->setPostType('post');

// Load the post by a specific ID
$post->load(123);

// Check whether the post was loaded
if ($post->getId()) {
  echo $post->getId() . ': ' . $post->getName();
}
else {
  echo 'Post could not be loaded';
}

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()) {
  
  // Get the URL of the thumbnail image
  echo $image->getThumbnailImage();

  // Get the URL of the medium sized image
  echo $image->getMediumImage();

  // Get the URL of the large image
  echo $image->getLargeImage();

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

  // Get the post thumbnail image URL
  echo $image->getPostThumbnailImage();

  // Get a custom image size that you specified in WordPress
  echo $image->getImageByType('your_custom_image');
  
  // Work through these images and get the first available image
  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');

// 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\TermFactory in your constructor
$objectManager = \Magento\Framework\App\ObjectManager::getInstance()

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

// Use TermFactory to create an empty Term model
$term = $termFactory->create();

// You can set any taxonomy here or you use * to select from all taxonomies
// If not set, this defaults to *
$term->setTaxonomy('category');

// Load the Term by a specific ID
$term->load(123);

// Check whether the post was loaded
if ($term->getId()) {
  echo $term->getId() . ': ' . $term->getName();
}
else {
  echo 'Term could not be loaded';
}

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');

// 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
$userFactory = $objectManager->get('FishPig\WordPress\Model\UserFactory');

// Use UserFactory to create an empty Post model
$user = $userFactory->create();

// Load the user by a specific ID
$user->load(123);

// Load a user by an email
$user->loadByEmail('joe@bloggs.com');

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

// Check whether the post was loaded
if ($user->getId()) {
  echo $user->getId() . ': ' . $user->getUserLogin();
}
else {
  echo 'User could not be loaded';
}

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