Created
August 1, 2021 11:30
-
-
Save janboddez/40a2b38f868a38ee77bb8c687b152524 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Turns posts created through "Press This" into "read" posts. | |
*/ | |
add_filter( 'press_this_save_post', function( $data ) { | |
$data['post_type'] = 'iwcpt_read'; | |
$content = wp_unslash( $data['post_content'] ); | |
if ( preg_match_all( '~<blockquote>(.+?)</blockquote>~', $content, $matches ) ) { | |
for ( $i = 0; $i < count( $matches[0] ); $i++ ) { | |
$content = str_replace( $matches[0][$i], "\n> " . $matches[1][$i], $content ); | |
} | |
} | |
$content = trim( $content ); | |
if ( preg_match( '~Source: <em><a href="(.+?)">(?:.*?)</a></em>~', $content, $matches ) ) { | |
$url = $matches[1]; | |
$content = str_replace( $matches[0], '', $content ); | |
$content = '<i>Wants to read <a class="u-read-of" href="' . $url . '">' . $url . "</a>.</i>\n\n" . $content; | |
} | |
$content = preg_replace( '~<p>\s*</p>~', '', $content ); | |
$content = trim( $content ); | |
$data['post_content'] = wp_slash( $content ); | |
global $wpdb; | |
// Generate a random slug. (The IWCPT plugin will _not_ do this for us, as | |
// this callback runs _after_ the post's already been created.) | |
do { | |
$slug = bin2hex( openssl_random_pseudo_bytes( 5 ) ); | |
// Check uniqueness. | |
$result = $wpdb->get_var( $wpdb->prepare( "SELECT post_name FROM $wpdb->posts WHERE post_name = %s LIMIT 1", $slug ) ); | |
} while ( $result ); // If an identical slug already exists, repeat. | |
$data['post_name'] = $slug; | |
if ( ! empty( $url ) ) { | |
// Add post to my reader's Read Later "feed." To do: move this to | |
// another hook? | |
wp_remote_post( | |
esc_url_raw( 'https://fstop.cloud/micropub' ), | |
array( | |
'headers' => array( | |
'Authorization' => 'Bearer ' . '<my-secret-token>', | |
'Content-type' => 'application/x-www-form-urlencoded', | |
), | |
'body' => array( | |
'h' => 'entry', | |
'read-of' => $url, | |
), | |
'timeout' => 15, | |
) | |
); | |
} | |
return $data; | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment