如何在子主题的functions.php中覆盖父主题的add_image_size和$ content_width

用户名

我试图覆盖父主题中的某些功能,但我想将其add_image_size从590覆盖为800,$content-width从590覆盖为850。

这是父主题的functions.php。


class WPEX_Theme_Class {

    public function __construct() {     
        // Theme setup: Adds theme-support, image sizes, menus, etc.
        add_action( 'after_setup_theme', array( &$this, 'setup' ), 10 );
    }       


    public function setup() {
        // Set content width variable
        global $content_width;
        if ( ! isset( $content_width ) ) {
            $content_width = 590;
        }

        // Add theme support        
        add_theme_support( 'post-thumbnails' );

        // Add image sizes
        add_image_size( 'wpex-entry', 590, 9999, false );
        add_image_size( 'wpex-post', 590, 9999, false );
    }

  $blogger_theme_setup = new WPEX_Theme_Class;
} 

这是我的尝试:

function __construct() 
{
     add_action('after_setup_theme', array($this, 'change_theme'));
}

function change_theme() 
{
    remove_action('add_image_size', 'setup');
    add_action('wpex-post', array($this, 'setup'));
}

function setup() {

    add_theme_support( 'post-thumbnails' );

    // Add image sizes
    add_image_size( 'wpex-entry', 800, 9999, false );
    add_image_size( 'wpex-post', 800, 9999, false );

 }

它不起作用,我需要更改什么?

蓬松的小猫

将以下代码添加到您的子主题中,将重新声明图像大小和content_width。

您不需要删除父主题设置的图像大小-您可以在父主题调用add_image_size函数调用函数来覆盖它们

我们可以通过为设置较低的优先级来做到这一点add_action父主题使用,10因此我们可以使用11

// use priority 11 to hook into after_setup_theme AFTER the parent theme
 add_action('after_setup_theme', 'reset_parent_setup', 11);

function reset_parent_setup() 
{
    // Override the image sizes
    add_image_size( 'wpex-entry', 800, 9999, false );
    add_image_size( 'wpex-post', 800, 9999, false );

    // Set content width variable
    global $content_width;
    $content_width = 850;
}

注意:

add_image size不会自动创建已经上传的图像的新版本,因此不要忘了以后重新生成图像您可能还需要清除可能影响它的所有缓存。


更新:检查是否已注册正确的尺寸

下面的功能将为您的两个图像尺寸(wpex-entry和wpex-post)打印尺寸。将此添加到您的functions.php中以检查它们是什么(注意:该die()函数将停止显示页面的其余部分,从而更容易查看所显示的值):

add_action('loop_start', 'debug_image_sizes');
function debug_image_sizes() {
    global $_wp_additional_image_sizes;

    if ( isset( $_wp_additional_image_sizes['wpex-entry'] ) ){
        echo '<p>wpex-entry Image Size: </p><pre>';
        var_dump( $_wp_additional_image_sizes['wpex-entry'] );
        echo '</pre>';
    }
    else echo "<p>wpex-entry Image Size not found!!</p>";

    if ( isset( $_wp_additional_image_sizes['wpex-post'] ) ){
        echo '<p>wpex-post Image Size: </p><pre>';
        var_dump( $_wp_additional_image_sizes['wpex-post'] );
        echo '</pre>';
    }
    else echo "<p>wpex-post Image Size not found!!</p>";
    die();
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章