我有分类列表,有各自的图像。我能够获得类别名称和描述,但无法获得类别图像。我尝试了以下代码。
<ul>
<?php
$categories = get_categories( array(
\'taxonomy\' => \'category\',
\'orderby\' => \'name\',
\'parent\' => 0,
\'hide_empty\' => 0,
) );
foreach ( $categories as $category )
{
$cat_ID = $category->term_id;
$category_name = $category->name;
$category_desc = $category->description;
//$category_img = $category->category_images;
//$category_images = get_option(\'category_images\');?>
<li>
<?php
echo $category_name;
echo $category_desc;
echo $category_images; //display the path of image for temporary
$category_images = get_option(\'category_images\');
?>
</li>
<?php } ?>
</ul>
我得到了
var_dump($category_images)
输出
array(9) {
[17]=>
string(0) ""
[18]=>
string(63) "http://test.com/wp-content/uploads/2020/08/reghwij.png"
[19]=>
string(63) "http://test.com/wp-content/uploads/2020/08/hgeioiq.jpg"
[21]=>
string(88) "http://test.com/wp-content/uploads/2020/07/dan-freeman-m4-wkz4GV04-unsplash.png"
[22]=>
string(68) "http://test.com/wp-content/uploads/2020/07/green-breaks.jpg"
}
var\\u转储($类别)输出
SO网友:Tim
在代码中,您将图像存储在wp_options
带键的表格category_images
, 但是没有任何东西告诉WordPress在加载分类术语(您的类别)时必须获取图像。
你可以使用get_option(\'category_images\')
无论何时需要获取图像,或添加这样的挂钩过滤器。
add_filter( \'get_term\', function ( WP_Term $_term, string $taxonomy ): WP_Term
{
if ( \'my_taxonomy_name\' === $taxonomy ) {
$images = get_option( \'category_images\' );
if ( $image = ( $images[ $_term->term_id ] ?? null ) ) {
$_term->background_image = $image;
}
}
return $_term;
}, 10, 2 );
然后您将拥有
background_image
获取分类术语时添加的属性。