How to get the first image field from a node without knowing the field's name?

ε祈祈猫儿з 提交于 2019-12-11 10:49:44

问题


The site I am working on uses many content types and almost all of them use one or more image fields. Image fields are not shared between content types, so there is a big number of them.

What I need is to get the first image field from a node, assuming there are more image fields linked to a node and without knowing the name of any of these fields. The first one is considered to be the one with a lower weight.


回答1:


This should build you an array of the "lightest" imagefield per content type.

<?php
module_load_include('inc', 'content', 'includes/content.node_form');
$content_types = array('page', 'story', 'product', 'some_content_type');

$lightest_imagefields = array(); // arranged by content type
foreach ($content_types as $content_type_name) {
  $content_type_data = content_types($content_type_name);
  $last_weight = NULL;
  foreach ($content_type_data['fields'] as $field_name => $field_data) {
    if ($field_data['widget']['type'] == 'imagefield_widget' && (is_null($last_weight) || (int)$field_data['widget']['weight'] < $last_weight)) {
        $lightest_imagefields[$content_type_name] = $field_name;
        $last_weight = (int)$field_data['widget']['weight'];
    }
  }
}
/** Hypothetical Usage:
 * $node = load_some_node_i_want();
 * $node->$lightest_imagefields[$node->type]; // Access this node's lightest imagefield.
 */

Then when you load a node of, say, the "product" content type, you know which imagefield is the lightest (i.e $node->$lightest_imagefields[$node->type]).

Hope it helps. (test it before using it, though!)



来源:https://stackoverflow.com/questions/6656595/how-to-get-the-first-image-field-from-a-node-without-knowing-the-fields-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!