0

I've set up a custom post type and removed the content editor. I'd like to put a widget area in its place and show the widgets when you view the post on the front-end, but the widget areas need to be specific to each post.

Is this possible?

1 Answer 1

0

Assuming that your theme still has the_content to populate that area you can use the_content filter to populate is. Because widgets normally echo their output you would also need to buffer output. Like this:

add_filter ('the_content','wpse304648_widget_content');
function wpse304648_widget_content ($content) {
  if (get_post_type == 'your_cpt_name') {
    ob_start ();
    .. execute widget
    $content = ob_get_contents();
    ob_end_clean();
    }
  return $content;
  }

Now, the question is how to execute a widget in this function. You are talking about creating a separate widget area for every post. That would clutter your admin widget page, but it is possible. In your functions.php you can loop through all your custom posts and register a sidebar in the usual way. Then in your widget admin define a bunch of widgets for every sidebar. If you register sidebars with the name 'your-cpt-name-ID' you can easily call them like this:

dynamic_sidebar ( 'your-cpt-name-'. get_the_ID());

It seems more logical to build your own widget that loads content depending on the post. In that case you only have to define one sidebar.

5
  • Thanks for your answer cjbj but maybe I wasn't clear what I was after - rather than using the admin widget page, these widget areas would appear individually on the admin post edit page, essentially acting like a simpler version of a 'page-builder' plugin. Maybe using widget areas isn't the best option, but it was the first thing that came to mind which might do what I'm trying to do, so I'm open to other ideas for a drag/drop one-column page builder too.
    – AJT
    May 28, 2018 at 18:22
  • Also, I'm building this as a standalone plugin so I'd like to avoid anything theme-dependent if possible.
    – AJT
    May 28, 2018 at 18:23
  • But do you want any widget to be available in the custom post or just a bunch you are providing in your plugin?
    – cjbj
    May 28, 2018 at 18:57
  • I'd like both, ideally
    – AJT
    May 28, 2018 at 20:37
  • If you want external widgets, you'll have to hack the widget admin interface into the post edit interface in some way. Perhaps doable, but don't hold your breath. Otherwise, I'd look into shortcodes, which are meant to facilitate complex building blocks in the post edit page.
    – cjbj
    May 29, 2018 at 11:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.