我正在做一个wordpress项目,我完全陷入了困境......我必须把它们的阅读时间放在帖子附近的某个地方(在帖子网格页面中)。因此,我必须测试一个 js 脚本,该脚本采用 url(在元素上找到的 href)和主题的 function.php 文件中的一个函数,该函数采用帖子的 url 并返回计算的阅读时间...不过,当我手动输入短代码时它可以工作,但当我使用 JS 时则不行。 (顺便说一句,我也在使用 elmentor ...)
JS脚本(html块):
<script>
document.addEventListener('DOMContentLoaded', function(){
let childDivs = document.querySelectorAll('.void-row > *');
childDivs.forEach(child =>{
let links = child.querySelectorAll('a');
let postUrl = links[0].href;
let short = `[get_post_reading_time url=${postUrl}]`;
links[4].textContent = short;
});
});
</script>
Php 函数(function.php):
function get_post_reading_time($att = '', $content = null){
$url = $att['url'];
$post_id = url_to_postid($url);
$post = get_post($post_id);
$content = $post->post_content;
$word_count = str_word_count(strip_tags($content));
return ceil($word_count / 200);
}
add_shortcode('get_post_reading_time', 'get_post_reading_time');
有人可以帮助我理解和/或找到另一种方法吗?提前致谢。 (也许是因为 function.php 在 JS 脚本中替换了链接 [4] 的 textContent 中的短代码?)
我会使用 AJAX 来更轻松地获取数据,这是 function.php 的样子:
function record_reading_time() {
if (isset($_POST['url'], $_POST['time_spent'])) {
$url = $_POST['url'];
$time_spent = intval($_POST['time_spent']); // Convert to integer
$post_id = url_to_postid($url);
// Here you can update a post meta or perform any other action
update_post_meta($post_id, 'user_time_spent', $time_spent);
echo 'Time successfully recorded';
wp_die(); // Important for proper AJAX response termination
}
}
add_action('wp_ajax_nopriv_record_reading_time', 'record_reading_time');
add_action('wp_ajax_record_reading_time', 'record_reading_time');
然后,对于前端 javascript,我将使用如下函数: document.addEventListener('DOMContentLoaded', function () { 让 startTime = Date.now();
function sendTimeOnPage() {
let endTime = Date.now();
let timeSpent = endTime - startTime; // Time in milliseconds
let postUrl = window.location.href;
// Send the time spent back to the server using AJAX
fetch(ajaxurl, {
method: 'POST',
credentials: 'same-origin',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
}),
body: `action=record_reading_time&url=${encodeURIComponent(postUrl)}&time_spent=${timeSpent}`
})
.then(response => response.text())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));
}
window.addEventListener('beforeunload', sendTimeOnPage);
});
请务必将
替换为应发送 AJAX 请求的 URL。ajaxurl
现在,这就是我所知道的你所问的问题,但我不是 Workdpress 方面的专家,所以请确保你的 JavaScript 在 WordPress 中正确排队,如果你有更多自定义黑客,请进行调整;)