将函数调用到sprintf()的一些问题

时间:2013-03-25 17:51:55

标签: php wordpress-theming printf wordpress

我是PHP和WordPress的新手,我正在个性化现有的模板,我遇到以下问题。

在模板的 function.php 文件中,我有以下功能:

function admired_posted_on() {
    printf( __( '<span class="sep">Posted on </span>
                 <a href="%1$s" title="%2$s" rel="bookmark">
                    <time class="entry-date" datetime="%3$s" pubdate>%4$s</time>
                 </a>
                 <span>%5$s</span>
                 <span class="by-author"> 
                    <span class="sep"> by bla</span> 
                    <span class="author vcard">
                        <a class="url fn n" href="%6$s" title="%7$s" rel="author">%8$s</a>
                    </span>
                 </span>
                 ', 'admired' ),

    esc_url( get_permalink() ),
    esc_attr( get_the_time() ),
    esc_attr( get_the_date( 'c' ) ),
    esc_html( get_the_date() ),
    sprintf('Views: ', get_PostViews(get_the_ID())),
    esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ),
    sprintf( esc_attr__( 'View all posts by %s', 'admired' ), get_the_author() ),
    esc_html( get_the_author() )
    );
}

正如您所看到的,此函数会创建一些HTML代码,这些代码将在模板的特定部分(循环内)中打印。

好的,你可以看到这一行:

sprintf('Views: ', get_PostViews(get_the_ID())),

应该打印字符串“Views:”后跟函数get_the_ID()返回的值(表示阅读帖子的人数)

正如您所看到的,此函数是被调用函数列表中的第五个函数,因此应将此值而不是%5 $ s 占位符放入以下span标记中:

<span>%5$s</span>

问题是,我在这个范围内执行我的页面只显示值:视图:但不显示get_PostViews()函数的输出。

如果不是原来的行:

sprintf('Views: ', get_PostViews(get_the_ID())),

我用这一行:

sprintf(get_PostViews(get_the_ID())),

它运作良好,但我无法预先解释说明文字:“观点:”

为什么呢?如何打印“视图”文本后跟get_PostViews函数的返回值?

TNX

安德烈

2 个答案:

答案 0 :(得分:1)

sprintf('Views: %d', get_PostViews(get_the_ID()))

sprintf的第一个参数应该包含以下参数的占位符,“%d”格式告诉sprintf这应该是integer

More about this method here

答案 1 :(得分:0)

正如汉克所提到的,你错过了文本中的占位符。

您也可以这样做,以便您可以在文本中多次使用相同的占位符。

sprintf('Views: %1$d', get_PostViews(get_the_ID()));