【问题标题】:PHP/Wordpress - Get the width/height attributes of a <img>PHP/Wordpress - 获取 <img> 的宽度/高度属性
【发布时间】:2014-07-03 10:38:47
【问题描述】:

我目前正在开发我的网站的基于 Wordpress 的新版本,我想在不知道如何添加的情况下添加一个功能。

所以也许你可以帮助我......我希望如此!

我想在 the_content 上添加一个过滤器,它适用于其中的每个 &lt;img ...&gt;。 该函数将获取变量($thisWidth$thisHeight)中的宽度和高度属性(例如&lt;img src="image.jpg" **height="120" width="300**" alt="test" /&gt;)。

然后我会比较每个图像的宽度和高度以了解它是横向还是纵向格式,并添加相应的类。简单:if($width &gt; $height) { ... } else { ... }

我不习惯与regex 一起工作,所以这就是我需要你帮助的原因。 我的技能允许我编写函数的基础,但仅此而已:

function imgClass($content) {

   /* for each '<img ....>' Loop ? */
   $thisWidth = /* get html width attribute */;
   $thisHeight = /* get html height attribute */;
   if($width > $height) { /* add class='landscape' */ } else { /* add class='portrait' */ }
   return $content;
}
add_filter('the_content','imgClass');

我会非常感谢任何能够帮助我的人... 提前致谢!

【问题讨论】:

  • 附注 - 当你在主题的 functions.php 文件中定义你自己的函数时(或者如果你开发了一个插件),总是给它一个唯一的名字并包装if(!function_exists('your_function_name')) 中的函数以避免函数名与其他插件/Wordpress 冲突。
  • 非常感谢你们的帮助! Mindreater > 它是!在发布我的问题之前搜索时没有找到它。但我不明白如何在比较之后向 添加一个类。并且不需要为每个图像做一个循环吗?该函数作为循环应用于每个图像,一个接一个? Bodi0 > 不知道,对避免内部冲突很有帮助!

标签: php wordpress image height width


【解决方案1】:

这是一个很好的例子,使用 javascript

    <!DOCTYPE html>
<html>
<body>

<img id="planets" src="planets.gif" width="145" height="126" usemap="#planetmap">



<p>Click the button to display the coordinates for the "planets.gif" area.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("planets").width;
    var y = document.getElementById("planets").height;
}
</script>

</body>
</html>

【讨论】:

  • 谢谢,但我想避免使用 javascript。
猜你喜欢
  • 2022-11-04
  • 2012-03-26
  • 2017-09-15
  • 2013-03-19
  • 1970-01-01
  • 2013-12-24
  • 2019-05-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多