phpwordpresswordpress-featured-image

Wordpress set featured image of one post to change daily to the featured image from another post type


I have a post (post id 8661) that contains a list of recent posts from another post type (wakeup). These (wakeup) posts are added daily. I would like the thumbnail of the main, listing post (8661) to change to the featured image of the most recent (wakeup) post in the list every day.

function set_custom_thumbnail( $post_8661, $thumbnail_id ) {
  $post_8661 = get_post(8661);
  $args = array(
    'post_type' => 'wakeup',
      'post_status' => 'publish',
      'posts_per_page' => 1
  );
  $new_query = new WP_Query( $args );
  if ($new_query->have_posts()) {
    while($new_query->have_posts()){
        $new_query->the_post();
        $thumbnail_id = the_post_thumbnail('thumbnail');
        }
      wp_reset_postdata();
    }
    return update_post_meta( $post_8661, '_thumbnail_id', $thumbnail_id );
}

Solution

  • Here's an answer for you. This is one way to execute the code on save post hook. Long story short... You need a hook to execute a function, otherwise it's just a function that will never get called. Suggest you look at WordPress Hooks

    /**
     * Set the post thumbnail for post 8661.
     *
     * @param int    $post_ID (int) Post ID.
     * @param object $post the Post Object.
     * @param bool   $update is it an update or not?
     * @return bool|int
     */
    function set_custom_thumbnail( $post_ID, $post, $update ) {
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }
        update_post_meta( 8661, '_thumbnail_id', get_post_thumbnail_id( $post_ID ) );
    }
    add_action( 'save_post_wakeup', 'set_custom_thumbnail', 10, 3 );