Finales felices (con revisión) y apadrinamiento, preparados y ocultos

- Formulario [ga_final_feliz]: las familias envían texto y foto (solo imágenes reales ≤5 MB,
  límite de envíos, consentimiento de publicación). Queda pendiente hasta que el equipo
  la publica; aviso por correo y contador en el menú.
- Sección «Finales felices»: historias aprobadas o, si no hay, los adoptados.
- Casilla «Busca padrino o madrina», sección «Apadrina» y motivo de contacto (sin pagos).
- Páginas «Finales felices / Amaiera zoriontsuak» creadas como borrador.
- API: profile.sponsorable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-25 10:30:53 +02:00
parent fac5e6035c
commit 1ad21c1b08
12 changed files with 293 additions and 23 deletions

View File

@@ -103,6 +103,7 @@ function ga_fields() {
'adoptado' => ga__( 'Adoptado', 'Adoptatuta' ),
), 'help' => 'Los adoptados salen solos del listado.' ),
'destacado' => array( 'shared' => true, 'label' => ga__( 'Destacado', 'Nabarmendua' ), 'type' => 'checkbox', 'help' => 'Aparece en la portada. Útil para quien lleva más tiempo esperando o necesita un hogar especial.' ),
'apadrinable' => array( 'shared' => true, 'label' => ga__( 'Busca padrino o madrina', 'Aitabitxi edo amabitxi bila' ), 'type' => 'checkbox', 'help' => 'Aparece en la sección «Apadrina» (si está activada en Personalizar).' ),
'sexo' => array( 'shared' => true, 'label' => ga__( 'Sexo', 'Sexua' ), 'type' => 'select', 'options' => array(
'macho' => ga__( 'Macho', 'Arra' ),
'hembra' => ga__( 'Hembra', 'Emea' ),
@@ -434,7 +435,7 @@ add_action( 'pre_get_posts', function ( $q ) {
* @param array $args numero, especie (slugs), estado (lista o 'adoptado'), destacados (bool).
*/
function ga_query_animals( $args = array() ) {
$args = wp_parse_args( $args, array( 'numero' => 6, 'especie' => '', 'estado' => '', 'destacados' => false ) );
$args = wp_parse_args( $args, array( 'numero' => 6, 'especie' => '', 'estado' => '', 'destacados' => false, 'apadrinables' => false ) );
$query = array(
'post_type' => 'animal',
'posts_per_page' => (int) $args['numero'],
@@ -457,6 +458,9 @@ function ga_query_animals( $args = array() ) {
if ( $args['destacados'] ) {
$meta[] = array( 'key' => '_ga_destacado', 'value' => '1' );
}
if ( $args['apadrinables'] ) {
$meta[] = array( 'key' => '_ga_apadrinable', 'value' => '1' );
}
$query['meta_query'] = $meta;
$q = new WP_Query( $query );
@@ -472,8 +476,10 @@ function ga_query_animals( $args = array() ) {
/* [ga_animales numero="6" especie="perro" destacados="1" vista="carrusel"] */
add_shortcode( 'ga_animales', function ( $atts ) {
$atts = shortcode_atts( array( 'numero' => 6, 'especie' => '', 'estado' => '', 'destacados' => '', 'vista' => 'rejilla' ), $atts, 'ga_animales' );
$atts['destacados'] = in_array( $atts['destacados'], array( '1', 'si', 'true' ), true );
$atts = shortcode_atts( array( 'numero' => 6, 'especie' => '', 'estado' => '', 'destacados' => '', 'apadrinables' => '', 'vista' => 'rejilla' ), $atts, 'ga_animales' );
foreach ( array( 'destacados', 'apadrinables' ) as $flag ) {
$atts[ $flag ] = in_array( $atts[ $flag ], array( '1', 'si', 'true' ), true );
}
$q = ga_query_animals( $atts );
ob_start();
if ( $q->have_posts() ) {

View File

@@ -40,6 +40,7 @@ function ga_api_map() {
return array(
'status' => 'estado',
'featured' => 'destacado',
'sponsorable' => 'apadrinable',
'sex' => 'sexo',
'birthDate' => 'nacimiento',
'age' => 'edad',
@@ -73,6 +74,7 @@ function ga_animal_api_data( $post_id ) {
$data = array(
'status' => ga_api_to( 'estado', ga_status( $post_id ) ),
'featured' => (bool) ga_get( $post_id, 'destacado' ),
'sponsorable' => (bool) ga_get( $post_id, 'apadrinable' ),
'sex' => ga_api_to( 'sexo', ga_get( $post_id, 'sexo' ) ),
'birthDate' => $text( 'nacimiento' ),
'age' => '' === ga_get( $post_id, 'edad' ) ? null : (float) ga_get( $post_id, 'edad' ),
@@ -116,6 +118,7 @@ function ga_animal_api_update( array $profile, $post_id ) {
}
break;
case 'featured':
case 'sponsorable':
$value = $raw ? '1' : '';
break;
case 'age':
@@ -157,6 +160,7 @@ function ga_animal_api_schema() {
'properties' => array(
'status' => array( 'type' => 'string', 'enum' => array_values( ga_api_enums()['estado'] ), 'description' => 'Adopted animals are hidden from public listings.' ),
'featured' => array( 'type' => 'boolean', 'description' => 'Shown on the home page.' ),
'sponsorable' => array( 'type' => 'boolean', 'description' => 'Looking for a sponsor.' ),
'sex' => $enum( 'sexo' ),
'birthDate' => $string_or_null + array( 'format' => 'date' ),
'age' => array( 'type' => array( 'number', 'null' ), 'description' => 'Approximate age, used when birthDate is unknown.' ),
@@ -211,6 +215,7 @@ add_action( 'graphql_register_types', function () {
'fields' => array(
'status' => array( 'type' => 'AnimalStatusEnum' ),
'featured' => array( 'type' => 'Boolean' ),
'sponsorable' => array( 'type' => 'Boolean' ),
'sex' => array( 'type' => 'AnimalSexEnum' ),
'birthDate' => array( 'type' => 'String' ),
'age' => array( 'type' => 'Float' ),

View File

@@ -13,6 +13,7 @@ function ga_contact_reasons() {
'acogida' => ga__( 'Casa de acogida', 'Harrera-etxea' ),
'voluntario' => ga__( 'Voluntariado', 'Boluntariotza' ),
'material' => ga__( 'Ayuda material', 'Laguntza materiala' ),
'apadrinar' => ga__( 'Apadrinamiento', 'Apadrinatzea' ),
'otro' => ga__( 'Otro', 'Beste bat' ),
);
}

View File

@@ -0,0 +1,175 @@
<?php
/**
* Finales felices (historias enviadas por las familias, con revisión) y apadrinamiento.
*/
defined( 'ABSPATH' ) || exit;
/* -------------------------------------------------------------------------
* Historias: tipo de contenido
* ---------------------------------------------------------------------- */
add_action( 'init', function () {
register_post_type( 'ga_historia', array(
'labels' => array(
'name' => 'Finales felices',
'singular_name' => 'Final feliz',
'add_new_item' => 'Añadir final feliz',
'edit_item' => 'Revisar final feliz',
'all_items' => 'Finales felices',
'not_found' => 'Aún no hay historias',
'featured_image' => 'Foto',
),
'public' => false,
'show_ui' => true,
'show_in_menu' => 'edit.php?post_type=animal',
'supports' => array( 'title', 'editor', 'thumbnail' ),
'map_meta_cap' => true,
) );
} );
/* Contador de historias pendientes en el menú */
add_action( 'admin_menu', function () {
global $submenu;
$pending = (int) wp_count_posts( 'ga_historia' )->pending;
foreach ( $submenu['edit.php?post_type=animal'] ?? array() as $i => $item ) {
if ( 'edit.php?post_type=ga_historia' === $item[2] && $pending ) {
$submenu['edit.php?post_type=animal'][ $i ][0] .= ' <span class="awaiting-mod">' . $pending . '</span>';
}
}
}, 99 );
/** Historias publicadas en el idioma actual (o en cualquiera si no hay). */
function ga_query_stories( $number = 6 ) {
return new WP_Query( array(
'post_type' => 'ga_historia',
'post_status' => 'publish',
'posts_per_page' => $number,
'no_found_rows' => true,
) );
}
/* -------------------------------------------------------------------------
* [ga_final_feliz] formulario para que las familias envíen su historia
* ---------------------------------------------------------------------- */
add_shortcode( 'ga_final_feliz', function () {
$status = sanitize_key( $_GET['historia'] ?? '' );
$privacy = ga_page_url( 'politica-de-privacidad' );
ob_start();
if ( 'ok' === $status ) {
echo '<div class="ga-notice ga-notice--ok" role="status">' . esc_html( ga__( '¡Gracias por compartirlo! Lo revisaremos antes de publicarlo.', 'Eskerrik asko partekatzeagatik! Argitaratu aurretik berrikusiko dugu.' ) ) . '</div>';
return ob_get_clean();
}
if ( 'error' === $status ) {
echo '<div class="ga-notice ga-notice--error" role="alert">' . esc_html( ga__( 'No hemos podido enviarlo. Revisa los campos y que la foto sea JPG, PNG o WebP de menos de 5 MB.', 'Ezin izan dugu bidali. Egiaztatu eremuak eta argazkia JPG, PNG edo WebP dela eta 5 MB baino gutxiago dituela.' ) ) . '</div>';
}
?>
<form class="ga-form" method="post" enctype="multipart/form-data" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
<input type="hidden" name="action" value="ga_final_feliz">
<input type="hidden" name="redirect" value="<?php echo esc_url( get_permalink() ); ?>">
<input type="hidden" name="idioma" value="<?php echo esc_attr( ga_lang() ); ?>">
<?php wp_nonce_field( 'ga_final_feliz', 'ga_nonce' ); ?>
<div class="ga-hp" aria-hidden="true"><label>No rellenar <input type="text" name="web" tabindex="-1" autocomplete="off"></label></div>
<div class="ga-form__row">
<label><?php ga_e( 'Nombre del animal', 'Animaliaren izena' ); ?> *<input type="text" name="animal" required maxlength="80"></label>
<label><?php ga_e( 'Vuestro nombre', 'Zuen izena' ); ?> *<input type="text" name="familia" required maxlength="80"></label>
</div>
<label><?php ga_e( 'Correo electrónico (no se publica)', 'Posta elektronikoa (ez da argitaratzen)' ); ?> *<input type="email" name="email" required></label>
<label><?php ga_e( '¿Cómo está ahora?', 'Nola dago orain?' ); ?> *<textarea name="texto" rows="5" required maxlength="800"></textarea></label>
<label><?php ga_e( 'Una foto (JPG, PNG o WebP, máx. 5 MB)', 'Argazki bat (JPG, PNG edo WebP, gehienez 5 MB)' ); ?><input type="file" name="foto" accept="image/jpeg,image/png,image/webp"></label>
<label class="ga-form__check"><input type="checkbox" name="publicar" value="1" required>
<span><?php ga_e( 'Autorizo a Bilagun a publicar este texto y la foto en su web y redes. *', 'Bilaguni baimena ematen diot testu hau eta argazkia bere webgunean eta sareetan argitaratzeko. *' ); ?></span></label>
<label class="ga-form__check"><input type="checkbox" name="privacidad" value="1" required>
<span><?php
printf(
wp_kses( ga__( 'He leído y acepto la <a href="%s" target="_blank">política de privacidad</a>. *', '<a href="%s" target="_blank">Pribatutasun-politika</a> irakurri eta onartzen dut. *' ), array( 'a' => array( 'href' => array(), 'target' => array() ) ) ),
esc_url( $privacy )
);
?></span></label>
<button type="submit" class="ga-btn"><?php ga_e( 'Enviar nuestra historia', 'Gure istorioa bidali' ); ?></button>
</form>
<?php
return ob_get_clean();
} );
add_action( 'admin_post_nopriv_ga_final_feliz', 'ga_handle_story' );
add_action( 'admin_post_ga_final_feliz', 'ga_handle_story' );
function ga_handle_story() {
$redirect = wp_validate_redirect( esc_url_raw( wp_unslash( $_POST['redirect'] ?? '' ) ), home_url( '/' ) );
$go = function ( $status ) use ( $redirect ) {
wp_safe_redirect( add_query_arg( 'historia', $status, $redirect ) . '#historia' );
exit;
};
if ( ! isset( $_POST['ga_nonce'] ) || ! wp_verify_nonce( $_POST['ga_nonce'], 'ga_final_feliz' ) ) {
$go( 'error' );
}
if ( ! empty( $_POST['web'] ) ) {
$go( 'ok' );
}
// Límite sencillo: 3 envíos por hora y dirección IP.
$key = 'ga_story_' . md5( $_SERVER['REMOTE_ADDR'] ?? '' );
$count = (int) get_transient( $key );
if ( $count >= 3 ) {
$go( 'error' );
}
set_transient( $key, $count + 1, HOUR_IN_SECONDS );
$animal = sanitize_text_field( wp_unslash( $_POST['animal'] ?? '' ) );
$familia = sanitize_text_field( wp_unslash( $_POST['familia'] ?? '' ) );
$email = sanitize_email( wp_unslash( $_POST['email'] ?? '' ) );
$texto = mb_substr( sanitize_textarea_field( wp_unslash( $_POST['texto'] ?? '' ) ), 0, 800 );
if ( ! $animal || ! $familia || ! is_email( $email ) || ! $texto || empty( $_POST['publicar'] ) || empty( $_POST['privacidad'] ) ) {
$go( 'error' );
}
$story_id = wp_insert_post( array(
'post_type' => 'ga_historia',
'post_status' => 'pending',
'post_title' => $animal,
'post_content' => $texto,
) );
if ( ! $story_id || is_wp_error( $story_id ) ) {
$go( 'error' );
}
update_post_meta( $story_id, '_ga_familia', $familia );
update_post_meta( $story_id, '_ga_email', $email );
update_post_meta( $story_id, '_ga_idioma', 'eu' === ( $_POST['idioma'] ?? '' ) ? 'eu' : 'es' );
// Foto: solo imágenes reales de hasta 5 MB.
if ( ! empty( $_FILES['foto']['tmp_name'] ) && UPLOAD_ERR_OK === $_FILES['foto']['error'] ) {
$file = $_FILES['foto'];
$check = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'], array( 'jpg|jpeg' => 'image/jpeg', 'png' => 'image/png', 'webp' => 'image/webp' ) );
if ( $file['size'] > 5 * MB_IN_BYTES || ! $check['type'] || ! @getimagesize( $file['tmp_name'] ) ) {
wp_delete_post( $story_id, true );
$go( 'error' );
}
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
$attachment = media_handle_upload( 'foto', $story_id, array(), array( 'test_form' => false, 'mimes' => array( 'jpg|jpeg' => 'image/jpeg', 'png' => 'image/png', 'webp' => 'image/webp' ) ) );
if ( ! is_wp_error( $attachment ) ) {
set_post_thumbnail( $story_id, $attachment );
}
}
wp_mail(
ga_contact_email(),
'[Web] Nuevo final feliz por revisar: ' . $animal,
sprintf( "%s ha enviado la historia de %s.\n\nRevísala y publícala aquí: %s", $familia, $animal, admin_url( 'post.php?action=edit&post=' . $story_id ) )
);
$go( 'ok' );
}
/* En el panel: quién la envió (sin publicar su correo) */
add_action( 'add_meta_boxes_ga_historia', function () {
add_meta_box( 'ga_historia_info', 'Enviada por', function ( $post ) {
printf(
'<p><strong>%s</strong><br>%s<br>Idioma: %s</p><p class="description">Para publicarla pulsa «Publicar». El nombre de la familia se muestra; el correo no.</p>',
esc_html( get_post_meta( $post->ID, '_ga_familia', true ) ?: '—' ),
esc_html( get_post_meta( $post->ID, '_ga_email', true ) ?: '' ),
esc_html( get_post_meta( $post->ID, '_ga_idioma', true ) ?: 'es' )
);
}, 'ga_historia', 'side' );
} );