I am attempting to merge two separate PHP functions into one will be able to use within my Wordpress theme. I am using Wordpress functions to obtain the publish meta from the key "_videoembed" that is then trimmed from the YouTube URL lower towards the YouTube video ID. I'll include both earlier functions &lifier my technique for using them and so the one I am focusing on. All assistance is appreciated greatly! -Matt

Previous Method

In theme

<?php 
  $vidurl = get_post_meta($post->ID, "_videoembed", true );
  $youtube_id = getYouTubeIdFromURL($vidurl);
  $finalid = trim($youtube_id);
  echo $finalid;
?>

In functions.php

function getYouTubeIdFromURL($url)
{
$url_string = parse_url($url, PHP_URL_QUERY);
parse_str($url_string, $args);
return isset($args['v']) ? $args['v'] : false;
}

Below is a good example of how I am attempting to merge the 2:

In theme

<?php getvidID(); ?>

In functions.php

function getvidID() 
{
  $vidurl = get_post_meta($post->ID, "_videoembed", true );
  $url_string = parse_url($vidurl, PHP_URL_QUERY);
  parse_str($vidurl_string, $args);
  return isset($args['v']) ? $args['v'] : false;
  echo $vidurl;
}

As you can tell, the older method I made use of was quite bulky, and I am attempting to streamline things to ensure that my files are simpler to utilize and to ensure that you will find less PHP functions.

Thanks!

Matt

That isn't makes sense. Every function must do one factor and something factor only. That's the thought of encapsulation. When the function has several task, you'll have the next problems at some point:

  • you may need a function that does only among the tasks
  • you will have to refactor/rewrite among the tasks and could break both rather than only one

If you wish to eliminate PHP code inside your view, which may be beneficial To be sure, then you definitely must write more functions. However I don't really visit a need inside your situation. It's readably code before and also you allow it to be unreadable and simply breakable.

Function usage:

<?php get_vid_id($post->ID); ?>

Function itself:

function get_vid_id($id) 
{
  $vidurl = get_post_meta($id, "_videoembed", true );
  $url_string = parse_url($vidurl, PHP_URL_QUERY);
  parse_str($vidurl_string, $args);
  return isset($args['v']) ? $args['v'] : false;
  echo $vidurl;
}

But I'd recommend using less functions. Keeps your code clean. Maybe create classes?

I'd keep your functional models more compact, rather than developing a bigger single function.

Splitting a large function into more compact functional models is really a known refactoring pattern known as extract method.

Merging small functions is virtually the alternative of refactoring, that is targeted at keeping code clean, simpler to follow along with and keep.