0

What's the best way to force oembed (or shortcodes too) to the top of a post?

I'd like to feature youtube embeds before the actual article content, regardless of where the link was inserted. Any ideas?

1

you can create custom post meta which contain youtube url and then

$yt=get_post_meta($post->ID,'youtube_url',true);
if( '' != $yt)
echo $GLOBALS['wp_embed']->autoembed( $yt );

Updated:

If i'm getting correctly then your content contain youtube url any where in it and you want to show them at top regardless there position in content.

jut paste this code in functions.php

add_filter('the_content','ravs_youtube_atTop',1);
function ravs_youtube_atTop($content){
    /* get list of all youtubr urls */
    preg_match_all('#https?://(www\.)?youtube.com/watch.*#', $content, $matches);
    /*replace all youtube url by empty string*/
    $content = preg_replace('#https?://(www\.)?youtube.com/watch.*#','',$content);
    /* return actual content if not youtube url found */
    if( empty($matches[0]) )
        return $content;
    /*insert all youtube embed iframes at top of content*/
    foreach( $matches[0] as $match){
        $content = wp_oembed_get($match).$content;
    }
    return $content;
}
  • No way to do this with OEmbed? – landons Jul 12 '13 at 19:18
  • answer updated.check is this one work for you? – Ravinder Kumar Jul 13 '13 at 8:56
1

Part of your question asked about shortcodes. That is relatively simple.

function move_shortcode_to_top($content) {
  if (!is_singular()) return;

  $regex = get_shortcode_regex();
  preg_match_all('/'.$regex.'/',$content,$matches);

  $move_these = array(
    'testsc'
  );

  if (!empty($matches[2])) {
    foreach ($matches[2] as $k => $v) {
      if (in_array($v,$move_these)) {
        $content = $matches[0][$k].str_replace($matches[0][$k],'',$content);
      }
    }
  } 

  return $content;
}
add_action('the_content','move_shortcode_to_top',1);

Just provide a list ($move_these) of the shortcodes you want to move.

For oembeds, you need something a little different:

function move_oembed_to_top($content) {
  $pattern = '|^\s*(https?://[^\s"]+)\s*$|im';
  preg_match_all($pattern,$content,$matches);
  if (!empty($matches[1])) {
    $content = preg_replace($pattern,'',$content);
    $content = implode("\n",$matches[1])."\n".$content;
  }
  return $content;
}
add_filter('the_content','move_oembed_to_top',1);

That will move as many embeds as it finds. Tested with YouTube embeds.

Note: That regex is exactly the one used by the Core embed system.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.