St3
St3

Reputation: 401

How to remove lines of code in a Wordpress child theme?

I've been messing around with child themes in Wordpress and while I know how to add or change code from the parent theme I'm having a bit of a problem removing certain code. For example I'm using a theme that uses featured images for thumbnails in posts. I want the added picture for the thumbnail but it also includes it at the top of the actual post which I am trying to remove. I can comment out part of the code to achieve this in the parent functions.php like this

if (!function_exists('mh_featured_image')) {
    function mh_featured_image() {
        global $post;
        if (has_post_thumbnail() && !is_attachment()) {
            $thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id(), 'content');
            // echo "\n" . '<div class="post-thumbnail">' . "\n";
            //  echo '<img src="' . esc_url($thumbnail[0]) . '" alt="' . esc_attr(get_post_meta(get_post_thumbnail_id(), '_wp_attachment_image_alt', true)) . '" title="' . esc_attr(get_post(get_post_thumbnail_id())->post_title) . '" />' . "\n";
            //  if (get_post(get_post_thumbnail_id())->post_excerpt) {
            //      echo '<span class="wp-caption-text">' . esc_attr(get_post(get_post_thumbnail_id())->post_excerpt) . '</span>' . "\n";
            //  }
            // echo '</div>' . "\n";
        }
    }
   }

So when I comment out the actual code out in the parent functions.php as shown above everything works perfectly. My issue is how do I translate this to the child functions.php? I just want to keep everything but edit out those six lines that are echoed.

Upvotes: 0

Views: 748

Answers (1)

David
David

Reputation: 5937

im not sure i understand the issue correctly, have you set up a child theme ?

If so, the child themes functions are loaded before the parent themes allowing you to overwrite the parent functions that are wrapped in:

if (!function_exists('myfunction')) { 
       function myfunction(){}; 
}

Which is basically saying, if the function myfunction() does not exist (note the ! operator which means not in a if statement), it has not been defined in a earlier file (in this case your child theme, could also be a plugin which are also loaded before theme files) and the function is then defined. As you may or may not know you cannot redeclare a function in php so by only defining the function if it has not already been defined allows for your own definition to be made.

Therefore to change the function to the version you want, you place the following in the child themes functions.php file

function mh_featured_image() {
    global $post;
    if (has_post_thumbnail() && !is_attachment()) {
        $thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id(), 'content');
    }
}

And it should work, although your function doesn't actually return or output or store any values, so you need to consider this in your expected result

Upvotes: 2

Related Questions