主题定制器图像控件

时间:2013-05-02 作者:Tom J Nowell

我知道可以向主题定制器添加控件来添加图像。

但是,此控件返回一个图像URL,我需要它的附件ID,而不是图像URL。在哪里可以拦截或窃取此图像的附件ID以执行此操作?有我可以拦截的救命钩吗?还是基于javascript的方法?

1 个回复
最合适的回答,由SO网友:Tom J Nowell 整理而成

解决方案需要一个扩展原始图像控件的自定义控件对象,并执行SQL查询以获取清理时的GUID和关联附件ID。不太好,克鲁奇,但很管用

$wp_customize->add_setting( \'customimage\', array(
    \'default\'       => $default,
    \'capability\'    => \'edit_theme_options\',
    \'type\'          => \'option\',
    \'sanitize_callback\' => array( \'ICIT_Customize_Image_Control_AttID\', \'attachment_guid_to_id\' ),
    \'sanitize_js_callback\' => array( \'ICIT_Customize_Image_Control_AttID\', \'attachment_guid_to_id\' ),
) );

$wp_customize->add_control( new ICIT_Customize_Image_Control_AttID( $wp_customize, "custom_image_attach_id", array(
    \'label\'      => $label,
    \'section\'    => "custom_image_attach_id",
    \'settings\'   => \'customimage\'
) ) );

if ( ! class_exists( \'ICIT_Customize_Image_Control_AttID\' ) ) {
    class ICIT_Customize_Image_Control_AttID extends WP_Customize_Image_Control {

        public $context = \'custom_image\';

        public function __construct( $manager, $id, $args ) {
            $this->get_url = array( $this, \'get_img_url\' );
            parent::__construct( $manager, $id, $args );
        }

        // As our default save deals with attachment ids not urls we needs this.
        public function get_img_url( $attachment_id = 0 ) {
            if ( is_numeric( $attachment_id ) && wp_attachment_is_image( $attachment_id ) )
                list( $image, $x, $y ) = wp_get_attachment_image_src( $attachment_id );

            return ! empty( $image ) ? $image : $attachment_id;
        }


        public function attachment_guid_to_id( $value ) {
            global $wpdb;
            if ( ! is_numeric( $value ) ) {
                $attachment_id = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_type = \'attachment\' AND guid = %s ORDER BY post_date DESC LIMIT 1;", $value ) );
                if ( ! is_wp_error( $attachment_id ) && wp_attachment_is_image( $attachment_id ) )
                    $value = $attachment_id;
            }

            return $value;
        }
    }
}

结束

相关推荐

Upload images - Theme options

我正在使用这个很棒的[图坦卡门+教程][1]创建主题选项页面。这对我来说很好,因为我需要通过css更改div的背景图像。它可以很好地与一个图像,但我不知道如何使它与2个图像?如果你能告诉我我做错了什么,那将是一个巨大的帮助?谢谢 <?php function wptuts_get_default_options() { $options = array(); $options[] = array(\'logo\' => \'\');