通过PHP (WP插件)发送一个数组到前端JS变量,然后替换页面上的href链接(如果存在)


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

我有一个自定义的WordPress插件,我已经开发,它是部分完成,它使用一个客户号码,从一个单独的插件拉。然后,我获取客户#,通过PDO连接将其传递到本地DB(内部),并返回Amazon S3中音频文件的自定义链接数组。这些链接从10个到138个不等。他们有一个"productID",它将被设置为id="productIDhere"在前端页面的下载链接。

我需要将数组传递给JavaScript,然后让JavaScript替换这些URL(如果它们存在),如果没有,那么继续并保留默认链接。

1)。我如何从WP插件传递数组到JavaScript ?

2)。我将如何编写JavaScript来获取数组,然后搜索要替换的html链接,然后如果它们存在于数组中,则实际替换它们。

如何将数组从WP插件传递到JavaScript ?

WordPress HeartBeat API非常适合这样的功能。由于您没有提供示例代码,我将使用我自己的示例。另外,请查看本教程:http://code.tutsplus.com/tutorials/the-heartbeat-api-getting-started--wp-32446

和一些额外的文档: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);
});

我如何编写JavaScript来获取数组,然后搜索要替换的html链接,然后如果它们存在于数组中,则实际替换它们。

这部分答案是用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));
相关文章: