0

I have added function to functions.php so authors can search only their published content. I would like to add additional "Search my posts" button to searchform.php so only logged in users would see - have this button for searching posts they published. But I can get it to work. :(

When I click on any button "Search All posts" or "Search My Posts" when logged in it searches only logged in author.

function search_author($query) {
  if ($query->is_search) {
        $query->set('author', get_current_user_id());
  }
  return $query;
}
add_filter('pre_get_posts','search_author');

searchform.php

<?php if ( is_user_logged_in() ) { ?>
<form action="<?php echo home_url(); ?>/" method="get" id="searchform">
    <fieldset>
        <div id="searchbox">
            <input class="input" name="s" type="text" id="keywords" value="<?php _e('Search input','mytheme') ?>" onfocus="if (this.value == '<?php _e('Search input','mytheme') ?>') {this.value = '';}" onblur="if (this.value == '') {this.value = '<?php _e('Search input','mytheme') ?>';}">
                </div>
                <div id="searchbutton1">
                <p class="button search">
            <input type="submit" name="search" value="<?php _e('Search All Posts','mytheme') ?> ">
                </p>
                </div>
                <div id="searchbutton2">
                <p class="button search">
            <input type="submit" name="author" value="<?php _e('Search My Posts','mytheme') ?> ">
                </p>
                </div>
        </fieldset>
</form>
<?php } else { ?>
<form action="<?php echo home_url(); ?>/" method="get" id="searchform">
    <fieldset>
        <div id="searchbox2">
            <input class="input" name="s" type="text" id="keywords" value="<?php _e('Search input','mytheme') ?>" onfocus="if (this.value == '<?php _e('Search input','mytheme') ?>') {this.value = '';}" onblur="if (this.value == '') {this.value = '<?php _e('Search input','mytheme') ?>';}">
                </div>
                <p class="button search2">
            <input type="submit" name="search" value="<?php _e('Search','mytheme') ?> ">
                </p>
        </fieldset>
</form>
<?php } ?>

Thank you for any suggestions.

1

You might have to check which button was clicked by user, weather it is search all post or search my post, based on that you can apply filter. Try this..

function search_author($query) {
  if($query->is_search) 
  {
    if($query->query_vars['author']=='Search My Posts') 
    {
        $query->set('author', get_current_user_id());
    }
  }
  return $query;
}
add_filter('pre_get_posts','search_author');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.