I put a contact form that the user must compile and if the fields are ok, it can start the automatic download's file, so I do this (suppose the title's file is "math" and the file is "math.pdf":

document.addEventListener( 'wpcf7mailsent', function( event ) {
   //This code is important
   var variable="<?php  echo get_attachment_url_by_slug('math); ?>";
    console.log("VARIABILE "+JSON.stringify(variable));

  //The code continues but it not important 
}, false );

Now in my functions.php, I add this method:

function get_attachment_url_by_slug( $slug ) {
  $args = array(
    'post_type' => 'attachment',
    'name' => sanitize_title($slug),
    'posts_per_page' => 1,
    'post_status' => 'inherit',
  $_header = get_posts( $args );
  $header = $_header ? array_pop($_header) : null;
  return $header ? wp_get_attachment_url($header->ID) : '';

The problem can be that javascript doesn't call the method in functions.php, or this way to operate is not correct. Anyone can help me?

  • Are you getting anything in your console log? As shown here you're missing a single quote that would make PHP not echo a URL at all. Also double-check your actual post slug for the "math.php" file and make sure you're passing the right value ('math'). – WebElaine Oct 6 '17 at 14:58
  • @webElaine I correct your suggest but it doens't work! – Van Oct 8 '17 at 14:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.