What you are trying to accomplish here is will not work just but calling the function make_sticky
on a link because this function doesn’t actually print anything for the final user to take an action. What will happen here is that every post in the loop will get set as sticky
every time that method is called.
So to resolve your issue you want to create a page within your WordPress administration and then create a page template inside your theme and assign it to that page.
For the sake of an explanation I will say that you called this page make-sticky
, now you will access this page by creating a link like this:
<?php echo add_query_arg( array( '_post', get_the_ID() ), get_permalink( get_page_by_path( 'make-sticky' ) ) );
This will output http://yoursite.com/make-sticky/?_post=130
.
The template file has to contain only the template metadata section:
<?php
/*
* Template Name: Make Sticky
* Description: This page will make the Post Sticky
*/
After that you will add the following lines on your functions.php
:
<?php
function q166504_make_sticky_redirect(){
// If we are not on that page template just leave
if ( ! is_page_template( 'template-make-sticky.php' ) ){
return;
}
// If the _post _GET param doesnt exist leave
if ( empty( $_GET['_post'] ) ){
exit( wp_redirect( home_url() ) );
}
$post_id = absint( $_GET['_post'] );
// If the user doesn't have permission leave
if ( ! current_user_can( 'edit_others_posts' ) ){
exit( wp_redirect( get_permalink( $post_id ) ) );
}
// Safe to execute the action
$is_sticky = (bool) get_post_meta( $post_id, 'sticky', 0 );
// Make the toggle
update_post_meta( $post_id, 'sticky', ! $is_sticky );
// Now redirect back to the post
exit( wp_redirect( get_permalink( $post_id ) ) );
}
add_action( 'template_redirect', 'q166504_make_sticky_redirect' );
This method will intercept the template of WordPress then redirect the user to edited post, if the user doesn’t have permission or something is wrong it will redirect to the home.