简体   繁体   中英

send an array via PHP (WP plugin) to a front-end JS variable, then replace href links on the page (if exists)

I have a custom WordPress plugin that I've developed, it's partially completed, It uses a customer number that's pulled from a separate plugin. Then I take the customer #, pass it through a PDO connection to a local DB (in-house) and return an array of customized links for audio files in Amazon's S3. These links vary anywhere from 10 links to ~138 links. They have a "productID" which will be set as the id="productIDhere" on the front end page for the download links.

I need to pass the array over to JavaScript, then have JavaScript replace these URL's (if they exist) if not then go ahead and leave the default links in place.

1.) How do I pass the Array over to JavaScript from the WP plugin?

2.) How would I code the JavaScript to pick up the array, then search for the html links to replace, then actually replace them if they exist within the array.

How do I pass the Array over to JavaScript from the WP plugin?

WordPress HeartBeat API is great for features like this. Since you did not provide sample code, I will use my own example. Also, check out this tutorial: http://code.tutsplus.com/tutorials/the-heartbeat-api-getting-started--wp-32446

And some additional documentation: https://developer.wordpress.org/reference/hooks/heartbeat_received/

<?php
add_filter( 'heartbeat_received', function ( $response, $data, $screen_id ) {
    if ( isset( $data['something-to-enqueue'] ) ) {
        $response['something-to-enqueue'] = array('some-array' => 'this is my array');
    }
    return $response;
}, 10, 3 );
?>

 var name = 'something-to-enqueue'; wp.heartbeat.enqueue(name, { 'key': 'some-key', 'value': 'some-val' }, false); wp.heartbeat.connectNow(); jQuery(document).on('heartbeat-tick.' + name, function(event, data) { console.log(data[name]); /* do something with the array from php */ wp.heartbeat.dequeue(name); }); 

How would I code the JavaScript to pick up the array, then search for the html links to replace, then actually replace them if they exist within the array.

This portion of the answer is written in ES6.

<p>Lorem ipsum dolor sit amet, <a href="http://stackoverflow.com/questions/tagged/wordpress">wordpress on so</a> adipiscing elit. Duis tempor maximus purus, nec ullamcorper leo. Cras tortor ligula, blandit vel dolor eget, posuere eleifend dolor. Praesent tempus dui vel arcu imperdiet, eu placerat erat pulvinar. Vestibulum a <a href="http://stackoverflow.com/questions/tagged/javascript">javascript on so</a> viverra, feugiat ante pharetra, accumsan orci. Nulla vel lorem non odio ornare scelerisque quis a justo. Ut et placerat arcu. Ut dolor velit, interdum ac dolor aliquet, <a href="http://stackoverflow.com/">StackOverflow</a> pulvinar lacus. Vestibulum at nulla gravida, blandit lorem nec, hendrerit ipsum. Fusce dui odio, pellentesque at dictum sit amet, porttitor tincidunt ex.</p>
(function(urls){
    /**
     * rewrite links.
     * Rewrites the urls and domains respectively.
     * Do not analyze a link more than once.
     * Loop is resource heavy and has to go through every single link on page.
     */

    function getNewLinks (map, links) {
        /**
         * @param {object} map
         * Loop over all links and repalce origin with appropriate beta site
         */

        return [...links].map(function(link) {
            /** See if the link matches a key from the map */
            if (map.has(link.href)) {
                let newLink = link.href = link.href.replace(new RegExp(link.href, 'gi'), map.get(link.href)());
                return newLink;
            }
        }).filter(link => link !== null && link !== undefined);
    }

    var objectMap = new Map(),
        getHeartBeatAPI = () => 'http://wordpress.stackexchange.com/questions/tagged/heartbeat-api',
        getWPJS = () => 'http://wordpress.stackexchange.com/questions/tagged/javascript';


    /* you may need to do this differently, since you're url are from the heartbeat array, again you didn't provide any sample code to go off. */
    objectMap
        .set('http://stackoverflow.com/questions/tagged/wordpress', getHeartBeatAPI)
        .set('http://stackoverflow.com/questions/tagged/javascript', getWPJS);

    return getNewLinks(objectMap, urls);
}(document.links));

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