Support

Account

Home Forums General Issues Dynamically create vcard from ACF data and download with button click? Reply To: Dynamically create vcard from ACF data and download with button click?

  • So I did end up just creating the vCard upon saving the custom post type by cobbling together a few different methods. I started with this function:

    function hj_create_vCard( $post_id ) {
    
    	/*
         * In production code, $slug should be set only once in the plugin,
         * preferably as a class property, rather than in each function that needs it.
         */
        $post_type = get_post_type($post_id);
    
        // only update the attorneys custom post type on save
        if ( "attorneys" != $post_type ) return;
    
        $vpost = get_post($post->ID);
        $filename = $vpost->post_name.".vcf";
        header('Content-type: text/x-vcard; charset=utf-8');
        header("Content-Disposition: attachment; filename=".$filename);
        $data=null;
        $data.="BEGIN:VCARD\n";
        $data.="VERSION:3.0\n";
        $data.="FN:".$vpost->post_title."\n"; // get post title
        $data.="ORG:Client Company Name\n";
        $data.="EMAIL;TYPE=work:" .get_field('att_email',$vpost->ID)."\n";  // get acf field value
        $data.="TEL;WORK;VOICE:" .get_field('att_phone',$vpost->ID)."\n";  // get acf field value
        $data.="ADR;WORK;PREF:123 Fake Street;Fake City;MN;55106\n";  // get acf field value
        $data.="END:VCARD";
        $filePath = get_template_directory()."/vcard/".$filename; // you can specify path here where you want to store file.
        $file = fopen($filePath,"w");
        fwrite($file,$data);
        fclose($file);
    }
    add_action( 'save_post', 'hj_create_vCard' );

    Then for use in my template I just grab the file that is generated on save by looking for the file based on its name, which is generated from the page slug:

    <?php
    global $post;
    $vcfname = $post->post_name;
    ?>
    
    <a href="<?php echo get_template_directory_uri(); ?>/vcard/<?php echo $vcfname; ?>.vcf"><i class="far fa-address-card"></i> Download Vcard</a>