简体   繁体   中英

Populate a form field with page URL

I have a downloads section on a client wordpress site. Using Download Monitor plugin. They are protected with a form using the Ninja Forms addon for the DM plugin so users have to register details to access the download.

I'd like to add the ID from the download form URL to a field in the form so client can see which download that form registration is associated with.

The generated url of the unlock registration form for a particular download is similar to the following:

https://domain.com/no-access/download-id/572/

I have found how to do this with a query string ( https://ninjaforms.com/how-to-auto-populate-form-fields-using-query-string/ ) but not sure how to do it with the IDs in my url above.

Ideally I'd like to translate that ID to the actual download title too if that's possible.

Can anyone please advise?

Thanks!

If the id is always at the end of the url that way, you can use basename to grab it very simply:

<?php
    // in your code you will do this:
    //$url = $_SERVER['REQUEST_URI'];

    // but for this example, i need your url:
    $url = 'https://domain.com/no-access/download-id/572/';

    // grab the basename:
    $id = basename($url);

    echo "($id)"; // (572)

ADDITION

Now that you can find that $id which is the download-id requested, put it in a variable that you can use within the code that is writing your ninja form. For instance:

    $url = $_SERVER['REQUEST_URI'];

    // this was just for debugging...now comment it out
    // $url = 'https://domain.com/no-access/download-id/572/';
    // echo "($id)"; (572)

    $id = basename($url);

    // instead put it in a variable you can use in your form
    $GLOBALS['requested-download-id'] = (integer) $id;

Now wherever you have the code for your ninja form do something like this:

<form id="ninja-form" action="your-action" method="POST">

  <?php
    // sanity check...something may have gone wrong
    if (empty($GLOBALS['requested-download-id'])) {
      $download_id = 'NOT FOUND';
    } else {
      $download_id = $GLOBALS['requested-download-id'];
    }
  ?>
  <input value="<?php echo $download_id; ?>" type="hidden" name="download-id">

EVEN MORE SIMPLIFIED - DO IT ALL AT ONCE

<form id="ninja-form" action="your-action" method="POST">

  <?php
    $id = basename($_SERVER['REQUEST_URI']);
    // be sure you ended up with a number
    $id = (integer) $id;

    if (empty($id)) {
      $download_id = 'NOT FOUND';
    } else {
      $download_id = $id;
    }
  ?>
  <input value="<?php echo $download_id; ?>" type="hidden" name="download-id">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM