Last active
November 19, 2017 00:14
-
-
Save bappi-d-great/88302389c26a60075787 to your computer and use it in GitHub Desktop.
Show posts based on user preference in wordpress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action( 'show_user_profile', 'extra_fields' ); | |
add_action( 'edit_user_profile', 'extra_fields' ); | |
add_action( 'personal_options_update', 'save_fields' ); | |
add_action( 'edit_user_profile_update', 'save_fields' ); | |
add_action( 'pre_get_posts', 'exclude_category' ); | |
function extra_fields($user) { | |
$pref_cat = explode( ',', get_user_meta( $user->ID, 'pref_cat', true ) ); | |
?> | |
<h3><?php _e("Extra profile information", "DOMAIN"); /*DOMAIN = Lang domain for l10n (optional)*/ ?></h3> | |
<table class="form-table"> | |
<tbody> | |
<tr> | |
<th><?php _e("Your preferred categories", "DOMAIN"); /*DOMAIN = Lang domain for l10n (optional)*/ ?></th> | |
<td> | |
<?php | |
$categories = get_categories( array( 'type' => 'post' ) ); | |
foreach( $categories as $cat ){ | |
?> | |
<label><input <?php echo in_array( $cat->term_id, $pref_cat ) ? 'checked' : '' ?> type="checkbox" name="pref_cat[]" value="<?php echo $cat->term_id ?>"> <?php echo $cat->name ?></label> | |
<?php | |
} | |
?> | |
</select> | |
</tr> | |
</tbody> | |
</table> | |
<?php | |
} | |
function save_fields( $user_id ) { | |
if ( !current_user_can( 'edit_user', $user_id ) ) { return false; } //Checking if the current user has ability to edit the user profile information | |
update_user_meta( $user_id, 'pref_cat', implode( ',', $_POST['pref_cat'] ) ); | |
} | |
function exclude_category( $query ) { | |
if( is_user_logged_in() ) { | |
$current_user = wp_get_current_user(); | |
if ( $query->is_home() && $query->is_main_query() ) { | |
$query->set( 'cat', get_user_meta( $current_user->ID, 'pref_cat', true ) ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment