首页 > 解决方案 > 如何将默认图像尺寸过滤器添加到 get_first_image 函数?

问题描述

我正在我的 wordpress 中显示第一个 img 帖子,例如缩略图!但我正在尝试将默认大小的拇指应用于第一张图片,但没有成功:

我的默认尺寸是:

add_image_size('video-large', 565, 318, true);
add_image_size('video-single', 750, 330, true);
add_image_size('blog-single', 728, 288, true);
add_image_size('video-medium', 370, 208, true);
add_image_size('video-small', 175, 98, true);
add_image_size('widget-post', 55, 55, true);
add_image_size('term-listing', 170, 125, true);

我想对 get_first_image 应用“video-large”大小,因为这个过滤器裁剪图像,我想要它。

我试试这个:

<img src="<?php echo get_first_image('video-large');?>

但是,不工作!

// Get first image
function get_first_image() {
    global $post, $posts;

    $first_image = '';
    ob_start();
    ob_end_clean();

    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
    $first_image = $matches[1][0];

    if ( empty($first_image) ) {
        // Defines a default image
        // Set the default image if there are no image available inside post content
        $first_image = "/img/default.jpg";
    }

    return $first_image;
}

标签: wordpress

解决方案


在 function.php 中添加 WordPress 自定义图像大小

// Make sure featured images are enabled
add_theme_support( 'post-thumbnails' );

// Add featured image sizes
add_image_size( 'featured-large', 640, 294, true ); // width, height, crop
add_image_size( 'featured-small', 320, 147, true );

// Add other useful image sizes for use through Add Media modal
add_image_size( 'medium-width', 480 );
add_image_size( 'medium-height', 9999, 480 );
add_image_size( 'medium-something', 480, 480 );

// Register the three useful image sizes for use in Add Media modal
add_filter( 'image_size_names_choose', 'wpshout_custom_sizes' );
function wpshout_custom_sizes( $sizes ) {
    return array_merge( $sizes, array(
        'medium-width' => __( 'Medium Width' ),
        'medium-height' => __( 'Medium Height' ),
        'medium-something' => __( 'Medium Something' ),
    ) );
}

推荐阅读