如何在不知道字段名称的情况下从节点获取第一个图像字段? [英] How to get the first image field from a node without knowing the field's name?
问题描述
我正在开发的网站使用多种内容类型,并且几乎所有类型都使用一个或多个图像字段.图像字段在内容类型之间不共享,因此数量很多.
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
.
推荐答案
这应该为您构建每个内容类型的最轻"图像字段数组.
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.
*/
然后当你加载一个节点,比如产品"内容类型时,你知道哪个图像字段是最轻的(即 $node->$lightest_imagefields[$node->type]
).
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!)
这篇关于如何在不知道字段名称的情况下从节点获取第一个图像字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!