【问题标题】:Insert custom field to custom post type将自定义字段插入自定义帖子类型
【发布时间】:2020-05-02 19:01:39
【问题描述】:

我有一个由插件制作的组件,它显示来自自定义帖子类型的文章列表。每篇文章都有与之关联的类 post-id。我无法覆盖子主题中的插件文件以在生成列表的模板内循环,因此我需要在 functions.php 中创建一个函数。我需要用高级自定义字段插件制作的自定义字段(颜色选择器)样式的新 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');

【问题讨论】:

  • 也许您需要将 $new_div 声明为数组并在 $posts 循环中填充它

标签: php html jquery wordpress advanced-custom-fields


【解决方案1】:

您可以从每个帖子中获取新颜色到数组,然后使用 json_encode() 将数组传递给 javascript

这是您的代码的修改片段,我不确定它是否会起作用,因为 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>

【讨论】:

  • 您好,谢谢您的回答,不幸的是,您的解决方案 $color_picker_custom_field 没有显示,但我用另一个解决方案编辑了我的代码及其工作。唯一需要做的就是为文章的子元素添加一个具有相同 post-id 的类。所以如果我有 article.post-id = .overlay.post-id 添加一个类,这样我就可以隐藏我不需要的其他 div
猜你喜欢
  • 1970-01-01
  • 2017-01-03
  • 1970-01-01
  • 2012-07-29
  • 2011-10-23
  • 1970-01-01
  • 1970-01-01
  • 2014-03-02
  • 2019-06-01
相关资源
最近更新 更多