Changing the title of post with code

Your question isn’t terribly clear, because, yes it is possible to change post data programmatically, and you’re on the right track using wp_update_post, but I’m unsure of what the code in your theme’s index.php file is trying to achieve.

My assumption is that you want to be able to change the post title from your theme, but you’re not passing anything to afunction() to update it.

Also, in your function above, when you call mb_convert_case, you’re also re-defining $new_title as the original post title, so when $post->post_title === $new_title is executed, it always equates to true.

To achieve what I think you’re trying to achieve, I would do something like this:

In functions.php:

function afunction( $post, $new_title ) {
  // if new_title isn't defined, return
  if ( empty ( $new_title ) ) {
      return;
  }    

  // ensure title case of $new_title
  $new_title = mb_convert_case( $new_title, MB_CASE_TITLE, "UTF-8" );

  // if $new_title is defined, but it matches the current title, return
  if ( $post->post_title === $new_title ) {
      return;
  }

  // place the current post and $new_title into array
  $post_update = array(
    'ID'         => $post->ID,
    'post_title' => $new_title
  );

  wp_update_post( $post_update );
}

Updated: In your theme file (index.php, page.php, single.php, etc):

<?php while (have_posts()) : the_post(); ?>

   <h2>
       <a href="https://wordpress.stackexchange.com/questions/168913/<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a>
   </h2>

   <div class="single-post-content">
       <?php the_content(); ?>
   </div>

    <?php 
        $current_id = get_the_id();
        $post = get_post($current_id);
        $new_title="New Title";
        afunction( $post, $new_title );
    ?>

<?php endwhile; ?>

You will have to refresh at least once to see the change. If you manually change your theme file, you would have to refresh twice. Once to load the changed file, a second time to perform the update. To avoid that, you would need to perform a POST request (see the WordPress HTTP API), or something to that effect.

This is not something someone normally would do with WordPress. But I can imagine some situations when it would be appropriate. Generally, a good practice would be to only allow logged in users to perform actions that update post data in your database.

Note: Take special care that if, as in your example index.php, you are using if (have_posts()) : while (have_posts()) : the_post(); that you are also closing that with endif; AFTER all of your code.

I also recommend that you review other examples of theme files from the default theme, and take care to review the logic of your PHP to check for problems.

So I hope that’s useful.