Skip to content

Commit

Permalink
Shortcodes: enable inline PDFs (#14960)
Browse files Browse the repository at this point in the history
* Shortcodes: enable inline PDFs

* Fix sprintf replacement

* Add unit tests and fix lint errors

* Fix lint errors, add prefix, and other fixes

Add unit test

* Fix unit test

Co-authored-by: Jeremy Herve <jeremy@jeremy.hu>
  • Loading branch information
lancewillett and jeherve authored Mar 30, 2020
1 parent ad6a639 commit a749f09
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
30 changes: 30 additions & 0 deletions modules/shortcodes/inline-pdfs.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php
/**
* Embed support for Inline PDFs
*
* Takes a plain-text PDF URL (*.pdf), and attempts to embed it directly
* in the post instead of leaving it as a bare link.
*
* @package Jetpack
*/

wp_embed_register_handler( 'inline-pdfs', '#https?://[^<]*\.pdf$#i', 'jetpack_inline_pdf_embed_handler' );

/**
* Callback to modify the output of embedded PDF files.
*
* @param array $matches Regex partial matches against the URL passed.
* @param array $attr Attributes received in embed response.
* @param array $url Requested URL to be embedded.
*/
function jetpack_inline_pdf_embed_handler( $matches, $attr, $url ) {
/** This action is documented in modules/widgets/social-media-icons.php */
do_action( 'jetpack_bump_stats_extras', 'embeds', 'inline-pdf' );

return sprintf(
'<object data="%1$s" type="application/pdf" width="100%%" height="800">
<p><a href="%1$s">%1$s</a></p>
</object>',
esc_attr( $url )
);
}
40 changes: 40 additions & 0 deletions tests/php/modules/shortcodes/test-class.inline-pdf.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php
/**
* Unit test for Inline PDF embeds.
*
* @package Jetpack
* @since 8.4
*/
class WP_Test_Jetpack_Shortcodes_Inline_Pdfs extends WP_UnitTestCase {

/**
* Unit test for Inline PDF embeds.
*
* @author lancewillett
* @covers ::jetpack_inline_pdf_embed_handler
* @since 8.4
*/
public function test_shortcodes_inline_pdf() {
global $post;

$url = 'https://jetpackme.files.wordpress.com/2017/08/jetpack-tips-for-hosts.pdf';
$post = $this->factory()->post->create_and_get( array( 'post_content' => $url ) );

setup_postdata( $post );

// Test HTML version.
ob_start();
the_content();
$actual = ob_get_clean();

wp_reset_postdata();

$this->assertContains(
sprintf(
'<p><object data="%1$s" type="application/pdf" width="100%%" height="800"><p><a href="%1$s">%1$s</a></p></object></p>' . "\n",
$url
),
$actual
);
}
}

0 comments on commit a749f09

Please sign in to comment.