Ich saß vor einigen Tagen an meinem Blogbeitrag und habe mir gedacht, dass wenn ich jetzt schon wieder etwas über Programmierung poste, es z.B. Menschen wie meine Frau gar nicht interessieren würde. Deswegen habe ich mir eine Alternative überlegt, was ich posten könnte, was auch jeden anderen, der meinen Blog verfolgt posten kann.
Die Lösung: Zitate mit schönen Hintergrundbildern.
Das geht jedoch nicht so einfach. Ich kann mich nicht jeden Tag an Photoshop setzen und ein Bild mit Text verzieren und es mit Hashtags auf zwei Plattformen posten. Also musste eine Automatisierung her.
WordPress Backend
Ich habe ein Post Type quotes generiert um dort meine Zitate einzugeben. Diesem Post Type habe ich zusätzlich noch diese Funktionen gegeben:
- Post excerpt
- Post Thumbnail (min. 1920px1080px)
Nachdem ich damit fertig war, musste ich noch meine Funktionen anpassen, die ich zum veröffentlichen meiner Beiträge benutze.
Facebook Autopost
/*
$facebook_photo_id = facebook_photo_upload(array(
'url' => UrlToFile (required),
'caption' => TextForPhoto (optional)
'post_id' => PostID (optional)
));
*/
function facebook_photo_upload( $args ){
$post_id = intval($args['post_id']);
if(
$post_id &&
($facebook_photo_id = get_post_meta( $post_id, 'facebook_post_id', true ))
) return $facebook_photo_id;
require_once('sdk/autoload.php');
$fb = new \Facebook\Facebook([
'app_id' => 'XXXXXXXXXX',
'app_secret' => 'XXXXXXXXXX',
'default_graph_version' => 'v2.10',
'default_access_token' => 'XXXXXXXXXX',
]);
$graphOptions = array(
'url' => $args['url']
);
if($args['caption']) $graphOptions['caption'] = $args['caption'];
try {
$response = $fb->post('/me/photos',$graphOptions);
} catch(\Facebook\Exceptions\FacebookResponseException $e) {
ob_start();
var_dump($e);
var_dump($args);
$facebook_post_dump = ob_get_contents();
ob_end_clean();
wp_mail(
get_option('admin_email'),
'Facebook Post Fail',
"<pre>$facebook_post_dump</pre>",
array('Content-Type: text/html; charset=UTF-8')
);
return false;
}
$facebook_photo_id = json_decode((string) $response->getBody())->id;
update_post_meta( $post_id, 'facebook_post_id', $facebook_photo_id );
return $facebook_photo_id;
}
Dieser Code sorgt einfach nur dafür, dass mein Bild automatisch auf Facebook hochgeladen wird. Es ist einfach eine erweiterte Version dem dem, was ich euch hier erkläre:
Twitter Autopost
function tweet_media( $args ) {
if($tweet_id = get_post_meta( $args['post_id'], 'tweet_id', true )) return $tweet_id;
require_once('TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => "XXXXXXXXXX",
'oauth_access_token_secret' => "XXXXXXXXXX",
'consumer_key' => "XXXXXXXXXX",
'consumer_secret' => "XXXXXXXXXX"
);
$twitter = new TwitterAPIExchange($settings);
if ($args['attachment_url']) {
$media = json_decode( (string) $twitter->buildOauth(
'https://upload.twitter.com/1.1/media/upload.json',
'POST'
)->setPostfields(array(
'media_data' => base64_encode(file_get_contents($args['attachment_url']))
))->performRequest()
);
if (!$media->media_id_string) return false;
}
$tweet = ( strlen($args['text']."\n".$args['hashtags'].(($args['link'])? "\n".$args['link'] : '')) < 280 )?
$args['text']."\n".$args['hashtags'].(($args['link'])? "\n".$args['link'] : '') :
$args['text'].(($args['link'])? "\n".$args['link'] : '');
$tweet = json_decode( (string) $twitter->buildOauth(
'https://api.twitter.com/1.1/statuses/update.json',
'POST'
)->setPostfields(array(
'status' => $tweet,
'media_ids' => $media->media_id_string
))->performRequest()
);
if ($tweet->id) {
update_post_meta( $args['post_id'], 'tweet_id', $tweet->id );
}else {
ob_start();
var_dump($tweet);
$tweet_dump = ob_get_contents();
ob_end_clean();
wp_mail(
get_option('admin_email'),
'Tweet Fail',
"<pre>$tweet_dump</pre>",
array('Content-Type: text/html; charset=UTF-8')
);
}
Hier gilt das Selbe wie mit Facebook. Das Bild wird automatisch auf Twitter getweetet. Eine genauere Anleitung findet ihr hier:
publish_quote Action
function share_published_quote( $ID, $post ) {
require_once('twitter/twitter.php');
require_once('facebook/facebook.php');
$facebook_photo_id = facebook_photo_upload(array(
'url' => 'https://www.konzeptcode.com/wp-content/themes/konzeptcode-theme/inc/post-to-quote.php?blog_id='.get_current_blog_id().'&post_id='.$ID,
'caption' => $post->post_excerpt."\n".$post->post_title."\n".tags_to_hashtags($ID),
'post_id' => $ID
));
$tweet_id = tweet_media(array(
'post_id' => $ID,
'text' => $post->post_excerpt."\n".$post->post_title,
'hashtags' => tags_to_hashtags($ID),
'attachment_url' => 'https://www.konzeptcode.com/wp-content/themes/konzeptcode-theme/inc/post-to-quote.php?blog_id='.get_current_blog_id().'&post_id='.$ID
));
}
add_action( 'publish_quote', 'share_published_quote', 10, 2 );
WordPress bietet Action und Filter-Funktionen. Actions sorgen dafür, dass eine bestimmte Funktion zusätzlich ausgeführt wird, wenn etwas geschehen ist. Mit den Filtern kann man die Variablen, welche zurück gegeben werden manipulieren.
Ich habe hier wie ihr seht, publish_quote abgefangen. Das bedeutet, dass jedes Mal, wenn ein Beitrag mit dem Beitragstypen quote auf öffentlich gesetzt wird, die Funktion share_published_quote ausgeführt wird.
Der Bildgenerator
Ich habe mir gedacht, dass es besser ist, dass ich euch erst einmal ein Beispiel Bild zeige und dann im Code mit Kommentaren versuche, euch die einzelnen Schritte zu erklären. Dann könnt ihr auch die Zusammenhänge besser verstehen:

<?php
// Indem ich den Header so konfiguriere, sage ich aus, dass diese php Datei als eine Bilddatei ausgegeben werden soll.
header('Content-Type: image/jpeg');
// Die Essentiellen WordPress Dateien werden reingeladen
require_once("../../../../wp-load.php");
// Ich habe eine Multisite. Es wird auf den richtigen Blog gewechselt
switch_to_blog(intval($_GET['blog_id']));
// Initiale Variablen werden geholt
$post_id = intval($_GET['post_id']);
$hide_author = ($post_id)? boolval(get_post_meta($post_id, 'hide_author', true)) : boolval($_GET['hide_author']);
/* Essentielle Variablen */
$margin_bottom = 120;
$margin_left_right = 120;
$quote_size = 50;
$author_size = intval($quote_size / 1.5);
$padding = 50;
$quote = get_the_excerpt($post_id);
$author = get_the_title($post_id);
$file = get_the_post_thumbnail_url($post_id,'full');
$im = imagecreatefromjpeg($file);
$quote_font = get_template_directory().'/fonts/josefinsans/JosefinSans-Regular.ttf';
$author_font = get_template_directory().'/fonts/josefinsans/JosefinSans-Bold.ttf';
$white = imagecolorallocatealpha($im, 255, 255, 255,20);
$black = imagecolorallocate($im, 0, 0, 0);
/* Bildanpassung */
$imageDimensions = getimagesize($file);
$imageWidth = $imageDimensions[0];
$imageHeight = $imageDimensions[1];
$imageHeight = floor(($imageHeight/$imageWidth)*1920);
$imageWidth = 1920;
$im = imagescale($im,$imageWidth,$imageHeight);
$im = imagecrop($im,[
'x' => ($imageWidth > 1920)? ($imageWidth-1920)/2 : 0,
'y' => ($imageHeight > 1920)? ($imageHeight-1080)/2 : 0,
'width' => 1920,
'height' => 1080
]);
/* Author */
$author_text_sizes = imagettfbbox( $author_size,0 , $author_font, $author );
$author_width = $author_text_sizes[4];
$author_height = $author_text_sizes[1];
$author_position_bottom = ($hide_author)? 1080-$padding : 1080-$author_height-$margin_bottom;
/* Copyright */
$author_text_sizes = imagettfbbox( $author_size/1.5 ,0 , $author_font, 'talhasariyuerek.com' );
$author_width = $author_text_sizes[4];
$author_height = $author_text_sizes[1];
imagettftext($im, $author_size/1.5 , 0, 1920-$author_width-120+$padding, 1080-$author_height-$padding/2, $white, $author_font, 'talhasariyuerek.com');
/* Satz Umbruch Aufbau */
$words = explode(' ', $quote);
$quote = '';
$currentLine = '';
foreach ($words as $position => $word) {
if ($position === 0) {
$currentLine = $word;
} else {
$textDimensions = imagettfbbox(
$quote_size,
0,
$quote_font,
$currentLine . ' ' . $word
);
$textLeft = min($textDimensions[0], $textDimensions[6]);
$textRight = max($textDimensions[2], $textDimensions[4]);
$textWidth = $textRight - $textLeft;
if ($textWidth > 1680) {
$quote .= $currentLine;
$quote .= PHP_EOL;
$currentLine = $word;
} else {
$currentLine .= ' ';
$currentLine .= $word;
}
}
}
$quote .= $currentLine;
$text_size = imagettfbbox( $quote_size, 0, $quote_font, $quote );
$text_position_bottom = $author_position_bottom-$text_size[1]-1.5*$padding;
// Texthintergrund wird erstellt und eingebunden
imagefilledrectangle(
$im,
$margin_left_right-$padding, // links
$text_position_bottom-$quote_size-$padding, // Oben
1920 - 120 + $padding, // Rechts
1080 - $margin_bottom + $padding, // Unten
$white
);
// Das Zitat wird in das Bild geschrieben
imagettftext($im, $quote_size, 0, $margin_left_right, $text_position_bottom, $black, $quote_font, $quote);
// Wenn Autor gewünscht und gegeben wird der Autor hinzugefügt
if(!$hide_author) imagettftext($im, $author_size, 0, $margin_left_right, $author_position_bottom, $black, $author_font, $author);
// Die Verwendung von imagepng() ergibt bessere Textqualität als imagejpeg()
imagejpeg($im, NULL, 100);
imagedestroy($im);