【问题标题】:How to add 'function' and 'add_action' php in a single post page (wordpress)?如何在单个帖子页面(wordpress)中添加“function”和“add_action”php?
【发布时间】:2021-08-26 04:42:14
【问题描述】:

我需要在一个帖子页面中添加“function”和“add_action”。
我在 functions.php 中创建了以下代码,然后在单个帖子页面中添加了短代码 [test-query]。
但是,它甚至不显示回声的值。
请告诉我如何在单个帖子页面中添加“function”和“add_action”?

我试过的代码:

function test_query(){
   function update_post_b( $post_id, $post, $update ){

    if .....
    $posts = get_posts(array( ....
    echo .....

   add_action( 'save_post_infosubmission', 'update_post_b', 10, 3 );
}
add_shortcode( 'test-query', 'test_query' );



谢谢。

【问题讨论】:

  • 那个代码很奇怪,我不确定你想要实现什么。另外我认为,如果您两次调用 test_query() 函数,您可能会在重新声明内部函数时遇到 PHP 致命错误。我不确定这是否是一个好方法
  • @AdrianaHernández:感谢您的 cmets。我是新手,我只是尝试了我能做的,然后它没有像你说的那样工作。 function() 和 add_action() 在我将它们放入 functions.php 时有效,但我无法回显它们。因此,我想将整个代码放在单个帖子页面中,以便我可以回显和检查值。

标签: php wordpress post


【解决方案1】:

您可以使用 wordpress 函数 'is_singular()' 或 'is_page("Post ID|title|slug")' 来检查您是否在单个帖子页面中。 例如

if(is_singular() && is_page("post-title")) {
    // ...
}

请记住始终从您的简码函数回调中返回。 所以你的解决方案应该是:

if(is_singular() && is_page("title")) {
    function test_query($atts, $content = null, $tag){
        function update_post_b( $post_id, $post, $update ){

            if .....
            # perform actions based on $atts
            $posts = get_posts(array( ....
            # Always return :)
            return $post;
        }
        add_action( 'save_post_infosubmission', 'update_post_b', 10, 3 );
    }
    # Shortcodes are hooked into the 'init' action
    add_action('init', add_shortcode( 'test-query', 'test_query' ));
}

要了解有关“test_query”中的参数、它们的作用以及如何处理它们的更多信息,请查看短代码上的 wp 插件手册文档https://developer.wordpress.org/plugins/shortcodes/shortcodes-with-parameters/

调试愉快:)

【讨论】:

  • 您好,感谢您的建议。我在单个帖子中添加了代码,但它仍然没有显示回显的结果。我认为 function () 和 add_action() 在单个帖子页面中不起作用...
猜你喜欢
  • 1970-01-01
  • 2017-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多