我有一些代码可以生成所有post
文件。我想把这个下拉列表添加到每个帖子页面的顶部,就在帖子内容之前。
这样做的正确钩/动作是什么?
自定义函数。php:
<?php
function create_post_dropdown($titles){
?>
<div id="article-choice">
<h3>Choose an Article, or browse below</h3>
<select onchange="if (this.value) window.location.href=this.value">
<?php
foreach($titles as $title => $url){
echo "<option value=" . $url . ">" . $title . "</option>";
}
?>
</select>
</div>
<?php
}
add_action(\'__after_header\', \'create_post_dropdown\');
function add_dropdown_to_posts(){
$args = [
\'post_type\' => \'post\',
\'post_status\' => \'publish\',
\'posts_per_page\' => -1
];
$posts = new WP_Query( $args );
$titles = get_post_titles($args);
if (get_post_type() == "post"){
$title = $post->post_title; // get_the_title();
$title = create_post_dropdown($titles) . "<br>" . $title;
}
return $title;
}
add_filter(\'the_content\', \'add_dropdown_to_posts\');
我们的想法是
post
打开/查看页面,此下拉列表(通过
create_post_dropdown
) 将添加在帖子内容之前。
最合适的回答,由SO网友:Antti Koskinen 整理而成
一种方法是使用自定义下拉功能return
自定义html。然后你可以在你的add_dropdown_to_posts
并将返回的内容放入helper变量中。之后,只需在$content
变量the_content 过滤器提供。
像这样,
function my_custom_dropdown_html() {
return \'<html stuff here>\'; // you could put your html also in a variable and then return that.
}
function add_dropdown_html_before_the_content($content) {
$dropdown = my_custom_dropdown_html();
// if statement just to be safe - e.g you change the custom function output to something else than string of html and forget you\'ve used it here
if ( $dropdown && is_string( $dropdown ) ) {
$content = $dropdown . $content; // prepend custom html to content
}
return $content;
}
add_filter( \'the_content\', \'add_dropdown_html_before_the_content\' );