Note: this code will only work with the Premium versions of the plugin and only with files served from the /wp-content/uploads/
directory on your server.
You will need to write a bit of PHP for this feature. The code can be added to a custom or child theme’s functions.php file or by using a plugin that inserts PHP code into your site such as WPCode.
The PHP code:
// Code for PDF Embedder Counts.
function pdfemb_docs_get_attachment_id( $url, $invertscheme = false ) {
global $wpdb;
if ( $invertscheme ) {
$url = set_url_scheme( $url, preg_match( '#^https://#i', $url ) ? 'http' : 'https' );
}
$attachment = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE guid='%s';", esc_url( $url ) ) );
if ( is_array( $attachment ) && isset( $attachment[0] ) && $attachment[0] > 0 ) {
return $attachment[0];
}
return 0;
}
function pdfemb_docs_counts( $atts, $content = '' ) {
if ( empty( $atts['url'] ) ) {
return '<strong>PDF Embedder counts requires a URL attribute.</strong>';
}
$url = $atts['url'];
$post_id = pdfemb_docs_get_attachment_id( $url );
if ( ! $post_id ) {
$post_id = pdfemb_docs_get_attachment_id( $url, true );
}
if ( $post_id ) {
$count_views = get_post_meta( $post_id, 'pdfemb-views', true );
$count_downloads = get_post_meta( $post_id, 'pdfemb-downloads', true );
if ( is_numeric( $count_views ) ) {
$content .= 'Views: ' . $count_views;
}
if ( is_numeric( $count_downloads ) ) {
$content .= ' Downloads: ' . $count_downloads;
}
}
return $content;
}
add_shortcode( 'pdfemb-docs-counts', 'pdfemb_docs_counts' );
Code language: PHP (php)
You will need to use the Classic editor block if using the blocks editor or a Text/HTML/Code module with a drag and drop editor. In the page or post content, use the following shortcode replacing the path-to-pdf.pdf with your document’s file path:
[pdf-embedder-counts url="url-to-file.pdf"]
Code language: JSON / JSON with Comments (json)
Add the document title, thumbnail, or a link to the embed page and the end result will be something similar to this (the stats will update whenever the page is loaded):