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

@@ -15,3 +15,4 @@ require_once __DIR__ . '/gure-ametsa/api.php';
require_once __DIR__ . '/gure-ametsa/admin.php';
require_once __DIR__ . '/gure-ametsa/share.php';
require_once __DIR__ . '/gure-ametsa/seo.php';
require_once __DIR__ . '/gure-ametsa/stories.php';

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' );
} );

View File

@@ -409,11 +409,26 @@ function ga_customizer_registry() {
'eyebrow' => $t( 'Antetítulo', 'Ya están en casa', 'Etxean daude jada' ),
'title' => $t( 'Título', 'Finales felices', 'Amaiera zoriontsuak' ),
'text' => $t( 'Texto', 'Gracias por formar parte de sus segundas oportunidades.', 'Eskerrik asko haien bigarren aukeren parte izateagatik.', 'textarea' ),
'count' => array( 'type' => 'number', 'label' => 'Número de animales', 'default' => 8, 'min' => 1, 'max' => 24 ),
'count' => array( 'type' => 'number', 'label' => 'Número de historias o animales', 'default' => 8, 'min' => 1, 'max' => 24 ),
'view' => array( 'type' => 'select', 'label' => 'Presentación', 'default' => 'carrusel', 'choices' => array(
'carrusel' => 'Carrusel (se desliza)',
'rejilla' => 'Rejilla',
) ),
'button' => $t( 'Botón para enviar historias (vacío = ocultar)', 'Cuéntanos vuestra historia', 'Kontaiguzu zuen istorioa' ),
),
),
'sponsor' => array(
'panel' => 'ga_home',
'title' => 'Apadrina',
'section' => true,
'hidden' => true,
'description' => 'Muestra los animales marcados como «Busca padrino o madrina».',
'fields' => array(
'eyebrow' => $t( 'Antetítulo', 'Apadrina', 'Apadrinatu' ),
'title' => $t( 'Título', 'Acompáñales *mientras esperan*', 'Lagun egiozu *itxaroten duten bitartean*' ),
'text' => $t( 'Texto', 'Algunos llevan mucho tiempo con nosotras. Si no puedes adoptar, puedes apadrinar a uno de ellos. Escríbenos y te contamos cómo.', 'Batzuk denbora luzea daramate gurekin. Ezin baduzu adoptatu, haietako bat apadrinatu dezakezu. Idatzi iezaguzu eta nola kontatuko dizugu.', 'textarea' ),
'button' => $t( 'Botón', 'Quiero apadrinar', 'Apadrinatu nahi dut' ),
'count' => array( 'type' => 'number', 'label' => 'Número de animales', 'default' => 4, 'min' => 1, 'max' => 12 ),
),
),
'intake' => array(

View File

@@ -550,6 +550,15 @@ body { overflow-x: clip; }
.ga-animal__photo { position: static; }
}
/* Finales felices */
.ga-story { display: flex; flex-direction: column; background: #fff; border: 1px solid var(--ga-line); border-radius: var(--ga-radius); overflow: hidden; }
.ga-story__img { aspect-ratio: 4/3; background: var(--ga-green-soft); }
.ga-story__img img { width: 100%; height: 100%; object-fit: cover; }
.ga-story__body { margin: 0; padding: 18px 20px 20px; font-size: .98rem; flex: 1; display: flex; flex-direction: column; }
.ga-story__body p::before { content: "“"; font: 800 2rem/0 var(--ga-serif); color: var(--ga-red); vertical-align: -.35em; margin-right: 2px; }
.ga-story__body footer { margin-top: auto; padding-top: 10px; border-top: 1px solid var(--ga-line); color: var(--ga-muted); font-size: .9rem; }
.ga-story__body footer strong { font-family: var(--ga-serif); color: var(--ga-green-dark); }
/* Pestañas Perros / Gatos */
.ga-tabs { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 28px; }
.ga-tab { padding: 11px 26px; border-radius: 999px; border: 2px solid var(--ga-green); color: var(--ga-green); font-weight: 700; text-decoration: none; font-size: 1.05rem; }

View File

@@ -0,0 +1,15 @@
<?php
$html = do_shortcode( sprintf( '[ga_animales numero="%d" apadrinables="1"]', max( 1, (int) ga_opt( 'sponsor', 'count' ) ) ) );
if ( false !== strpos( $html, 'ga-empty' ) ) {
return; // Nadie marcado como «Busca padrino o madrina».
}
$button = ga_opt( 'sponsor', 'button' )
? sprintf( '<a class="ga-btn ga-btn--primary" href="%s">%s</a>', esc_url( add_query_arg( 'motivo', 'apadrinar', ga_page_url( 'contacto' ) ) . '#formulario' ), esc_html( ga_opt( 'sponsor', 'button' ) ) )
: '';
?>
<section class="ga-section ga-section--sand" id="apadrina">
<div class="ga-wrap">
<?php ga_section_head( 'sponsor', array( 'extra' => $button ) ); ?>
<?php echo $html; // Generado por el shortcode (escapado). ?>
</div>
</section>

View File

@@ -1,25 +1,40 @@
<?php
/* Últimos animales adoptados: se oculta si todavía no hay ninguno. */
$adopted = ga_query_animals( array(
'numero' => max( 1, (int) ga_opt( 'stories', 'count' ) ),
'estado' => 'adoptado',
) );
if ( ! $adopted->have_posts() ) {
/*
* Finales felices: las historias aprobadas (enviadas por las familias); si aún no hay,
* los últimos animales adoptados. Si no hay nada, la sección no aparece.
*/
$number = max( 1, (int) ga_opt( 'stories', 'count' ) );
$stories = function_exists( 'ga_query_stories' ) ? ga_query_stories( $number ) : null;
$adopted = ( $stories && $stories->have_posts() ) ? null : ga_query_animals( array( 'numero' => $number, 'estado' => 'adoptado' ) );
if ( ! ( $stories && $stories->have_posts() ) && ! $adopted->have_posts() ) {
return;
}
$form_page = get_page_by_path( 'finales-felices' );
$form_url = $form_page && 'publish' === $form_page->post_status ? ga_page_url( 'finales-felices' ) : '';
$button = $form_url && ga_opt( 'stories', 'button' )
? sprintf( '<a class="ga-btn ga-btn--outline" href="%s">%s</a>', esc_url( $form_url ), esc_html( ga_opt( 'stories', 'button' ) ) )
: '';
$carousel = 'carrusel' === ga_opt( 'stories', 'view' );
?>
<section class="ga-section">
<div class="ga-wrap">
<?php ga_section_head( 'stories', array( 'center' => true ) ); ?>
<?php
$carousel = 'carrusel' === ga_opt( 'stories', 'view' );
$carousel ? ga_carousel_open( ga_opt( 'stories', 'title' ) ) : print( '<div class="ga-grid">' );
while ( $adopted->have_posts() ) :
$adopted->the_post();
get_template_part( 'template-parts/animal-card' );
endwhile;
wp_reset_postdata();
$carousel ? ga_carousel_close() : print( '</div>' );
?>
<?php ga_section_head( 'stories', array( 'extra' => $button ) ); ?>
<?php $carousel ? ga_carousel_open( ga_opt( 'stories', 'title' ) ) : print( '<div class="ga-grid">' ); ?>
<?php if ( $stories && $stories->have_posts() ) : ?>
<?php while ( $stories->have_posts() ) : $stories->the_post(); ?>
<article class="ga-story">
<div class="ga-story__img">
<?php echo has_post_thumbnail() ? get_the_post_thumbnail( null, 'ga-card', array( 'loading' => 'lazy' ) ) : '<div class="ga-card__placeholder">' . ga_placeholder_svg() . '</div>'; ?>
</div>
<blockquote class="ga-story__body">
<p><?php echo esc_html( wp_strip_all_tags( get_the_content() ) ); ?></p>
<footer><strong><?php the_title(); ?></strong><?php $f = get_post_meta( get_the_ID(), '_ga_familia', true ); echo $f ? ' · ' . esc_html( $f ) : ''; ?></footer>
</blockquote>
</article>
<?php endwhile; ?>
<?php else : ?>
<?php while ( $adopted->have_posts() ) : $adopted->the_post(); get_template_part( 'template-parts/animal-card' ); endwhile; ?>
<?php endif; ?>
<?php wp_reset_postdata(); $carousel ? ga_carousel_close() : print( '</div>' ); ?>
</div>
</section>