Wordpress Force Post to select category

2019-05-27 12:58发布

问题:

i am using WordPress post to build post.is there any plugin or some function that warn be when i don't select a category for the post.its a headache ever time i post a category i miss some time as there is a lot of post to be made in the category after some time see those post in uncategory its a great headache.

add_theme_support('menus');

**

**> the above code is nothing because stack over flow doesn't allow me to

post my question as it say standard low.**

** thanks in advance. hope i could find one suitable answer

回答1:

hah.. its so funny but you can try as below in your functions.php file

function force_post_categ_init() 
{
  wp_enqueue_script('jquery');
}
function force_post_categ() 
{
  echo "<script type='text/javascript'>\n";
  echo "
  jQuery('#publish').click(function() 
  {
    var cats = jQuery('[id^=\"taxonomy\"]')
      .find('.selectit')
      .find('input');
    category_selected=false;
    for (counter=0; counter<cats.length; counter++) 
    {
        if (cats.get(counter).checked==true) 
        {
            category_selected=true;
            break;
        }
    }
    if(category_selected==false) 
    {
      alert('You have not selected any category for the post. Please select post category.');
      setTimeout(\"jQuery('#ajax-loading').css('visibility', 'hidden');\", 100);
      jQuery('[id^=\"taxonomy\"]').find('.tabs-panel').css('background', '#F96');
      setTimeout(\"jQuery('#publish').removeClass('button-primary-disabled');\", 100);
      return false;
    }
  });
  ";
   echo "</script>\n";
}
add_action('admin_init', 'force_post_categ_init');
add_action('edit_form_advanced', 'force_post_categ');

NOte:- javascript must be enable to run this



回答2:

I would suggest using a jQuery object to read the real value of the input since the page can be loaded with a checked value and then an input can be un-checked and saved. This uses the jQuery object .is('checked') method:

function force_post_categ() 
{
    $custom_js = <<<CUSTOM_JS
    <script type='text/javascript'>
    jQuery('#publish').click(function() 
    {

      var cats = jQuery('[id^="taxonomy"]').find('.selectit').find('input');
      category_selected = false;

      $.each(cats, function(key,value){
          if ( $(this).is(':checked') == true ) {
            category_selected = true;
            return false;
          }
      });

      if (category_selected == false) 
      {
        alert('You have not selected any metro or country for the post. Please select a metro.');
        setTimeout("jQuery('#ajax-loading').css('visibility', 'hidden');", 100);
        jQuery('[id^="taxonomy"]').find('.tabs-panel').css('background', '#F96');
        setTimeout("jQuery('#publish').removeClass('button-primary-disabled');", 100);
        return false;
      }
    });
    </script>
CUSTOM_JS;

    echo $custom_js;
}