0

I've tried to solve my problem in the simplest way, but it doesn't work: why?

  function createNewWidgetSavingAPost($post_id) {


        add_action( 'widgets_init', function(){

            $new_widget = new myWdgetClass("widget_id");

            register_widget( $new_widget );

          });

   }

 add_action('save_post', 'createNewWidgetSavingAPost', 10);
  • It doesn't make any sense to only register a widget when a post is saved. Widgets need to be registered on every page load. Are you trying to add a specific instance of a widget to a sidebar? – Jacob Peattie Aug 26 '18 at 4:00
1

As you can see from the hook order, widget_init is a hook that is quite early in the page execution order. So, by the time save_post is fired widget_init has already passed. If you add an action to a hook that has already passed, nothing will happen.

  • Perhaps if you describe what you are trying to do, we can advise a suitable solution? There are ways to list posts in widgets. Do you really want a widget for every new post ? It's not impossible (you could update an option each time a post is saved, then have code early on look up the options and create a widget for each post) BUT may not be the best way to address what you are trying to achieve? Also It would never show anywhere unless it got added to a sidebar. – anmari Aug 26 '18 at 5:45
  • Sure. I Would like create a widget when a new post (custom post type: "widget") is created. To make this, I thought to create the widget when saving, with the idea of adding later a line of code like "if (!thiswidget) { createAWidget() }"... – AmintaCode Aug 26 '18 at 17:21
  • As explained it is pointless to create a widget when a new post is created, because soon afterwards the page refreshes and the widget is gone. You probably mean something else, but it is unclear what. – cjbj Aug 27 '18 at 8:38

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.