Day: November 21, 2024

  • Last coat of paint is drying

    Last coat of paint is drying

    This ended up being a lot more research for very little change, but I’m happy so far. I may still adjust some colors, but other than that I’m happy.

    What I ended up spending the most time on was a simple feature that required php code to work. I wanted to set the first image in the post as the WP Feature Image for the post. I am really surprised this feature isn’t part of word press to be honest.

    Here is the code that I had to add to my functions.php file.

    // add support for Feature Image.  Pobably redundent as it should be in parent theme
    add_theme_support( 'post-thumbnails' );
    
    // // autoset_featured is a function that sets the featured image to the first image in the post
    function autoset_featured() {
        global $post;
        $already_has_thumb = has_post_thumbnail($post->ID);
        if (!$already_has_thumb)  {
            $attached_image = get_children("post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
                if ($attached_image) {
                    foreach ($attached_image as $attachment_id => 
                    $attachment) {
                        set_post_thumbnail($post->ID, $attachment_id);
                    }
                }
            }
        }
    add_action('the_post', 'autoset_featured');
    add_action('save_post', 'autoset_featured');
    add_action('draft_to_publish', 'autoset_featured');
    add_action('new_to_publish', 'autoset_featured');
    add_action('pending_to_publish', 'autoset_featured');
    add_action('future_to_publish', 'autoset_featured');

    Unfortunately, there was several hours of research and missteps to get this working properly, and the way I wanted.

    I started by reading the first several sections of the WordPress Developer Theme Handbook. This was more interesting than you’d think, and I know how a much better idea about where things go. Specifically, the functions.php file(in my child theme, which I now know I should create).

    Then I found this person’s code and just copy and pasted it. Which sounds lazy, but I know what all the code does at the moment, which is nice.