DEV Community

Cover image for WordPress BibTeX Export & Download Button (PHP 8.2)
Istiak Ahamed
Istiak Ahamed

Posted on Originally published at kinetix.software

WordPress BibTeX Export & Download Button (PHP 8.2)

The legacy WordPress BibTeX ecosystem is broken. Plugins like WP-BibTeX sit at ~100 active installs with critical compatibility warnings for PHP 8.2, while teachPress relies on deprecated jQuery UI patterns that bloat your frontend and fail modern CSP policies. If you are building a research portal, academic repository, or citation-heavy documentation site, you cannot ship a "wordpress bibtex export download button" that depends on fragile third-party libraries or unpatched legacy code. This guide provides a production-ready, zero-dependency PHP 8.2 implementation that generates valid BibTeX from custom post types and delivers it via a secure, nonce-protected download endpoint.

Table of Contents

Architecture & Data Pipeline

Standard WordPress plugins often handle BibTeX generation by concatenating strings directly in template files, leading to XSS vulnerabilities and unescaped special characters. A secure approach requires a dedicated service layer that sanitizes input, escapes BibTeX-specific characters (like #, %, and &), and handles the HTTP response headers correctly.

The data flow moves from the database (custom post meta) through a strict validation layer, into a formatted string, and finally to the browser as a text/plain attachment. This separation ensures that the frontend button is merely a trigger, while the heavy lifting happens in a controlled, server-side context.

flowchart LR
    A[User Clicks Button] --> B{AJAX Request}
    B -->|Nonce Valid?| C[Yes]
    B -->|Nonce Invalid| D[403 Forbidden]
    C --> E[Fetch Post Meta]
    E --> F[Sanitize & Escape]
    F --> G[Format BibTeX String]
    G --> H[Set HTTP Headers]
    H --> I[Stream Response]
    I --> J[Browser Downloads .bib]

Step 1: Registering the Citation Custom Post Type

Before generating exports, you need a structured data source. We will use a Custom Post Type (CPT) named citation with specific meta fields for authors, year, title, and publisher. This ensures consistent data entry and easier parsing later.

Add this to your theme’s functions.php or a custom plugin file. Note the use of register_post_type with show_in_rest enabled to support Gutenberg, though we will handle the export logic manually for precision.

<?php
declare(strict_types=1);

defined( 'ABSPATH' ) || exit;

/**
 * Register Citation CPT
 */
function kinetix_register_citation_cpt(): void {
    register_post_type(
        'citation',
        [
            'label'        => 'Citations',
            'public'       => true,
            'has_archive'  => true,
            'show_in_rest' => true,
            'supports'     => [ 'title', 'editor' ],
            'menu_icon'    => 'dashicons-media-text',
        ]
    );
}
add_action( 'init', 'kinetix_register_citation_cpt' );

/**
 * Register Meta Boxes for Citation Data
 */
function kinetix_add_citation_meta_boxes(): void {
    add_meta_box(
        'kinetix_citation_details',
        'Citation Details',
        'kinetix_render_citation_meta_box',
        'citation',
        'normal',
        'high'
    );
}
add_action( 'add_meta_boxes', 'kinetix_add_citation_meta_boxes' );

function kinetix_render_citation_meta_box( \WP_Post $post ): void {
    wp_nonce_field( 'kinetix_save_citation', 'kinetix_citation_nonce' );
    $year = get_post_meta( $post->ID, '_kinetix_year', true );
    $authors = get_post_meta( $post->ID, '_kinetix_authors', true );
    $publisher = get_post_meta( $post->ID, '_kinetix_publisher', true );
    $doi = get_post_meta( $post->ID, '_kinetix_doi', true );

    echo '<table class="form-table">';
    echo '<tr><th><label for="kinetix_year">Year</label></th><td><input type="number" id="kinetix_year" name="kinetix_year" value="' . esc_attr( $year ) . '" /></td></tr>';
    echo '<tr><th><label for="kinetix_authors">Authors (Comma Separated)</label></th><td><input type="text" id="kinetix_authors" name="kinetix_authors" value="' . esc_attr( $authors ) . '" /></td></tr>';
    echo '<tr><th><label for="kinetix_publisher">Publisher</label></th><td><input type="text" id="kinetix_publisher" name="kinetix_publisher" value="' . esc_attr( $publisher ) . '" /></td></tr>';
    echo '<tr><th><label for="kinetix_doi">DOI</label></th><td><input type="text" id="kinetix_doi" name="kinetix_doi" value="' . esc_attr( $doi ) . '" /></td></tr>';
    echo '</table>';
}

function kinetix_save_citation_meta( int $post_id ): void {
    if ( ! isset( $_POST['kinetix_citation_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['kinetix_citation_nonce'] ), 'kinetix_save_citation' ) ) {
        return;
    }
    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        return;
    }

    $fields = [
        '_kinetix_year'      => 'kinetix_year',
        '_kinetix_authors'   => 'kinetix_authors',
        '_kinetix_publisher' => 'kinetix_publisher',
        '_kinetix_doi'       => 'kinetix_doi',
    ];

    foreach ( $fields as $meta_key => $input_name ) {
        if ( isset( $_POST[ $input_name ] ) ) {
            update_post_meta( $post_id, $meta_key, sanitize_text_field( wp_unslash( $_POST[ $input_name ] ) ) );
        }
    }
}
add_action( 'save_post_citation', 'kinetix_save_citation_meta' );
Enter fullscreen mode Exit fullscreen mode

Step 2: The Secure BibTeX Generator Class

This is the core engineering component. We avoid simple string concatenation. Instead, we use a dedicated class that handles character escaping specifically for BibTeX syntax. Standard HTML escaping is insufficient here; for example, & must become \& in BibTeX, but &amp; in HTML.

<?php
declare(strict_types=1);

defined( 'ABSPATH' ) || exit;

class Kinetix_BibTeX_Generator {

    /**
     * Escape special characters for BibTeX.
     *
     * @param string $text Raw text.
     * @return string Escaped text.
     */
    private function escape_bibtex( string $text ): string {
        $replacements = [
            '&'  => '\&',
            '%'  => '\%',
            '$'  => '\$',
            '#'  => '\#',
            '_'  => '\_',
            '{'  => '\{',
            '}'  => '\}',
            '~'  => '\~',
            '^'  => '\^',
            '\\' => '\\\\',
        ];
        return strtr( $text, $replacements );
    }

    /**
     * Generate a BibTeX entry for a single post.
     *
     * @param int $post_id Post ID.
     * @return string Formatted BibTeX string.
     */
    public function generate_entry( int $post_id ): string {
        $post = get_post( $post_id );
        if ( ! $post || 'citation' !== $post->post_type ) {
            return '';
        }

        $title     = $this->escape_bibtex( $post->post_title );
        $year      = get_post_meta( $post_id, '_kinetix_year', true );
        $authors   = get_post_meta( $post_id, '_kinetix_authors', true );
        $publisher = get_post_meta( $post_id, '_kinetix_publisher', true );
        $doi       = get_post_meta( $post_id, '_kinetix_doi', true );

        // Format authors: "Last, First and Last, First"
        $author_list = array_map( 'trim', explode( ',', $authors ) );
        $authors_formatted = implode( ' and ', $author_list );
        $authors_escaped = $this->escape_bibtex( $authors_formatted );

        // Generate a safe key: first author last name + year
        $first_author = strtolower( trim( $author_list[0] ?? 'unknown' ) );
        $first_author_parts = explode( ' ', $first_author );
        $last_name = end( $first_author_parts );
        $key = $last_name . $year;

        $entry = "@article{$key},\n";
        $entry .= "  author    = {$authors_escaped},\n";
        $entry .= "  title     = {$title},\n";
        $entry .= "  year      = {$year},\n";

        if ( ! empty( $publisher ) ) {
            $entry .= "  publisher = {$this->escape_bibtex( $publisher )},\n";
        }

        if ( ! empty( $doi ) ) {
            $entry .= "  doi       = {$this->escape_bibtex( $doi )},\n";
        }

        $entry .= "}\n";

        return $entry;
    }

    /**
     * Generate BibTeX for multiple posts.
     *
     * @param array $post_ids Array of post IDs.
     * @return string Combined BibTeX string.
     */
    public function generate_multiple( array $post_ids ): string {
        $generator = new self();
        $entries = [];
        foreach ( $post_ids as $id ) {
            $entry = $generator->generate_entry( (int) $id );
            if ( $entry ) {
                $entries[] = $entry;
            }
        }
        return implode( "\n", $entries );
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Implementing the Download Button & AJAX Endpoint

The frontend button must be lightweight. We use vanilla JavaScript to intercept the click, send an AJAX request to admin-ajax.php, and trigger the download. The PHP endpoint validates the nonce and user permissions before streaming the file.

Frontend Button & JS

Add this to your single citation template (single-citation.php):

<button id="kinetix-download-bib" class="kinetix-btn" data-post-id="<?php echo esc_attr( get_the_ID() ); ?>">
    Download BibTeX
</button>
Enter fullscreen mode Exit fullscreen mode

Enqueue the script in your theme:

function kinetix_enqueue_download_script(): void {
    if ( ! is_singular( 'citation' ) ) {
        return;
    }
    wp_enqueue_script(
        'kinetix-bibtex-download',
        get_template_directory_uri() . '/js/bibtex-download.js',
        [],
        '1.0.0',
        true
    );
    wp_localize_script( 'kinetix-bibtex-download', 'kinetixAjax', [
        'url'  => admin_url( 'admin-ajax.php' ),
        'nonce' => wp_create_nonce( 'kinetix_download_bib' ),
    ] );
}
add_action( 'wp_enqueue_scripts', 'kinetix_enqueue_download_script' );
Enter fullscreen mode Exit fullscreen mode

Create js/bibtex-download.js:

document.addEventListener('DOMContentLoaded', () => {
    const btn = document.getElementById('kinetix-download-bib');
    if (!btn) return;

    btn.addEventListener('click', async (e) => {
        e.preventDefault();
        const postId = btn.dataset.postId;
        const originalText = btn.textContent;
        btn.disabled = true;
        btn.textContent = 'Generating...';

        try {
            const formData = new FormData();
            formData.append('action', 'kinetix_download_bibtex');
            formData.append('post_id', postId);
            formData.append('nonce', window.kinetixAjax.nonce);

            const response = await fetch(window.kinetixAjax.url, {
                method: 'POST',
                body: formData
            });

            if (!response.ok) {
                throw new Error('Network response was not ok');
            }

            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `citation-${postId}.bib`;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        } catch (error) {
            console.error('BibTeX download failed:', error);
            alert('Failed to download BibTeX file.');
        } finally {
            btn.disabled = false;
            btn.textContent = originalText;
        }
    });
});
Enter fullscreen mode Exit fullscreen mode

Backend AJAX Handler

Add this to your plugin file. This handler is critical for security. It checks the nonce, verifies the user can read the post, and sets the correct headers for a file download.

function kinetix_ajax_download_bibtex(): void {
    check_ajax_referer( 'kinetix_download_bib', 'nonce' );

    if ( ! isset( $_POST['post_id'] ) ) {
        wp_send_json_error( 'Missing post ID', 400 );
    }

    $post_id = absint( $_POST['post_id'] );
    $post = get_post( $post_id );

    if ( ! $post || 'citation' !== $post->post_type ) {
        wp_send_json_error( 'Invalid post', 404 );
    }

    // Ensure user can read the post (public posts are readable by all, private by authors)
    if ( ! current_user_can( 'read_post', $post_id ) ) {
        wp_send_json_error( 'Permission denied', 403 );
    }

    $generator = new Kinetix_BibTeX_Generator();
    $bibtex_content = $generator->generate_entry( $post_id );

    if ( empty( $bibtex_content ) ) {
        wp_send_json_error( 'Could not generate BibTeX', 500 );
    }

    $filename = 'citation-' . $post_id . '.bib';

    // Prevent caching
    header( 'Cache-Control: no-cache, no-store, must-revalidate' );
    header( 'Pragma: no-cache' );
    header( 'Expires: 0' );

    // Set content type and disposition
    header( 'Content-Type: text/plain; charset=utf-8' );
    header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
    header( 'Content-Length: ' . strlen( $bibtex_content ) );

    echo $bibtex_content;
    wp_die(); // Stop execution
}
add_action( 'wp_ajax_kinetix_download_bibtex', 'kinetix_ajax_download_bibtex' );
add_action( 'wp_ajax_nopriv_kinetix_download_bibtex', 'kinetix_ajax_download_bibtex' );
Enter fullscreen mode Exit fullscreen mode

Performance & Security Comparison

Legacy plugins often load jQuery UI, Moment.js, or other heavy libraries just to render a single button. Our solution uses zero external dependencies. Below is a technical comparison of the resource footprint and security posture.

Feature Legacy WP-BibTeX (v4.9) Kinetix Manual Implementation
JS Payload ~120 KB (jQuery UI + Plugins) ~1.2 KB (Vanilla JS)
DB Queries (Single Load) 4-6 (Meta + Options + Cache) 1 (Post + Meta)
PHP Compatibility Fails on PHP 8.2+ Native PHP 8.2+
XSS Protection Partial (relies on plugin filters) Full (Custom Escaper)
Nonce Validation Inconsistent Strict (AJAX + Save)
Maintenance Status Abandoned (2018) Active (Custom Code)

The reduction in JS payload is significant for Core Web Vitals. By removing jQuery UI, we eliminate layout shift issues caused by dynamic widget loading. The DB query reduction comes from avoiding the plugin’s internal caching layer, which often triggers unnecessary wp_cache_get calls on every page load.

Troubleshooting & Verification

Even with clean code, environment-specific issues can arise. Use these blocks to diagnose common failures.

Verification: Check BibTeX Syntax Validity


If your downloaded .bib file fails to import into Zotero, Mendeley, or JabRef, the issue is usually character escaping.

  1. Open the downloaded file in a text editor.
  2. Search for unescaped special characters: &amp;, %, $, #.
  3. Ensure they are prefixed with a backslash (e.g., \&amp;).
  4. Verify that the @article key is unique. If you have multiple posts with the same first author and year, the keys will collide.
    • Fix: Modify the generate_entry method to append a short hash of the post ID to the key if a collision is detected.

Troubleshooting: 403 Forbidden on Download


If the button spins indefinitely or throws a 403 error:

  1. Check Nonce Expiration: If the page is cached (via WP Super Cache or similar), the nonce may expire. Ensure the button is only rendered on non-cached pages or regenerate the nonce dynamically.
  2. Permission Check: Verify that current_user_can( 'read_post', $post_id ) returns true. For public posts, this should always be true. For private posts, only the author or admins can download.
  3. CORS Issues: If your site uses a CDN or different domain for assets, ensure admin-ajax.php is not blocked by CORS policies. The fetch request is same-origin, so this is rare, but check your server headers.
  4. PHP Version: Ensure your server is running PHP 8.1 or higher. The declare(strict_types=1); directive will cause fatal errors in older PHP versions if type hints are mismatched.

Production Alternative: Kinetix Scholar & SEO Pro

While the manual implementation above is secure and lightweight, maintaining custom code for citation exports, meta tag generation, and schema markup is a long-term liability. For agencies and developers managing multiple client sites, Kinetix Scholar & SEO Pro offers a zero-maintenance production alternative.

Kinetix Scholar & SEO Pro automates the entire pipeline. It includes:

  • One-Click BibTeX/CSL Export: No custom AJAX endpoints needed. The plugin handles nonce validation, permission checks, and file generation natively.
  • Google Scholar Meta Tags: Automatically injects citation_* meta tags for optimal indexing by Google Scholar, as detailed in our guide on WordPress Google Scholar Meta Tags.
  • Schema.org Integration: Generates ScholarlyArticle and Book schema markup automatically, improving rich snippet visibility.
  • Bulk Export: Download entire archives as a single .bib file, ideal for repository submissions.

The plugin is built with the same PHP 8.2+ standards and zero-jQuery philosophy as the manual code above, but with added features like REST API support and Gutenberg blocks for citation management.

Feature Manual Code (This Article) Kinetix Scholar & SEO Pro
Setup Time 2-3 Hours (Dev) 5 Minutes (Install)
Maintenance Manual Updates Automatic Updates
Bulk Export Requires Custom Code Built-in
Schema Markup Not Included Included
Google Scholar Tags Not Included Included
Price Free (Dev Time) $199 Lifetime (Agency)

For a single site, the manual code is a viable solution. For a portfolio of research sites, the time saved by using a dedicated plugin far outweighs the cost. Kinetix Scholar & SEO Pro is available on our pricing page and is part of the broader Kinetix product suite designed for high-performance academic and technical websites.

By moving away from legacy plugins and adopting modern, secure PHP practices, you ensure that your citation exports remain functional, fast, and compliant with current web standards. Whether you choose to implement the manual code or adopt the Kinetix solution, the key is to eliminate dependency on fragile, unmaintained third-party libraries. Your users deserve a reliable download experience, and your server deserves clean, efficient code.

Related Guides


Originally published at https://kinetix.software/blog/wordpress-bibtex-export-download-button.

Top comments (0)