php - 导航中的工作计数

标签 php html css wordpress variables

我正在尝试向我的菜单项“工作”添加一个数字以显示有多少工作可用。

这是一个 example

我有值(工作数),但我不知道如何将数字添加到我的菜单项中。

<?php
add_filter( 'nav_menu_link_attributes', 'dfib_contact_menu_atts', 10, 3 );
function dfib_contact_menu_atts( $atts, $item, $args ) {

    $jobs = new WP_Query(array( 'post_type' => 'jobs' ));

    if ($jobs->have_posts()) { 
        $count_posts = wp_count_posts( 'jobs' )->publish;
        echo "<span class='jobs__count'>$count_posts</span>"; 
    }

    // The ID of the target menu item
    $menu_target = "menu-item-19";

      // inspect $item
      if ($item->ID == $menu_target) {
        $atts["data-badge"] = $count_posts;
      }
      return $atts;
}
?>

我想将这个数字添加到类为“menu-item-job”的菜单项中,但我不知道如何在 php 中执行此操作

最佳答案

你应该使用 nav_menu_link_attributes() 钩子(Hook),因为它在这里解释:

https://wordpress.stackexchange.com/questions/121123/how-to-add-a-data-attribute-to-a-wordpress-menu-item

也就是说,类似于:

add_filter( 'nav_menu_link_attributes', 'wpse121123_contact_menu_atts', 10, 3 );
function wpse121123_contact_menu_atts( $atts, $item, $args )
{
  // The ID of the target menu item
  $menu_target = 123;

  // inspect $item
  if ($item->ID == $menu_target) {
    $atts['data-badge'] = $count_posts;
  }
  return $atts;
}

因此,将为您的菜单项显示值为 $count_posts 的新属性“data-badge”(假设它的 ID 为 123)。

然后您必须实现与您的示例网站相同的前端解决方案,以显示该属性。

关于php - 导航中的工作计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56853700/

相关文章:

php - 转义数据 - stripslashes, strip_tags

html - 使用 Bootstrap 3 时如何将最小布局宽度保持为 1024 像素?

html文本字段

css - 无法悬停以更改文本颜色

php - 在一台服务器上创建Mysql主机并从另一台服务器访问数据库?

javascript - 是否可以从 Html 本地存储输出到 .csv 或类似文件?

html - 在可变宽度表上设置 td 宽度并忽略内容的大小

PHP/MySQL 条件插入不插入

php - 如何在 C 中实现 Php call_user_func

php - 从 php 检测 MySQL querycache nativedriver