Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
<?php
/**
* oEmbed Attributes
*
* Add parameters to oEmbed query string. Useful for
* turning off related videos and such.
*
* Basic field use: $video = videoLink('your_field_name');
* Add second param if in a repeater: $video - videoLink('your_subfield_name', true);
*
* @see https://www.advancedcustomfields.com/resources/oembed/
*
* @param $field
* @param bool $repeater defaults to false / true if repeater
* @param array $params / array of query string parameters as key value pairs
*
* @return mixed embed HTML
*/
function videoLink( $field, $repeater = false, array $params = [] ) {
global $post;
// get current post ID
$id = $post->ID;
// set of default params
$defaults = array(
'rel' => 0,
'title' => 0,
'byline' => 0,
'portrait' => 0,
'autoplay' => 'true'
);
// Check if defaults have been passed in via function args,
// if not then add them to params array
foreach ( $defaults as $key => $value ) {
if(!array_key_exists($key, $params)) {
$params[$key] = $value;
}
}
if ( ! $repeater ) {
// get the field
$videoFrame = get_field( $field, $id );
} else {
// if we are in a repeater
$videoFrame = get_sub_field( $field, $id );
}
// use preg_match to find iframe src
preg_match( '/src="(.+?)"/', $videoFrame, $matches );
$src = $matches[1];
// add extra params to iframe src
$new_src = add_query_arg( $params, $src );
$videoLink = str_replace( $src, $new_src, $videoFrame );
return $videoLink;
}

alexstandiford commented Sep 20, 2016 edited

get_sub_field() appears to check if it is in a loop before it runs. I'm sure you could put the same logic in this. Here's the critical part of get_sub_field() that I think can be duplicated in this:

function get_sub_field( $selector, $format_value = true ) {

    // vars
    $row = acf_get_loop('active');


    // bail early if no row
    if( !$row ) return null;

Also, this is really useful!

Owner

smutek commented Jan 11, 2017 edited

Alex, I'm just seeing this. That's a good find, I haven't tried this out but are you suggesting something like this -


function videoLink($field) {

  global $post;
  // get current post ID
  $id = $post->ID;

  // is this a repeater?
  $repeater = acf_get_loop('active');

  if(!$repeater) {

    // get the field
    $videoFrame  = get_field( $field, $id );

  } else {

    // if we are in a repeater
    $videoFrame  = get_sub_field( $field, $id );

  }
  // ... etc...

That would get rid of having to pass the class second param, but I feel like it would be less efficient because now it's running acf_get_loop('active') twice - once in this function, and then again when it returns true and get_sub_field() runs.

What do you think? Am I missing something?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment