Skip to content

Instantly share code, notes, and snippets.

@yehudah
Created March 20, 2016 10:55
Show Gist options
  • Select an option

  • Save yehudah/2a30112770a3a11b116b to your computer and use it in GitHub Desktop.

Select an option

Save yehudah/2a30112770a3a11b116b to your computer and use it in GitHub Desktop.
Allow you to choose an image for facebook og.
<?php
/*
Plugin Name: Dynamic Facebook og image
Description: Allow you to choose an image for facebook og.
Author: Yehuda Hassine
Version: 1.0
*/
add_action('add_meta_boxes', 'fb_og_image_mb');
function fb_og_image_mb() {
add_meta_box( 'Facebbok og image', 'Facebbok og image', 'fb_og_image_callback', 'post', 'side' );
}
function fb_og_image_callback( $post ) {
$external_url = get_post_meta( $post->ID , 'fb_og_image', true); ?>
<p>
<?php wp_nonce_field( 'fb_og_image_none', 'meta_box_nonce' ); ?>
<input type="url" id="fb_og_image" name="fb_og_image" value="<?php echo esc_url( $external_url ); ?>" /><button class="upload_image button">בחירת תמונה</button>
<?php
if ( $external_url ) { ?>
<img id="fb_og_image_preview" style="max-width: 100%; margin-top: 5px;" src="<?php echo esc_url( $external_url ); ?>" />
<?php } ?>
</p>
<?php
}
function save_meta_box( $post_id ) {
if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'fb_og_image_none' ) ) return;
$fb_og_image = esc_url( $_POST['fb_og_image'] );
update_post_meta( $post_id, 'fb_og_image', $fb_og_image );
}
add_action( 'save_post', 'save_meta_box' );
function change_fb_og_image($content) {
global $post;
$fb_og_image = get_post_meta( $post->ID, 'fb_og_image', true);
if ( filter_var( $fb_og_image, FILTER_VALIDATE_URL ) ) {
$content = $fb_og_image;
}
return $content;
}
add_filter( 'wpseo_opengraph_image', 'change_fb_og_image' );
function open_media_upload() { ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
var file_frame;
jQuery('.upload_image').on('click', function( event ){
event.preventDefault();
if ( file_frame ) {
file_frame.open();
return;
}
file_frame = wp.media.frames.file_frame = wp.media({
multiple: false
});
file_frame.on( 'select', function() {
attachment = file_frame.state().get('selection').first().toJSON();
$('#fb_og_image').val(attachment.url);
$('#fb_og_image_preview').attr('src', attachment.url);
});
file_frame.open();
});
});
</script>
<?php
}
add_action('admin_head', 'open_media_upload' );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment