【问题标题】:WordPress: Sort custom taxonomy by Megabyte / Gigabyte name valueWordPress:按兆字节/千兆字节名称值对自定义分类进行排序
【发布时间】:2012-04-02 22:17:33
【问题描述】:

基本上,我正在为 USB 驱动器制造商创建一个网站。我使用自定义分类法来表示该公司提供的每个 USB 驱动器的内存大小。以下是 WordPress 输出我的术语的方式...

$terms = get_the_terms($post->ID, 'usb_mem');

if ($terms) {
 foreach ($terms as $taxindex => $taxitem) {

     echo '<span class="product_terms">' . $taxitem->name . '</span>';

 }
}

-16GB
-1GB
-256MB
-2GB
-32GB
-4GB
-512MB
-8GB

我需要 WordPress 按实际数据大小对它们进行排序,而不仅仅是数字。理想情况下是这样的:

-256MB
-512MB
-1GB
-2GB
-4GB
-8GB
-16GB
-32GB

提前致谢! :D

【问题讨论】:

  • 我不习惯php和相关的东西,但是为什么不拆分名称并将MB、GB分别扩展为2^20、2^30字节,然后比较字节值。

标签: php wordpress sorting taxonomy usort


【解决方案1】:

请注意,所有这些代码都是内联的。你最好过:

  • 在导入时标准化大小,从而避免大部分混乱。
  • 构造一个类来处理所有这些。

无论哪种方式,这里都是适当的代码。

// This is our lookup table to deal with strings.
$size_lookups = array('GB'=>pow(2,30), 'MB'=>pow(2,20), 'KB'=>pow(2,10), 'TB'=>pow(2,40));

// First, normalize all of the fields.
foreach ($terms as $taxitem)
{
   $taxitem->fixed_size = intval($taxitem->size,10);
   foreach ($size_lookups as $sizekey=>$sizemod)
   {
      if (strripos($taxitem->size, $sizekey))
      {
          $taxitem->fixed_size = intval($taxitem->size, 10) * $sizemod;
          break;
      }
   }
}

// Set up a sorting function.
function sortBySize($a, $b)
{
    return $b->fixed_size - $a->fixed_size;
}

// Do the sort.
$sorted = array_values($terms); // set up a shadow copy with new indexes.
usort ($sorted , 'sortBySize' );

// Display the results.
foreach ($sorted as $taxitem) {
    echo '<span class="product_terms">' . $taxitem->name . '</span>';
}

【讨论】:

  • 非常感谢!我只是对其进行了一些修改以使其完美运行:// Set up a sorting function. function sortBySize($a, $b) { if ($a-&gt;fixed_size == $b-&gt;fixed_size) { return 0; } return ($a-&gt;fixed_size &lt; $b-&gt;fixed_size) ? -1 : 1; }
  • 很高兴您对答案感到满意。我会说在这种情况下额外复杂的排序是不必要的,因为 fixed_size 已经规范化为一个 int,虽然是 intval。可以采用任何一种方式,因为除了 int 之外的任何排序都应该使用像你这样的函数。
猜你喜欢
  • 1970-01-01
  • 2011-01-31
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 2010-10-08
  • 1970-01-01
  • 2011-01-22
  • 2020-06-09
相关资源
最近更新 更多