我需要一个自定义字段作为Wordpress中每个类别的背景色,有人知道吗?
提前感谢:)
将以下代码放入主题的functions.php文件中,供管理员使用。
<?php
add_action('category_add_form_fields', 'add_background_color_field');
add_action('category_edit_form_fields', 'edit_background_color_field');
add_action('edit_term', 'save_background_color_field');
add_action('create_term', 'save_background_color_field');
function add_background_color_field() {
echo '<div class="form-field">
<label for="category_background_color">Background Color</label>
<input type="text" name="category_background_color" id="category_background_color" value="" />
<p class="description">Category Background Color.</p>
</div>';
}
function save_background_color_field($term_id) {
if(isset($_POST['category_background_color']))
update_option('cat_background_color'.$term_id, $_POST['category_background_color']);
}
function edit_background_color_field($category) {
$background_color = get_option('cat_background_color'.$category->term_id);
echo '<tr class="form-field">
<th scope="row" valign="top"><label for="category_background_color">Background Color</label></th>
<td>
<input type="text" name="category_background_color" id="category_background_color" value="'.$background_color.'" />
<p class="description">Category Background Color.</p>
</td>
</tr>';
}
?>
前端使用以下代码。
<?php
$cat_id = get_query_var('cat');
$background_color = get_option('cat_background_color'.$cat_id);
?>
如果要在archive.php或category.php文件中使用类别背景色,请使用$background_color变量值。
您可以使用高级自定义字段插件,然后在函数中获取类别颜色字段值。编写style标记,使用body类,并显示add-attach函数到wp_head。