链接到 cpt 的最新元素的菜单项

问题描述 投票:0回答:1

我使用 WordPress 和 Divi 主题。 我有一个名为 Publications 的 CPT。 我将拥有本年度 CPT 的一项(从 2013 年开始)。 “出版物”是主菜单中的一项。 有没有解决方案可以建立到出版物 CPT 最后一项的链接?

卡罗琳

wordpress hyperlink menu
1个回答
0
投票
  • 使用自定义查询从您的 CPT 检索最新出版物。您可以使用 WP_Query 类来实现此目的。

    $args = 数组( 'post_type' => '出版物', 'posts_per_page' => 1, 'orderby' => '日期', '订单' => 'DESC', );

    $latest_publication = new WP_Query($args);

    if ($latest_publication->have_posts()) { while ($latest_publication->have_posts()) { $latest_publication->the_post(); // 您现在处于最新出版物的循环内。 // 您可以在此处检索信息或自定义链接。 } }

    wp_reset_postdata(); // 自定义查询后重置发布数据。

  • 您可以使用 get_permalink() 函数获取最新出版物的永久链接并创建链接。

集成到 WordPress 菜单中: 要将其集成到您的 WordPress 菜单中,您可能需要使用自定义链接。您可以将自定义链接添加到 WordPress 菜单并使用占位符 URL(例如#latest-publication)。然后,使用 JavaScript 或 jQuery 在前端动态更新链接。

<script>
// Add this script to your theme (you might need to enqueue it properly).
document.addEventListener("DOMContentLoaded", function () {
// Assuming you've used the URL placeholder #latest-publication.
var latestPublicationLink = document.querySelector('a[href="#latest- 
publication"]');

// Update the href attribute with the actual link.
latestPublicationLink.href = "<?php echo esc_url($latest_publication_permalink); 
?>";
});
</script>

确保将脚本正确排入主题的functions.php 文件中或使用专用脚本文件。

这种方法允许您动态生成最新出版物的链接并将其集成到您的 WordPress 菜单中。根据您的主题结构和要求调整代码。

© www.soinside.com 2019 - 2024. All rights reserved.