• Hello! I have a function in my functions.php file that hooks into publish_post. The thing is, in my function I don’t seem to have access to the pretty version of the permalink, only the ugly version.

    function my_function( $ID, $post ){
       setup_postdata( $post );
       wp_die( "Ugly Link: ".get_permalink() );
       wp_reset_postdata();
    }
    add_action( 'publish_post', 'my_function', 10, 2 );

    This prints out an ugly permalink like http://www.mysite.com/?p=2719 instead of a pretty permalink like http://www.mysite.com/this-is-a-test-post/

    Is it possible to get access to the pretty permalink in the publish_post hook? I basically need my function to run whenever a post is published, and it’s important that I have the pretty permalink. Thanks for any guidance anyone can provide, it’s very much appreciated!

Viewing 5 replies - 1 through 5 (of 5 total)
  • Why are you using this function when WordPress already allows you to use pretty permalinks by going to Settings (in the backend) -> Permalinks?

    Thread Starter Testerossa

    (@testerossa)

    Ah well, the function I’m writing is actually meant to send post content to an external program whenever a post gets published. Part of the content I wanted to send to the external program is the permalink of the published post.

    I do already have the pretty permalinks set up in the backend options, and they work fine throughout the site. It’s just that in this function I’ve been writing, every time I try to access the permalink using get_permalink(), I get the ugly permalink instead of the pretty one, and I’m not sure why/how/if I can actually access it.

    Try this code:

    global $post; // global variable to access any post
    
    function my_function( $post ){
       setup_postdata( $post );
       echo the_permalink(); // echo the permalink as it should be pretty
       wp_reset_postdata();
    }
    add_action( 'publish_post', 'my_function', 10, 2 );

    Then from there you can do whatever is needed to expand on it.

    Thread Starter Testerossa

    (@testerossa)

    Ah, thanks for trying to help, I gave your code a try but I was still getting the same problem as before (it also output the ugly link). However, after quite a bit of tinkering around I finally seem to have figured it out.

    get_permalink(); // Outputs the ugly link
    get_permalink( $post -> ID ); // Outputs the pretty link

    I’m not sure why, but it seems to work. Thanks again for the help, it was much appreciated!

    That makes sense because you want to focus on the single post that is being passed to the function and you would want to use the ID in order to retrieve the permalink from the database using ID as the keyword.

    You are welcome!

Viewing 5 replies - 1 through 5 (of 5 total)

The topic ‘No Pretty Permalink during publish_post hook?’ is closed to new replies.