У меня ID
из GET
, и я проверяю, находится ли ID
в custom field
, и, если это так, поместите кнопку удаления , иначе выведите add button
custom field
получает string
каждый раз, когда мы отправляем значение, но для его удаления я использую unset
в массиве, проверяя, есть ли current ID
или нет.
Смущаюсь, когда я смешиваю implode
и explode
Весь код:
$postId = $_GET['postId'];
$allposts = '';
$user_id = get_current_user_id();
$userPosts = get_user_meta( $user_id, 'save_post', TRUE );
$userPosts = explode(',', $userPosts);
$response = wp_remote_get('https://example.com/wp-json/wp/v2/posts?include='.$postId);
if ( is_wp_error( $response ) ) {
return;
}
$posts = json_decode( wp_remote_retrieve_body( $response ) );
if ( empty( $posts ) ) {
return;
}
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (isset($_POST['save_post'])) {
array_push($userPosts, $postId);
$userPosts = array_values(array_unique($userPosts));
$userPosts = implode(',', $userPosts);
$userPosts = trim($userPosts);
$userPosts = ltrim($userPosts, ",");
update_user_meta( $user_id, 'save_post', $userPosts );
}
if (isset($_POST['remove_post'])) {
if (($key = array_search($postId, $userPosts)) !== false) {
unset($userPosts[$key]);
}
$userPosts = implode(',', $userPosts);
$userPosts = trim($userPosts);
$userPosts = ltrim($userPosts, ",");
update_user_meta( $user_id, 'save_post', $userPosts );
}
}
if ( ! empty( $posts ) ) {
// For each post.
foreach ( $posts as $post ) {
$allposts .= '<a href="' . esc_url( $post->link ) . '" target=\"_blank\">' . esc_html( $post->title->rendered ) . '</a> ' . esc_html( $fordate ) . '<br />'.$post->content->rendered;
?>
<div class="container margin-top-80 margin-bottom-80">
<div class="row">
<div class="col-8">
<form id="savedPosts" action="" method="POST" class="" autocomplete="off">
<input type="hidden" name="save_post" value="<?php echo $postId; ?>">
<?php
$userPosts = implode(',', $userPosts);
if (strpos($userPosts, $postId) !== false) { ?>
<button disabled="disabled" type="submit" class="save_post disabled btn btn-outline-dark" data-toggle="tooltip" data-placement="top" title="già nei tuoi favoriti">Già nella box</button>
<button id="remove_post" name="remove_post" type="submit" class="save_post" data-toggle="tooltip" data-placement="top" title="aggiungilo alla tua box">Rimuovi dalla box</button>
<?php } else {
?>
<button id="save_post" name="save_post" type="submit" class="save_post" data-toggle="tooltip" data-placement="top" title="aggiungilo alla tua box">Salva nella box</button>
<?php }
?>
</form>
</div>
</div>
</div>
<?php }
}
?>