阻止帖子在我的插件中有多个类别

时间:2012-09-10 作者:Shafiul

我正在写一个插件,我想防止帖子有多个类别(即同一产品有“三星”和“苹果”类别)。您知道如何使用我的插件使用一些操作/过滤器来实现这一点吗?

2 个回复
SO网友:Joshua Abenazer

请尝试以下代码。这将把类别分类复选框转换为单选按钮。这样,只能选择一个类别。

add_filter(\'wp_terms_checklist_args\', \'wpse_64691_one_category_only\', \'\', 2);
function wpse_64691_one_category_only( $args, $post_id){
    $args[\'walker\'] = new WPSE_64691_Category_Radio;
    return $args;
}

class WPSE_64691_Category_Radio extends Walker {
    var $tree_type = \'category\';
    var $db_fields = array (\'parent\' => \'parent\', \'id\' => \'term_id\'); //TODO: decouple this

    function start_lvl( &$output, $depth = 0, $args = array() ) {
            $indent = str_repeat("\\t", $depth);
            $output .= "$indent<ul class=\'children\'>\\n";
    }

    function end_lvl( &$output, $depth = 0, $args = array() ) {
            $indent = str_repeat("\\t", $depth);
            $output .= "$indent</ul>\\n";
    }

    function start_el( &$output, $category, $depth, $args, $id = 0 ) {
            extract($args);
            if ( empty($taxonomy) )
                    $taxonomy = \'category\';

            if ( $taxonomy == \'category\' )
                    $name = \'post_category\';
            else
                    $name = \'tax_input[\'.$taxonomy.\']\';

            $class = in_array( $category->term_id, $popular_cats ) ? \' class="popular-category"\' : \'\';
            if ( $taxonomy == \'category\' )
                $output .= "\\n<li id=\'{$taxonomy}-{$category->term_id}\'$class>" . \'<label class="selectit"><input value="\' . $category->term_id . \'" type="radio" name="\'.$name.\'[]" id="in-\'.$taxonomy.\'-\' . $category->term_id . \'"\' . checked( in_array( $category->term_id, $selected_cats ), true, false ) . disabled( empty( $args[\'disabled\'] ), false, false ) . \' /> \' . esc_html( apply_filters(\'the_category\', $category->name )) . \'</label>\';
            else
                $output .= "\\n<li id=\'{$taxonomy}-{$category->term_id}\'$class>" . \'<label class="selectit"><input value="\' . $category->term_id . \'" type="checkbox" name="\'.$name.\'[]" id="in-\'.$taxonomy.\'-\' . $category->term_id . \'"\' . checked( in_array( $category->term_id, $selected_cats ), true, false ) . disabled( empty( $args[\'disabled\'] ), false, false ) . \' /> \' . esc_html( apply_filters(\'the_category\', $category->name )) . \'</label>\';
    }

    function end_el( &$output, $category, $depth = 0, $args = array() ) {
            $output .= "</li>\\n";
    }
}

SO网友:jocken

有一些jquery插件可以将类别复选框更改为单选按钮Making category selection radio buttons. 然而,这并不是一个纯粹安全的解决方案。您可以使用

add_action(\'publish_post\', \'your_function\');
在函数中执行var\\u转储以查看实际发生的情况。然后,您还将看到是否检查了超过个类别。

function your_function($content){
  var_dump($content);

  //Check if more than one category is checked, return false and don\'t publish
}
您还可以查看:Running a function in Wordpress when publishing a custom post type

结束