0
votes

I need to add 'function' and 'add_action' in a single post page.
I created the following code in functions.php, then added the shortcode [test-query] in the single post page.
But, it even doesn't display the value of the echo.
Would you please let me know how to add 'function' and 'add_action' in the single post page?

Code I tried:

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' );



Thank you.

1
That code is weird, I'm not sure what you want to achieve. Also I think you may get a PHP fatal error for re-declaring the inner function, if you call test_query() function twice. I'm not sure if that's a good way - Adriana Hernández
@AdrianaHernández: Thank you for your comments. I'm a newbie, I just tried what I could do, then it didn't work as you said. function() and add_action() works when I put them in functions.php, but I can't echo them. So, I want to put the entire code in the single post page, so that I can echo and check values. - isbe

1 Answers

0
votes

You can use the wordpress function 'is_singular()' or 'is_page("Post ID|title|slug")' to check if you are in single post page. E.g

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

Remember to always return from your shortcode function callback. So your solution should be:

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' ));
}

To know more about the parameters in the 'test_query', what they do and how to handle them, check the wp plugin handbook doc on shortcodes https://developer.wordpress.org/plugins/shortcodes/shortcodes-with-parameters/

Happy debugging :)