CroaToa
CroaToa

Reputation: 910

get and show attached video wordpress

I need get attached video (by url from Youtube) from post and show it dynamically in same page. The fact is that I have 2 types of single.php One of them show posts with thumbnails enter image description here

The second one need show video instead of image.

For get image I use this code

<?php the_post_thumbnail('full'); ?>

I know, that is not attached file, that is thumbnail. But can I get attached video from post and show it like image?

For example I have post like this

And I recieve post page like this

Can I display same video above using any short code?

Upvotes: 1

Views: 8855

Answers (2)

Rohil_PHPBeginner
Rohil_PHPBeginner

Reputation: 6080

As you have mentioned that you don't want to use plugin, then you can achieve it with custom_field.

So firstly add one custom_field and name it what ever you want(I have used utube_video_url).

After adding the field, next step is to enter the Youtube URL to that.

Thats's it from the back end. Now its time for coding.

<?php 
    global $post, $wp_embed;
    $youtube_video_url = get_post_meta($post->ID, 'utube_video_url', true); //store youtube URL in variable

    if(!empty($youtube_video_url)): //Check Youtube URL is entered or not
        echo $wp_embed->run_shortcode('[embed]'.$youtube_video_url.'[/embed]');
    else:
        the_post_thumbnail();
    endif;

?>

We have stored Youtube URL in one variable and then checking whether user has entered YouTube URL or not.

If yes, then it will output youtube URL or else it will print Feature Image.

Reference for shortcode: Do_Shortcode not working for Embed

Let me know If you have any doubts.

Upvotes: 3

gaurav kumar
gaurav kumar

Reputation: 1091

<?php
    // add this in your theme functions.php

            function video_yt_shortcode( $atts ){
            ?>
         // for thumbnail
            <img src="http://img.youtube.com/vi/<?php echo $atts['video_id']; ?>/0.jpg">
         //for video
     <iframe width="745" height="400" src="http://www.youtube.com/embed/<?php echo     $atts['video_id']; ?>?autoplay=1" frameborder="0" allowfullscreen></iframe>';
            <?php
            }
            add_shortcode( 'yt_video', 'video_yt_shortcode' );
            ?>

use shortcode [yt_video video_id="ytvideo_id"]

like this [yt_video video_id="8KxIHVGch8I"]

Upvotes: 0

Related Questions