Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何根据类别向图像添加类?_Php_Function_Wordpress Theming - Fatal编程技术网

Php 如何根据类别向图像添加类?

Php 如何根据类别向图像添加类?,php,function,wordpress-theming,Php,Function,Wordpress Theming,我需要能够:1.)为图像指定类别,2.)为所有与其指定类别对应的图像添加类 我可以通过以下方式为图像添加类别: function ug_add_categories_to_attachments() { register_taxonomy_for_object_type( 'category', 'attachment' ); } add_action( 'init' , 'ug_add_categories_to_attachments' ); 我找到了一个函数,可以为图像添加一个类

我需要能够:1.)为图像指定类别,2.)为所有与其指定类别对应的图像添加类

我可以通过以下方式为图像添加类别:

function ug_add_categories_to_attachments() {
    register_taxonomy_for_object_type( 'category', 'attachment' );
}
add_action( 'init' , 'ug_add_categories_to_attachments' );
我找到了一个函数,可以为图像添加一个类,如下所示:

function add_image_class($class){
    $class .= ' additional-class';
    return $class;
}
add_filter('get_image_tag_class','add_image_class');
但我对php的了解还不够深入。我试过这个

function ug_add_image_class($class){
    foreach(get_the_category() as $cat) { $class .= ' category-'.$cat->slug; };
    return $class;
}
add_filter('get_image_tag_class','ug_add_image_class');
但是没有爱


帮忙?思想?请星期五快乐

非常感谢birgire在参考url上提供的答案:

/**
 * Append the image categories to the current image class.
 *
 * @see http://wordpress.stackexchange.com/a/156576/26350
 */

add_filter( 'get_image_tag_class', 
    function( $class, $id, $align, $size )
    {
        foreach( (array) get_the_category( $id ) as $cat ) 
        { 
            $class .= ' category-' . $cat->slug; 
        }
        return $class;
    }
, 10, 4 );