我有一个由插件制作的组件,可以显示一个自定义帖子类型的文章列表。每篇文章都有相关联的post-id类,我不能在子主题中覆盖插件的文件来循环生成列表,所以我需要创建一个功能。我不能在子主题中覆盖插件的文件来循环生成列表的模板,所以我需要在function.php中创建一个函数。我需要的是用一个新的div替换文章中的div,这个div的样式是用高级自定义字段插件制作的自定义字段(颜色选择器),这个字段是动态关联到每一篇文章的。
loop {
display: flex;
width: 100%;
}
article {
width: 200px;
height: 200px;
background: red;
margin:20px;
display:flex;
justify-content:center;
align-items:center;
}
.overlay {
width:150px;
height:150px;
}
<article class="portfolio-item post-53">
<div class="overlay" style="background-color:#000"></div>
</article>
<article class="portfolio-item post-65">
<div class="overlay" style="background-color:#000"></div>
</article>
<article class="portfolio-item post-70">
<div class="overlay" style="background-color:#000"></div>
</article>
function insert_custom_div() {
$args = array(
'meta_key' => 'new_color',
'post_type' => 'portfolio-item'
);
$posts = get_posts($args);
foreach ($posts as $post):
$color_picker_custom_field = get_field('new_color', $post->ID);
if ($color_picker_custom_field) {
?>
<script>
jQuery( document ).ready( function() {
jQuery('article').append('<div class="overlay post-<?php echo $post->ID; ?>" style="background-color:<?php echo $color_picker_custom_field; ?>"></div>');
});
</script>
<?php
}
endforeach;
}
add_action('wp_head','insert_custom_div');
你可以从每篇文章中获取新的颜色到数组,然后将数组传递给javascript,用 json_encode()
这里是修改过的你的代码片段,我不确定是否能用,因为html注入到functions.php是不好的做法,最好在模板中做。好吧,这只是思路的方向。
<?php
$new_div = array();
foreach ($posts as $post):
$color_picker_custom_field = get_field('new_color', $post->ID);
$new_div[] = '<div class="overlay" style="background-color:<?php echo $color_picker_custom_field; ?>"></div>';
endforeach;
?>
<script>
jQuery( document ).ready( function() {
var new_divs = <?php echo json_encode($new_div); ?>;
jQuery( '.overlay' ).each( function(ind, el) {
jQuery(this).replaceWith(new_divs[ind]');
});
});
</script>