0
I’m having a hard time getting the code to run.
I have the variable $posts_metas
which may be empty or have an array, depending on what the user has already registered in DB.
I also have the variable $uls
that contains urls of the images the user selected.
I’m trying to do some checks before saving in DB, see comments on the code below:
add_action( 'save_post', function ($post_id) {
if (isset($_POST['my_image_URL'])){ //se existem imagens selecionadas
$urls = $_POST['my_image_URL']; // variavel urls recebe as urls das imagens
$posts_metas = get_post_meta( $post_id, 'my-image-for-post' ); // busca no DB posts metas onde a coluna meta_key sejam = "my-image-for-post" e retorna as urls
if ($posts_metas === ''){ //se posts metas retornou vazio
foreach ($urls as $url){
add_post_meta( $post_id, 'my-image-for-post',$url ); // apenas cadastra todas urls... ate aqui quando o DB esta vazio cadastra corretamente as urls
}
}
}else{
foreach ($urls as $url){
foreach( $posts_metas as $value ) {
if($value != $url){
add_post_meta( $post_id, 'my-image-for-post',$url );
}elseif($value === $url ){
update_post_meta( $post_id, 'my-image-for-post', $url );
}else{
add_post_meta( $post_id, 'my-image-for-post',$url );
}
}
}
}
});
In the else
if there is already a meta_key for the post with the value 'my-image-for-post' then have some url registered.
I am trying to perform the following 2 conditions:
1ª if all registered values are different from the new url or if the url does not exist in the DB should add the url.
2nd if the value of the url is identical to an already registered url you should only update
It turns out that after the else
, I’m not getting the foreach and loop right
I appreciate help
Have you thought about changing the logic? In these cases it is better to delete everything and insert only what was passed. If you validate the case of the house, the cyclomatic complexity increases too much. If you perform the process linearly, it is very simple.
– Gabriel Heming
it was the same exit, I redid everything, I just left
delete_post_meta
andadd_post_meta
in the action and the rest I did with jquery. Thanks @Gabrielheming– Gislef