主页上带有缩略图和描述的类别列表

时间:2010-12-26 作者:Scott B

我真的需要一个全面的解决方案,所以我提供了近四分之一的代表悬赏:)

我想有一个插件,在我的主页上创建一个自定义类别列表。要做到这一点,我希望“类别编辑”屏幕可以增加一些额外的功能,如下所述。。。

将“上载/删除图像”处理程序添加到给定类别的类别编辑屏幕(这允许最终用户上载用于表示类别的图像。理想情况下,上载时插件应自动将其大小调整为125像素宽。

  • 添加“类别标题”给定类别的类别编辑屏幕的输入字段。这是对现有默认“名称”字段的补充生成的标记应该是一个没有嵌套的无序列表,就像这样。。。

    <ul class="custom-categories">
        <li>
            <span><a href="link-to-category-1"><img src="the-category-1-image" /></a></span>
            <a href="link-to-category-1">Category 1 Title</a> The category description text goes here
        </li>
        <li>
            <span><a href="link-to-category-2"><img src="the-category-2-image" /></a></span>
            <a href="link-to-category-2">Category 2 Title</a> The category description text goes here
        </li>
        etc...
    </ul>
    
    这是我启动的存根文件。。。

    add_filter( \'the_content\', \'cb_category_listing\' );
    
    function cb_category_listing( $content )
    {
        if ( is_home() ) {
            $cat_args[\'title_li\'] = \'\';
            $cat_args[\'exclude_tree\'] = 1;
            $cat_args[\'exclude\'] = 1;
            $myContent = wp_list_categories(apply_filters(\'widget_categories_args\', $cat_args)); 
            $content .= $myContent;
        }
        return $content;
    }
    

  • 3 个回复
    最合适的回答,由SO网友:sanchothefat 整理而成

    注意:这适用于较早版本的WP<;3.9在引入新媒体上传之前,这里介绍了如何在类别编辑屏幕上添加字段和保存值,以及添加图像上传字段的方法。

    向类别编辑屏幕添加字段要开始,我们需要在类别编辑屏幕上显示一些代码。

    add_action( \'edit_category_form_fields\', \'my_category_custom_fields\' );
    add_action( \'edit_category\', \'save_my_category_custom_fields\' );
    
    function my_category_custom_fields( $tag ) {
        // your custom field HTML will go here
        // the $tag variable is a taxonomy term object with properties like $tag->name, $tag->term_id etc...
    
        // we need to know the values of our existing entries if any
        $category_meta = get_option( \'category_meta\' );
        ?>
        <tr class="form-field">
            <th scope="row" valign="top"><label for="category-title"><?php _e("Title"); ?></label></th>
            <td>
                <input id="category-title" name="category_meta[<?php echo $tag->term_id ?>][title]" value="<?php if ( isset( $category_meta[ $tag->term_id ] ) ) esc_attr_e( $category_meta[ $tag->term_id ][\'title\'] ); ?>" />
                <span class="description"><?php _e(\'Enter an alternative title for this category.\'); ?></span>
            </td>
        </tr>
        <!-- rinse & repeat for other fields you need -->
        <?php
    }
    
    存储自定义值的最简单方法是在options表中(实际上应该有一个分类法元表,但没关系)。这样,我们只需进行一次查询即可获得所有类别的元数据。如果有人对存储有更好的想法,那就大声说出来!

    function save_my_category_custom_fields() {
        if ( isset( $_POST[\'category_meta\'] ) && !update_option(\'category_meta\', $_POST[\'category_meta\']) )
            add_option(\'category_meta\', $_POST[\'category_meta\']);
    }
    
    对于复选框,您只需存储true或false,以便使用category_extras[$tag->term_id][show_on_home] 并使用存储在中的值$category_meta 确定是否已检查。

    您可能想在save函数中添加一些额外的处理或消毒-我的只是一个简单的例子。

    图像字段

    这是一段相当复杂的代码,因此我不会在这里全部解释,但注释描述了每个函数的用途。如果你愿意,我们可以在评论中讨论。

    以下功能添加到类别编辑屏幕的链接,该屏幕将弹出wordpress媒体库/图像上传弹出窗口。然后,您可以上载图片并单击以使用它。然后,您就可以使用上面的另一个元数据获得图像ID和缩略图url。

    // add the image size you need
    add_image_size( \'category_thumb\', 125, 125, true );
    
    // setup our image field and handling methods
    function setup_category_image_handling() {
        // add the image field to the rest
        add_action( \'edit_category_form_fields\', \'category_image\' );
    
        global $pagenow;
        if ( is_admin() ) {
        add_action( \'admin_init\', \'fix_async_upload_image\' );
        if ( \'edit-tags.php\' == $pagenow ) {
            add_thickbox();
            add_action(\'admin_print_footer_scripts\', \'category_image_send_script\', 1000);
        } elseif ( \'media-upload.php\' == $pagenow || \'async-upload.php\' == $pagenow ) {
            add_filter( \'media_send_to_editor\', \'category_image_send_to_editor\', 1, 8 );
            add_filter( \'gettext\', \'category_image_replace_text_in_thickbox\', 1, 3 );
        }
        }
    }
    add_action( \'admin_init\', \'setup_category_image_handling\' );
    
    // the taxonomy edit screen image field
    function category_image( $tag ) {
        // get our category meta data
        $category_meta = get_option(\'category_meta\');
        ?>
               <tr class="form-field hide-if-no-js">
                   <th scope="row" valign="top"><label for="taxonomy-image"><?php _e("Image"); ?></label></th>
                   <td>
                       <div id="taxonomy-image-holder">
                   <?php if( !empty($category_meta[$tag->term_id][\'image\']) ) { ?>
                       <img style="max-width:100%;display:block;" src="<?php echo esc_attr( $category_meta[ $tag->term_id ][\'image\'][\'thumb\'] ); ?>" alt="" />
                       <a id="taxonomy-image-select" class="thickbox" href="media-upload.php?is_term=true&amp;type=image&amp;TB_iframe=1"><?php _e(\'Change image\'); ?></a>
                       <a class="deletion" id="taxonomy-image-remove" href="#remove-image">Remove image</a>
                   <?php } else { ?>
                       <a id="taxonomy-image-select" class="thickbox" href="media-upload.php?is_term=true&amp;type=image&amp;TB_iframe=1"><?php _e(\'Choose an image\'); ?></a>
                   <?php } ?>
                       </div>
                       <input type="hidden" name="category_meta[<?php echo $tag->term_id ?>][image][id]" value="<?php if( isset($category_meta[ $tag->term_id ][\'image\'][\'id\']) ) echo esc_attr($category_meta[ $tag->term_id ][\'image\'][\'id\']); ?>" class="tax-image-id" />
                       <input type="hidden" name="category_meta[<?php echo $tag->term_id ?>][image][thumb]" value="<?php if( isset($category_meta[ $tag->term_id ][\'image\'][\'thumb\']) ) echo esc_attr($category_meta[ $tag->term_id ][\'image\'][\'thumb\']); ?>" class="tax-image-thumb" />
                   <span class="description"><?php _e(\'A category image.\'); ?></span></td>
               </tr>
        <?php
    }
    
       // required for uploading images on non post/page screens
       function fix_async_upload_image() {
           if(isset($_REQUEST[\'attachment_id\'])) {
               $GLOBALS[\'post\'] = get_post($_REQUEST[\'attachment_id\']);
           }
       }
    
       // are we dealing with the taxonomy edit screen?
       function is_category_context() {
           if ( isset($_SERVER[\'HTTP_REFERER\']) && strpos($_SERVER[\'HTTP_REFERER\'],\'is_term\') !== false ) {
               return true;
           } elseif ( isset($_REQUEST[\'_wp_http_referer\']) && strpos($_REQUEST[\'_wp_http_referer\'],\'is_term\') !== false ) {
               return true;
           } elseif ( isset($_REQUEST[\'is_term\']) && $_REQUEST[\'is_term\'] !== false ) {
               return true;
           }
           return false;
       }
    
       // replace Insert Into Post text with something more appropriate
       function category_image_replace_text_in_thickbox($translated_text, $source_text, $domain) {
           if ( is_category_context() ) {
               if (\'Insert into Post\' == $source_text) {
                   return __(\'Use this image\', MB_DOM );
               }
           }
           return $translated_text;
       }
    
       // output a script that sets variables on the window object so that they can be accessed elsewhere
       function category_image_send_to_editor( $html, $id, $attachment ) {
           // context check might not be necessary, and, might not work in all cases
           if ( is_category_context() ) {
               $item = get_post($id);
               $src = wp_get_attachment_image_src($id,\'thumbnail\',true); // 0 = url, 1 = width, 2 = height, 3 = icon(bool)
               ?>
               <script type="text/javascript">
                   // send image variables back to opener
                   var win = window.dialogArguments || opener || parent || top;
                   win.TI.id = <?php echo $id ?>;
                   win.TI.thumb = \'<?php echo $src[0]; ?>\';
               </script>
               <?php
           }
           return $html;
       }
    
       // write out the javascript that handles what happens when a user clicks to use an image
       function category_image_send_script() { ?>
           <script>
               self.TI = {};
               var tb_position;
    
               function send_to_editor(h) {
                   // ignore content returned from media uploader and use variables passed to window instead
                   jQuery(\'.tax-image-id\').val( self.TI.id );
                   jQuery(\'.tax-image-thumb\').val( self.TI.thumb );
    
                   // display image
                   jQuery(\'#taxonomy-image-holder img, #taxonomy-image-remove\').remove();
                   jQuery(\'#taxonomy-image-holder\')
                       .prepend(\'<img style="max-width:100%;display:block;" src="\'+ self.TI.thumb +\'" alt="" />\')
                       .append(\'<a class="deletion" id="taxonomy-image-remove" href="#remove-image">Remove image</a>\');
    
                   jQuery(\'#taxonomy-image-select\').html(\'Change image\');
    
                   // close thickbox
                   tb_remove();
               }
    
               (function($){
                   $(document).ready(function() {
    
                       tb_position = function() {
                           var tbWindow = $(\'#TB_window\'), width = $(window).width(), H = $(window).height(), W = ( 720 < width ) ? 720 : width;
    
                           if ( tbWindow.size() ) {
                               tbWindow.width( W - 50 ).height( H - 45 );
                               $(\'#TB_iframeContent\').width( W - 50 ).height( H - 75 );
                               tbWindow.css({\'margin-left\': \'-\' + parseInt((( W - 50 ) / 2),10) + \'px\'});
                               if ( typeof document.body.style.maxWidth != \'undefined\' )
                                   tbWindow.css({\'top\':\'20px\',\'margin-top\':\'0\'});
                           };
    
                           return $(\'a.thickbox\').each( function() {
                               var href = $(this).attr(\'href\');
                               if ( ! href ) return;
                               href = href.replace(/&width=[0-9]+/g, \'\');
                               href = href.replace(/&height=[0-9]+/g, \'\');
                               $(this).attr( \'href\', href + \'&width=\' + ( W - 80 ) + \'&height=\' + ( H - 85 ) );
                           });
                       };
                       $(window).resize(function(){ tb_position(); });
    
                       $(\'#taxonomy-image-select\').click(function(event){
                           tb_show("Choose an image:", $(this).attr("href"), false);
                           return false;
                       });
                       $(\'#taxonomy-image-remove\').live(\'click\',function(event){
                           $(\'#taxonomy-image-select\').html(\'Choose an image\');
                           $(\'#taxonomy-image-holder img\').remove();
                           $(\'input[class^="tax-image"]\').val("");
                           $(this).remove();
                           return false;
                       });
                   });
               })(jQuery);
           </script>
           <?php
       }
    
    访问my_function bit取自您自己的答案,然后您可以访问元数据,如下所示:

    function my_function(){
        $args=array(
        \'orderby\' => \'name\',
        \'order\' => \'ASC\'
        );
        $categories=get_categories($args);
    
        // get our category meta data and exit out if there isn\'t any
        $category_meta = get_option(\'category_meta\');
        if ( !$category_meta )
            return;
    
        echo \'<ul style="list-style-type:none;margin:0;padding:0">\';
        foreach($categories as $category) {
            // skip unticked categories & categories with no meta data
            if ( !isset( $category_meta[ $category->term_id ] ) || ( isset( $category_meta[ $category->term_id ] ) && !$category_meta[ $category->term_id ][\'show_on_home\'] ) )
                continue;
            echo \'<li><a style="display:block;margin-top:20px;" href="\' . get_category_link( $category->term_id ) . \'" title="\' . sprintf( __( "View all posts in %s" ), $category->name ) . \'" \' . \'>\' . $category_meta[ $category->term_id ][\'title\'].\'</a>\';
            if ( "" != $category_meta[ $category->term_id ][\'image\'][\'id\'] )
                echo wp_get_attachment_image( $category_meta[ $category->term_id ][\'image\'][\'id\'], \'category_thumbnail\', false, array( \'alt\' => $category->name, \'class\' => \'\' ) );
            echo $category->description . \'</li>\';
            } 
        echo \'</ul>\';
    }
    

    SO网友:Wyck

    简单的方法就是这样http://wordpress.org/extend/plugins/category-images/ . 或者你可以自己写钩子。

    SO网友:Scott B

    这是我第一次尝试。。。

    add_filter( \'the_content\', \'cb_category_listing\' );
    
    function cb_category_listing( $content )
    {
        if ( is_home() ) {
            $cat_args[\'title_li\'] = \'\';
            $cat_args[\'exclude_tree\'] = 1;
            $cat_args[\'exclude\'] = 1;
            $myContent = wp_list_categories(apply_filters(\'widget_categories_args\', $cat_args)); 
            $content .= $myContent;
        }
        return $content;
    }
    
    显然,这只是创建一个类别名称列表,其中包含指向每个类别的链接。所以这让我开始了。然而,我仍然需要。。。

    一种将类别缩略图图像与每个类别相关联的方法,并将其显示在上面代码中的类别列表中。

    除类别名称外,还包括自定义类别标题,并将其显示在类别列表上(代替“类别名称”)

    一种显示/隐藏列表中每个类别的方法。理想情况下,带有复选框“显示在主页列表上”,可以在类别的编辑屏幕上进行编辑。

    这是我的最新代码。到了那里,但仍然没有处理缩略图图像或添加自定义字段(缩略图图像,自定义标题,显示/隐藏)到类别编辑器管理。。。

    function _add_my_filter() {
        if ( is_home() OR is_sticky() )
        {
        add_filter( \'the_content\', \'my_function\' );
        }
    }
    add_action(\'template_redirect\', \'_add_my_filter\');
    
    function my_function(){
        $args=array(
        \'orderby\' => \'name\',
        \'order\' => \'ASC\'
        );
        $categories=get_categories($args);
        echo \'<ul style="list-style-type:none;margin:0;padding:0">\';
        foreach($categories as $category) { 
            echo \'<li><a style="display:block;margin-top:20px;" href="\' . get_category_link( $category->term_id ) . \'" title="\' . sprintf( __( "View all posts in %s" ), $category->name ) . \'" \' . \'>\' . $category->name.\'</a>\';
            echo $category->description . \'</li>\';
            } 
        echo \'</ul>\';
    }
    

    结束

    相关推荐