【问题标题】:include w_thumbnail_src in function?在函数中包含 w_thumbnail_src?
【发布时间】:2012-02-27 10:54:12
【问题描述】:

我有一个在帖子中自动创建自定义字段的功能。我在我的functions.php中有这个。

Image 是自定义字段的名称,HERE 是值。如何将函数w_thumbnail_src 作为变量?

add_action('wp_insert_post', 'mk_set_default_custom_fields');
    function mk_set_default_custom_fields($post_id)

    {
        if ( $_GET['post_type'] != 'post' ) {
            add_post_meta($post_id, 'Image','HERE', true);
        }
        return true;
    }

让我补充一点,w_thumbnail_src 是同一个文件中的一个函数,看起来像这样

function w_thumbnail_src() {
    if (has_post_thumbnail()) {
        $thumb = wp_get_attachment_image_src(get_post_thumbnail_id(), 'emphasis');
       echo $thumb[0]; // thumbnail url
    }
}

【问题讨论】:

  • 我不太清楚你在问什么? add_post_meta($post_id, 'Image',w_thumbnail_src(), true); 是你的意思吗?
  • 就是这个想法,但我已经尝试过了,但它不起作用。它只返回一个空值字段。我需要缩略图 url 出现在那里

标签: php wordpress function thumbnails


【解决方案1】:

我认为你需要改变:
add_post_meta($post_id, 'Image','HERE', true);
至:
add_post_meta($post_id, 'Image', w_thumbnail_src(), true);

并且还通过将 w_thumbnail_src() 函数更改为以下内容来修复它:

function w_thumbnail_src() {
    if (has_post_thumbnail()) {
        $thumb = wp_get_attachment_image_src(get_post_thumbnail_id(), 'emphasis');
        return $thumb[0]; // thumbnail url
    } else {
        return '';  // or a default thumbnail url
    }
}

【讨论】:

  • 感谢您的尝试,但没有奏效,但我已经发布了答案。谢谢!!
【解决方案2】:

这是将缩略图 url 添加到名为 Image 的自定义字段的最终代码。

function w_thumbnail_src() {
    if (has_post_thumbnail()) {
        $thumb = wp_get_attachment_image_src(get_post_thumbnail_id(), 'emphasis');
        return $thumb[0]; // thumbnail url
    } else {
        return '';  // or a default thumbnail url
    }
}


add_action('publish_page', 'add_custom_field_automatically', 'w_thumbnail_src');
add_action('publish_post', 'add_custom_field_automatically');
function add_custom_field_automatically($post_id) {
global $wpdb;
if(!wp_is_post_revision($post_id)) {
add_post_meta($post_id, 'Image', w_thumbnail_src(), true);
}
}

【讨论】:

    猜你喜欢
    • 2015-07-10
    • 2021-03-25
    • 2013-06-12
    • 2014-12-02
    • 2019-03-29
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    相关资源
    最近更新 更多