Site icon WebDevStudios

Attaching Posts with CMB2 for WordPress

CMB2 creates metaboxes and forms with custom fields that will blow your mind. Attached Posts in an extension of this extremely useful plugin.

Every once in a while you may find yourself needing to attach various pieces of content to various other pieces of content within your site. Maybe you want to display a list of related content on a single post but you’re extremely particular about which posts should display as related. Maybe you have a special page template which needs to display various posts as sections or chapters on a single page.

Whatever the case may be, we always seem to find ourselves needing to attach one type of content to another type of content. With CMB2 Attached Posts, we give you that ability.

Sure, there are plugins that will do this for you. Here at WebDevStudios we’ve used Posts 2 Posts quite a bit which is a wonderful plugin allowing you to pair content from one post type to another. Why use CMB2, then? Well, why not?? We want to make CMB2 be and do all that it can, and when the need for relationships between post types came up it seemed like the perfect time to integrate this functionality directly into CMB2.

First things first, you’ll need to check out the CMB2 Attached Posts repo. You’ll drop those files right into your /mu-plugins/ directory, which will register the new CMB2 field type and enqueue the necessary JavaScript and CSS files in the dashboard.

So now that you’ve got that taken care of, let’s go!

First, we need to add the field like we would with any other CMB2 field:

As an added bonus, our own Justin Sternberg just made an update to this functionality on line 15 above. You can now specify the number of posts you want to pull in when using this field type!

Once you’ve got all of your options and parameters set, you’ll wind up with something like this:

Simple, right? This is going to look for posts and display this field ONLY on pages as indicated by the ‘object_types’ value above.

Once you have that in place, you’re ready to start draggin’ and droppin’!

When you update the post you’re editing, you’ll now have these post IDs saved in an array for you to use on the front-end. By rearranging posts, you’re able to rearrange them in the array itself; so, if you need to display this content in a specific order then drag and drop is going to be your best buddy.

Now that you have a nifty little array, you can do something like this do bring these babies to life:

The array stores the ID of each post, so the world is really your stinky little oyster as far as what you want to do with these posts. It’s all up to you!

You can grab CMB2 here: https://github.com/WebDevStudios/CMB2
You can grab CMB2 Attached Posts here: https://github.com/WebDevStudios/cmb2-attached-posts/

Exit mobile version