设置有功能的特色图像,1个部件不工作

时间:2013-04-30 作者:Eckstein

我正在尝试根据自定义字段设置帖子的特色图像。有不同类型的帖子,因此应根据填写的自定义字段设置特色图像。

以下是我目前所编辑的内容:

//Set post thumbnail based on various conditions
        if (get_post_meta($post_id, \'featured_image\', true)) {
            $attachment_id = get_post_meta($post_id, \'featured_image\', true);
        } elseif (get_post_meta($post_id, \'upload_single_image\', true)) {
            $attachment_id = get_post_meta($post_id, \'upload_single_image\', true);
        } elseif (get_post_meta($post_id, \'create_gallery\', false)) {
            $gallery = get_post_meta($post_id, \'create_gallery\', false);//get the full gallery
            $attachment_id = $gallery[0][\'upload_image\']; //Get image from first row    
        }
前两个条件有效,但第三个条件(创建库)无效。我原以为获取db表的第一行,然后调用自定义元数据的名称就可以了,但不起作用。

有人看到我可能做错了什么吗?

2 个回复
SO网友:tfrommen

您必须设置$single paramter of get_post_meta 设置为false(或不设置)以获取数组。

以下是加速版:

    if ($attachment_id = get_post_meta($post_id, \'featured_image\',      true)) :
elseif ($attachment_id = get_post_meta($post_id, \'upload_single_image\', true)) :
elseif ($attachment_id = get_post_meta($post_id, \'create_gallery\',     false)) :
    $attachment_id = $attachment_id[0][\'upload_image\'];
endif;
Note: 我没有测试这个。

<小时>// EDIT
以下是ACF功能的代码:

    if ($attachment_id = get_post_meta($post_id, \'featured_image\',      true)) :
elseif ($attachment_id = get_post_meta($post_id, \'upload_single_image\', true)) :
elseif ($gallery = get_field(\'create_gallery\', $post_id)) :
    $attachment_id = $gallery[0][\'upload_image\'];
endif;

SO网友:Eckstein

通过使用ACF的自定义函数而不是wp的元函数,它得以工作。

最终工作结果:

//Set post thumbnail based on various conditions
        if (get_post_meta($post_id, \'featured_image\', true)) {
            $attachment_id = get_post_meta($post_id, \'featured_image\', true);
        } elseif (get_post_meta($post_id, \'upload_single_image\', true)) {
            $attachment_id = get_post_meta($post_id, \'upload_single_image\', true);
        } elseif (get_field(\'create_gallery\', $post_id)) {
            $gallery = get_field(\'create_gallery\', $post_id);//get the full gallery
            $attachment_id = $gallery[0][\'upload_image\']; //Get image from first row    
        }

结束

相关推荐

如何在Functions.php中使用PHP手动修复WordPress库代码?

Wordpress为内置的gallery功能输出了一些非常糟糕的代码,这已经被谈论了很多次了。这是负责库输出的核心代码(在/wp-includes/media.php中):function gallery_shortcode($attr) { global $post; static $instance = 0; $instance++; // Allow plugins/themes to override the de