繁体   English   中英

我可以使用jQuery在帖子的缩略图后附加特定的帖子数据吗?

[英]Can I use jQuery to append specific post data with the post's thumbnail?

免责声明:我是一个普遍的新手,但特别是在JS和jQuery方面-实际上,我现在正在逐步完成cadecademy JS课程。

背景:我一直在试图找出如何在WP网站上帖子的缩略图下方(帖子的缩略图使用“列表类别帖子”插件显示)的特定内容,该缩略图显示在顶层页面上,而不是帖子本身,我一直在考虑以下两种方法之一:

1)使用“列表类别帖子”插件中的自定义字段显示2)使用jQuery来获取数据并将其附加到帖子缩略图下方,类似这样,但是它每次都必须可靠地获取唯一的数据,这将特定于每个帖子:

 <script>
 jQuery("#content > article > header > .entry-title").append("<hr />");
 </script>

该字段在每个帖子中作为ID不变(#static_field)。 我敢肯定有一个相当可靠的方法可以做到这一点,但是我不确定如何做到这一点。 我可以在代码中指定从何处获取每个帖子的数据来代替水平行吗?

一如既往,任何及所有帮助/建设性的批评表示赞赏!

在高层次上:

  1. 您需要设置WP端点以返回所需的数据。 通常,这将在functions.php看起来像:

     //setup hooks add_action('wp_ajax_my_action', 'my_action_cb'); add_action('wp_ajax_nopriv_my_action', 'my_action_cb'); // non logged in users function my_action_cb() { // pull in global global $wpdb; // grab sanitized get id value $post_id = filter_var($_GET['post_id'], FILTER_SANITIZE_STRING); $data = array(); //grab the data you need from the db and save to data echo json_encode($data); // json_encode the data wp_die(); // bail } 

更多信息: https//codex.wordpress.org/AJAX_in_Plugins

1b。 本地化您的wp_ajax_url。 仍然在functions.php中:

    wp_localize_script( some_handle, 'admin_url', array('ajax_url' => admin_url( 'admin-ajax.php' ) ) );
  1. 然后针对页面上的每个帖子,获取post_id并提出ajax请求

     (function($){ //grab all the articles on this page // loop over them and make an ajax call with the post id $(SOMESLECTOR).each(function() { var article = $(this); // get post_id from somehwhere makeAjaxRequest(post_id).then(function(resp) { // resp is a JS object that should contain whatever data you echoed in php article.find('.entry-title').append(/** Append you data here **/); }); }); function makeAjaxRequest(postId) { return $.ajax({ url: admin_url.ajax_url, data: { action: my_action, // same thing provided wp_ajax_<action> post_id: postId } }) } })(jQuery); 

注意:

与仅跳入WP模板文件并在循环中获取数据相比,这需要更多的工作和更多的开销。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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