Mic*_*ski 3 php wordpress function shortcode
嘿伙计们,我在编写主题短代码时遇到了一些麻烦.我希望代码显示带有视图计数器功能的div,然后是带有shotcodes内容的链接作为url.
view_count(); 函数在主题文件中调用时工作正常,我实际上设法让它显示,但然后它显示在the_content()之前; 帖子(灰色条),当我想要它在元素下的内容中时.
(1)这是我得到的:
function video_block( $atts, $content = null ) {
return '<div class="video-block"><span class="ViewCount"><?php the_views(); ?></span> <a class="dl-source" href="' . $content . '">Link</a></div>';
}
Run Code Online (Sandbox Code Playgroud)
(2)这是在页面顶部显示的代码:
function video_block( $atts, $content = null ) { ?>
<div class="video-block"><span class="ViewCount"><?php the_views(); ?></span> <a class="dl-source" href="<?php echo $content; ?>">Link</a></div>
<?php }
Run Code Online (Sandbox Code Playgroud)
(3)此代码显示上面的内容视图,以及正确位置的链接:
function video_block( $atts, $content = null ) {
$views = the_views();
return '<div class="video-block"><span class="ViewCount"><?php $views; ?></span> <a class="dl-source" href="<?php echo $content; ?>">Link</a></div>';
}
Run Code Online (Sandbox Code Playgroud)
我在Wordpress论坛的某个地方读到你应该在函数中返回(而不是echo)值,但这会破坏它,显示视图计数,跳过html并吐出$ content.
以下是相关页面的链接:http://nvrt.me/4Qf1(目前使用块#2中的代码)
我的午夜油耗尽了.如果有人可以帮助我,我真的很感激.
编辑:
这是the_views()的代码; 功能.我可以看到它已经回显,但是当更改为返回时,它根本不会显示它.
### Function: Display The Post Views
function the_views($display = true, $prefix = '', $postfix = '', $always = false) {
$post_views = intval(post_custom('views'));
$views_options = get_option('views_options');
if ($always || should_views_be_displayed($views_options)) {
$output = $prefix.str_replace('%VIEW_COUNT%', number_format_i18n($post_views), $views_options['template']).$postfix;
if($display) {
echo apply_filters('the_views', $output);
} else {
return apply_filters('the_views', $output);
}
}
elseif (!$display) {
return '';
}
}
Run Code Online (Sandbox Code Playgroud)
尽管在Wordpress中建议使用返回值的函数,但并不总是可行,尤其是在调用将其输出直接写入流的另一个函数时.
当组件将其输出直接写入流时,您需要编码以适应该行为,除非您想要重写who组件(我不会这样做;-)).
在这个例子中,the_views()函数实际上为您提供了两个选项.如果您查看$ display参数并按照代码执行此功能,则可以采用两种方式.如果$ display设置为True(默认值),它将回显函数的结果.如果$ display设置为False,它将返回输出.
所以你有两个选择,两个都应该有效:
选项1,返回一个值
请注意,当我调用the_views()时,我传递了一个假参数,如下所示:the_views(false)
<?php
function video_block( $atts, $content = null ) {
return "<div class=\"video-block\"><span class=\"ViewCount\">" . the_views(false) . "</span><a class=\"dl-source\" href=\"$content\">Link</a></div>";
}
?>
Run Code Online (Sandbox Code Playgroud)
*选项2:回应您的输出*
请注意,当我调用the_views()时,没有传递给它的参数.
<?php
function video_block( $atts, $content = null ) {
echo "<div class=\"video-block\"><span class=\"ViewCount\">";
the_views();
echo "</span><a class=\"dl-source\" href=\"$content\">Link</a></div>";
}
?>
Run Code Online (Sandbox Code Playgroud)
哦,另外,当你返回一个字符串时,别忘了逃避引号.