【问题标题】:Add ID to image within Advanced Custom Fields image basic display将 ID 添加到高级自定义字段图像基本显示中的图像
【发布时间】:2017-01-12 15:25:55
【问题描述】:

我正在寻找专门使用 CSS 的幻灯片中的目标图像。

我正在使用带有高级自定义字段的 Wordpress 来使用 PHP 生成图像 DIV。

我的代码:

<?php $image = get_field('product1_image1');

    $size = 'large'; // (thumbnail, medium, large, full or custom size)
    if( $image ) {

    echo wp_get_attachment_image( $image, $size );
} ?>

此代码生成如下内容:

<img width="2000" height="1333" src="http://www.johanvanhengel.com/wp-content/uploads/2016/06/TOR_for_Montis_by_Lambi__Van_Hengel_04-2000x1333.jpg" class="attachment-large size-large cycle-slide cycle-sentinel" alt="text" sizes="(max-width: 2000px) 100vw, 2000px" style="position: static; top: 0px; left: 0px; z-index: 100; opacity: 1; display: block; visibility: hidden;">

我想给生成的 IMG 标记一个 ID 'product1_image1',以便它可以使用 css 定位。

ex #product1_image1 { 不透明度:1; }

干杯!

【问题讨论】:

    标签: php css advanced-custom-fields


    【解决方案1】:

    改变..

    echo wp_get_attachment_image( $image, $size );

    进入:

    echo wp_get_attachment_image( $image, $size, '', array( "id" =&gt; "product1_image1" ) );

    正如您将在文档中看到的那样,该函数支持属性作为第四个参数; https://developer.wordpress.org/reference/functions/wp_get_attachment_image/

    【讨论】:

      【解决方案2】:

      danjah 的答案是完全正确的,但为了增加代码的可读性,我会更进一步......

      试试这个代码:

      <?php 
        $acf_img = get_field('product1_image1');
      
        $size = 'large'; // (thumbnail, medium, large, full or custom size)
        if( $acf_img ) {
          $image = wp_get_attachment_image_src( $acf_img, $size );
      
          echo '<img src="'.$image[0].'" width="'.$image[1].'" height="'.[2].'" class="your-class" id="product1_image1" />';
        } 
      ?>
      

      wp_get_attachment_image_src() 创建一个图像数组。 [0] =&gt; source, [1] =&gt; width, [2] =&gt; height.

      最后没有区别,但我认为这段代码是可读的,因为你可以直接看到输出的 html 标记。 并且:您可以完全控制您的标记 - 有时 WordPress 会更改某些功能的输出,而这些功能并非每次都需要。 (他们实现了srcsets,例如,我不希望它出现在我的网站上,因为我使用的框架会根据视口改变我的图像大小......)

      【讨论】:

        猜你喜欢
        • 2018-04-15
        • 2014-03-23
        • 2021-06-12
        • 1970-01-01
        • 2018-11-24
        • 2019-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多