Skip to content

Instantly share code, notes, and snippets.

@contempoinc
Created September 17, 2015 18:38
Show Gist options
  • Save contempoinc/b594106d215fee7c375d to your computer and use it in GitHub Desktop.
Save contempoinc/b594106d215fee7c375d to your computer and use it in GitHub Desktop.
PDF+XML functions
<?php
/* Usage Instructions
* [get-pdf-link] will return a raw link to the first PDF attachment to the post/page
*
* [pdf-content type="title|content"] "title" will return the Title of the PDF, which is referenced as "Root" in the XML document.
* ...continued: "content" will return the <Story> of the XML file, which is the top paragraph as assigned during PDF creation.
*/
add_filter('upload_mimes', 'custom_upload_xml');
function custom_upload_xml($mimes) {
$mimes = array_merge($mimes, array('xml' => 'application/xml'));
return $mimes;
}
add_filter( 'the_excerpt', 'shortcode_unautop');
add_filter( 'the_excerpt', 'do_shortcode');
function pdf_link(){
// Added otherwise it'll throw "Undefined variable" & "Trying to get property of non-object" errors
global $post;
$args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' => null, 'post_parent' => $post->ID );
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment )
{
if( strpos( wp_get_attachment_url( $attachment->ID ) , '.pdf') )
{
return wp_get_attachment_url( $attachment->ID );
}
}
}
}
add_shortcode('get-pdf-link','pdf_link');
function pdf_content($atts){
extract(shortcode_atts(array(
'type' => 'title'
), $atts));
// Added otherwise it'll throw "Undefined variable" & "Trying to get property of non-object" errors
global $post;
$args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' => null, 'post_parent' => $post->ID );
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment )
{
if( strpos( wp_get_attachment_url( $attachment->ID ) , '.xml') )
{
$url = wp_get_attachment_url( $attachment->ID );
$xml = file_get_contents($url);
$xml = simplexml_load_string($xml);
if ($type == 'title') {
$final = $xml->Root;
} else if ( $type == 'content') {
$final = $xml->Story;
}
else { $final = ''; }
return $final;
}
}
}
}
add_shortcode('pdf-content','pdf_content');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment