【发布时间】:2014-03-09 08:10:32
【问题描述】:
我正在尝试为分页的 WordPress 帖子生成自定义链接文本。
使用<!--nextpage--><!--pagetitle: My Title-->,我识别分页符并为下一页设置标题。
标题用作生成链接中的文本(而不是 WordPress 默认的 --plain 数字)。
调用wp_link_pages_titled() 将生成自定义链接并将其打印在页面上。
该函数按预期工作,并生成正确的链接,但是当<!--pagetitle: My Title--> 不存在时使用的回退有问题。
当没有指定标题时,我想恢复使用“页面 [编号]”作为链接文本。不幸的是,回退是打印不正确的数字。
为了测试这个功能,我创建了一个包含 3 个分页部分的帖子,这些部分都没有标题。
链接应该打印为
- 第 1 页
- 第 2 页
- 第 3 页
而是打印为
- 第 1 页
- 第 1 页
- 第 1 页
注意:锚的href属性是正确的,只有显示的文字是错误的。
我在下面包含了 foreach 循环。我试图尽可能多地评论 PHP 以描述正在发生的事情。
// For each paginated section
foreach ( $pages as $ndx => $part_content) {
$pageNumber = $ndx + 1;
// Check to see if the pagetitle quick tag is present
$has_part_title = strpos( $part_content, '<!--pagetitle:' );
if( $has_part_title ) {
$tagEnd = strpos( $part_content, '-->' );
$title = trim( str_replace( '<!--pagetitle:', '', substr( $part_content, 0, $tagEnd ) ) );
}
$output .= ' ';
// Generate a link to the $pageNumber -- Will not generate link for the current page
if ( ($pageNumber != $page) || ((!$more) && ($page==1)) ) {
$output .= _wp_link_page($pageNumber); // Page number is correct here - the link generated is accurate
}
echo 'Page Number: '.$pageNumber.' -- Link Generated <br /> '; // This is a test to check the value of $pageNumber. Value prints as expected
// If the pagetitle is present, use it. If not, pring 'Page [$pageNumber]'
$title = isset( $title ) && ( strlen( $title ) > 0 ) ? $title : 'Page '.$pageNumber;
$output .= $link_before . $title . $link_after;
echo 'Page Number Again: '.$pageNumber.' -- Title Generated <br> '; // This is a test to check the value of $pageNumber. Value prints as expected
// Close the generated link -- will not execute when $pageNumber == the current page
if ( ($pageNumber != $page) || ((!$more) && ($page==1)) ) {
$output .= '</a>';
}
}
// Close the "list"
$output .= $after;
}
/* Worth noting: Links are added to a single output string and printed in one go after the foreach executes.
Seems like it would be better to print each link individually */
if ( $echo )
echo $output; // When $output prints, the link text for every page is 'Page 1' for some reason, the page number here is not displayed correctly
return $output;
为什么echo $pageNumber; 打印正确的值,而'Page '.$pageNumber 只打印每个链接的“第 1 页”?
我确定我遗漏了一些明显的东西,但我无法确定它是什么。非常感谢任何帮助。
【问题讨论】:
-
为什么在脚本末尾有
if ($echo)? -
打印出
$ndx我敢打赌每次都是0。相反,只需跟踪$pageNumber并在每次迭代时增加它 -
@Floris 这是我从其他地方提取的函数。我相信 $echo 与 WordPress wp_link_pages() 函数相关联,这是为了增强。用于打印链接或返回变量的布尔开关。
-
@ElefantPhace 绝对不是每次都为 0。生成的 href 属性是正确的,并且依赖于相同的变量。此外,正如注释代码中所述,我在相关行之前和之后打印了变量作为测试,并确认该值是正确的。问题与 isset() 调用有关。 --见 Mark Dunphy 的遮阳篷。