0

I created a CPT with a page where you can add posts from the Frontend. This is the code in the fuction.php:

// Hook into the 'init' action
add_action( 'init', 'register_cpt_promociona', 0 );

if ( ! function_exists('register_cpt_promociona') ) {

    // Register Custom Post Type
    function register_cpt_promociona() {

        $labels = array(
            'name'                => _x( 'Promociones publicadas', 'Post Type General Name', 'ainder' ),
            'singular_name'       => _x( 'Promociona', 'Post Type Singular Name', 'ainder' ),
            'menu_name'           => __( 'Promociona', 'ainder' ),
            'parent_item_colon'   => __( 'Promoción padre', 'ainder' ),
            'all_items'           => __( 'Todas las Promociones', 'ainder' ),
            'view_item'           => __( 'Ver Promociones', 'ainder' ),
            'add_new_item'        => __( 'Tu Promoción', 'ainder' ),
            'add_new'             => __( 'Añadir nuevo', 'ainder' ),
            'edit_item'           => __( 'Editar Promoción', 'ainder' ),
            'update_item'         => __( 'Actualizar Promoción', 'ainder' ),
            'search_items'        => __( 'Buscar Promoción', 'ainder' ),
            'not_found'           => __( 'Ningna Promoción encontrada', 'ainder' ),
            'not_found_in_trash'  => __( 'Ningna Promoción encontrada en la papelera', 'ainder' ),
        );

        $rewrite = array(
            'slug'                => 'promociona',
            'with_front'          => true,
            'pages'               => true,
            'feeds'               => true,
        );

        $args = array(
            'label'               => __( 'promociona', 'ainder' ),
            'description'         => __( 'CPT de Promociones de usuarios', 'ainder' ),
            'labels'              => $labels,
            'supports'            => array( 'title', 'editor', 'thumbnail', 'author', 'comments', 'custom-fields', ),
            'taxonomies'          => array( 'categoria-promociona' ),
            'hierarchical'        => false,
            'public'              => true,
            'show_ui'             => true,
            'show_in_menu'        => true,
            'show_in_nav_menus'   => true,
            'show_in_admin_bar'   => true,
            'menu_position'       => 5,
            'can_export'          => true,
            'has_archive'         => true,
            'exclude_from_search' => false,
            'publicly_queryable'  => true,
            'rewrite'             => $rewrite,
        );

        register_post_type( 'promociona', $args );

    } // end function register_cpt_promociona

} // end if (!function_exists)

// Lo enganchamos en la acción init y llamamos a la función create_promociona_taxonomies() cuando arranque
add_action( 'init', 'create_promociona_taxonomies', 0 );

// Creamos dos taxonomías, género y autor para el custom post type "promoción"
function create_promociona_taxonomies() {
    // Añadimos nueva taxonomía y la hacemos jerárquica (como las categorías por defecto)
    $labels = array(
        'name'              => _x( 'Categoría de la promoción', 'taxonomy general name' ),
        'singular_name'     => _x( 'Categoría promociona', 'taxonomy singular name' ),
        'search_items'      =>  __( 'Buscar por Categoría' ),
        'all_items'         => __( 'Todas las Categorías' ),
        'parent_item'       => __( 'Categoría padre' ),
        'parent_item_colon' => __( 'Categoría padre:' ),
        'edit_item'         => __( 'Editar Categoría' ),
        'update_item'       => __( 'Actualizar Categoría' ),
        'add_new_item'      => __( 'Añadir nueva Categoría' ),
        'new_item_name'     => __( 'Nombre de la nueva Categoría' ),
    );
    register_taxonomy( 'categoria-promociona', 
        array( 'promociona' ), 
            array(
                'hierarchical'  => true,
                'labels'        => $labels, /* ADVERTENCIA: Aquí es donde se utiliza la variable $labels */
                'show_ui'       => true,
                'query_var'     => true,
                'rewrite'       => array( 'slug' => 'categoria-promociona' ),
            )
        );
} // end function create_promociona_taxonomies

And this is the code in the file page-proyecta.php:

    <?php

/**
 * Template Name: AINDER Promociona Loop
 *
 * @package BuddyPress
 * @subpackage Theme
 */

if (!is_user_logged_in()) {
    wp_redirect( home_url() );
}

get_header( 'buddypress' ); ?>

<script type="text/javascript">
    jQuery(document).ready(function() {
        jQuery('#titulo-cpt').focus(function(event) { 
            jQuery('#whats-new-options').addClass('whats-new-options-open', 2000);
        });
        jQuery('#whats-new').focus(function(event) {
            jQuery('#whats-new-options').addClass('whats-new-options-open', 2000);
        });
    });
</script>

<?php 
    // Conseguimos primero el id de la página para la imagen destacada y lo guardamos en una variable
    $id_page = get_the_ID();
    // Conseguimos el objeto ainder-promociona (CPT)
    $obj = get_post_type_object( 'promociona' );
?>

    <div id="content">

        <div id="item-header" role="complementary">

            <div id="item-header-avatar">

                <div class="single-group-box-image-container">
                    <a href="" title="<?php echo $obj->labels->singular_name; ?>"><img src="http://localhost/ainder/wp-content/uploads/group-avatars/30/aacdd8a094d297fd5d336809ccd89d01-bpfull.jpg" class="avatar group-30-avatar avatar-150 photo" width="150" height="150" alt="Logo del grupo LA INTELIGENCIA EMOCIONAL EN EL EMPRENDEDOR"></a>
                    <?php echo get_the_post_thumbnail( $id_page, array( 150, 150 ) ); ?>
                </div>

            </div><!-- #item-header-avatar -->

            <div id="item-header-content" class="cpt-morado">

                <h2><?php echo $obj->labels->singular_name; ?></h2>

                <div class="single-group-meta"></div>

                    <p><?php _e( '¿Tienes una empresa, organización u ONG? <br>
                    Dala a conocer', 'ainder' ); ?></p>

                    <div class="gtags-header"><!-- Categorías -->
                    </div> <!-- .gtags-header -->

            </div><!-- #item-header-content -->
        </div><!-- #item-header -->


        <div id="item-body">

<!-- FORMULARIO -->

            <?php
            // Para crear los post desde el front con un formulario
            if ($_POST && ( $_POST['titulo-promociona'] != '' ) ) {

                $post_type      = 'promociona';
                $post_title     = $_POST['titulo-promociona'];
                $post_content   = $_POST['contenido-promociona'];
                $post_category  = $_POST['categoria-promociona'];
                $image          = $_POST['imagen-promociona'];
                $video_url      = $_POST['video-promociona'];
                $enlace_url     = $_POST['enlace-promociona'];

                $new_post = array(
                 'post_author'      => $user->ID,
                 'post_title'       => $post_title,
                 'post_content'     => $post_content,
                 'post_category'    => array($post_category),
                 'post_status'      => 'publish',
                 'comment_status'   => 'open',
                 'post_type'        => $post_type
                );

                // Creamos el post con los datos de $new_post y obtenemos su ID nuevecita
                $post_id = wp_insert_post( $new_post );

                // Insertamos la "categoría" (realmente es una taxonomía)
                wp_set_object_terms( $post_id, $post_category, 'categoria-promociona');

                if ( !empty( $video_url )  ) {
                    // Insertamos en DDBB la URL del video si lo hay
                    update_post_meta( $post_id, 'video_url', $video_url );
                }

                if ( !empty( $enlace_url ) ) {
                    // Insertamos en DDBB la URL del enlace si lo hay
                    update_post_meta( $post_id, 'enlace_url', $enlace_url );
                }


                // Para la imagen lo tenemos un poco más complicado
                if ( !empty( $image ) ) {
                    // Guardamos la ruta del directorio upload en una variable
                    $upload_dir = wp_upload_dir();
                    // Leemos el archivo y lo guardamos en una variable
                    $image_data = file_get_contents($image);
                    // Nombramos la imagen con el nombre del archivo
                    $filename   = basename($image);

                    if(wp_mkdir_p($upload_dir['path']))
                        $file = $upload_dir['path'] . '/' . $filename;
                    else
                        $file = $upload_dir['basedir'] . '/' . $filename;

                    file_put_contents($file, $image_data);

                    $wp_filetype = wp_check_filetype($filename, null );

                    $attachment = array(
                        'post_mime_type' => $wp_filetype['type'],
                        'post_title'     => sanitize_file_name($filename),
                        'post_content'   => '',
                        'post_status'    => 'inherit'
                    );

                    $attach_id = wp_insert_attachment( $attachment, $file, $post_id );

                    require_once(ABSPATH . 'wp-admin/includes/image.php');

                    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );

                    wp_update_attachment_metadata( $attach_id, $attach_data );

                    set_post_thumbnail( $post_id, $attach_id );
                } // end if (isset($image))

            } // end if ($_POST)
            ?>

            <div class="cpt-title">
                <h4><?php echo $obj->labels->add_new_item; ?></h4>
            </div>

            <div class="cpt_form_container">

                <form action="" method="post" id="whats-new-form" name="whats-new-form" >

                    <?php // do_action( 'bp_before_activity_post_form' ); ?>

                    <div id="whats-new-avatar"> <!-- AVATAR DEL USUARIO -->
                        <a href="<?php echo bp_loggedin_user_domain(); ?>">
                            <?php bp_loggedin_user_avatar( 'width=' . bp_core_avatar_thumb_width() . '&height=' . bp_core_avatar_thumb_height() ); ?>
                        </a>
                    </div>

                    <p class="titulo-cpt">
                        <?php _e( 'Titula tu Link', 'ainder' ); ?>
                    </p>

                    <div id="whats-new-content">

                        <div id="whats-new-textarea">
                                <input type="text" class="bp-suggestions" name="titulo-promociona" id="titulo-cpt" required maxlength="60"></input>
                        </div>

                        <p class="input-cpt">
                            <?php printf( __( '%s, explica en qué consiste y qué ofreces (max. 300 caracteres)', 'ainder' ), bp_get_user_firstname( bp_get_loggedin_user_fullname() ) ); ?>
                        </p>

                        <div id="whats-new-textarea">
                            <textarea class="bp-suggestions" name="contenido-promociona" id="whats-new" required>
                            </textarea>
                        </div>

                        <div id="whats-new-options">
                            <p class="input-cpt">
                                <?php _e( 'Añade una imagen (obligatorio)', 'ainder' ); ?>
                            </p>
                            <div id="whats-new-textarea">
                                <input type="file" class="bp-suggestions" name="imagen-promociona" id="imagen-cpt" required>
                            </div>

                            <p class="input-cpt">
                                <?php _e( 'Añade el Link', 'ainder' ); ?>
                            </p>
                            <div id="whats-new-textarea">
                                <input type="url" class="bp-suggestions" name="enlace-promociona" id="enlace-cpt">
                            </div>

                            <p class="input-cpt">
                                <?php _e( 'Añade un video', 'ainder' ); ?>
                            </p>
                            <div id="whats-new-textarea">
                                <input type="url" class="bp-suggestions" title="Si pegas el enlace para compartir de Youtube, aparecerá el vídeo, si sólo pegas la ruta normal aparecerá el enlace vinculado al vídeo" name="video-promociona" id="video-cpt">
                            </div>

                            <div id="whats-new-submit">
                                <input type="submit" name="submit" id="submit" value="<?php esc_attr_e( 'Publicar', 'ainder' ); ?>" />
                            </div>

                            <?php //if ( bp_is_active( 'groups' ) && !bp_is_my_profile() && !bp_is_group() ) : ?>

                            <div id="whats-new-post-in-box">

                                <?php _e( 'Publicar en', 'ainder' ); ?>:

                                <select required id="whats-new-post-in" name="categoria-promociona">
                                    <option selected="selected" value="">
                                        <?php 
                                            $args = array(
                                                'post_type' => 'promociona',
                                                'taxonomy'  => 'categoria-promociona',
                                                'hide_empty' => 0,
                                                'order' => 'ASC'
                                            );

                                            $categories = get_categories($args);

                                            foreach($categories as $category) { 
                                                                //echo '<div class="cat"><h2><a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "have a look at %s" ), $category->name ) . '" ' . '>' . $category->name.'</a></h2><br /><p>Books: '. $category->count.' </p></div> '; 
                                                echo "<option value='".$category->name."'>$category->name</option>"; // $category->term_id
                                            }  
                                        ?>

                                </select>
                            </div> <!-- #whats-new-post-in-box -->
                                <!-- <input type="hidden" id="whats-new-post-object" name="whats-new-post-object" value="groups" /> -->

                            <?php // elseif ( bp_is_group_home() ) : ?>

                                <!-- <input type="hidden" id="whats-new-post-object" name="whats-new-post-object" value="groups" /> -->
                                <!-- <input type="hidden" id="whats-new-post-in" name="whats-new-post-in" value="<?php// bp_group_id(); ?>" /> -->

                            <?php // endif; ?>

                            <?php //do_action( 'bp_activity_post_form_options' ); ?>

                        </div><!-- #whats-new-options -->
                    </div><!-- #whats-new-content -->

                    <?php wp_nonce_field( 'post_update', '_wpnonce_post_update' ); ?>
                    <?php// do_action( 'bp_after_activity_post_form' ); ?>

                </form><!-- #whats-new-form -->
            </div> <!-- .bpfb_form_container -->
        </div> <!-- .item-body -->

<!-- /FORMULARIO -->

<!-- Loop de CPT promociona -->

        <div class="titulo-loop">
            <h4><?php echo $obj->labels->name; ?></h4>
        </div>

        <div class="categoria-loop">
            <div id="titulo-desplegable">
                <span class="desplegable"><?php _e('Elegir por categorías', 'ainder') ?></span>


                <!-- <option selected="selected" value="0"><?php _e("Elegir categoría", "ainder"); ?></option> -->
                <?php 
                $terms = get_terms( 'categoria-promociona' );

                echo '<ul class="desplegable-categoria-loop">';


                foreach ( $terms as $term ) {

                    // The $term is an object, so we don't need to specify the $taxonomy.
                    $term_link = get_term_link( $term );

                    // If there was an error, continue to the next term.
                    if ( is_wp_error( $term_link ) ) {
                        continue;
                    }

                    // We successfully got a link. Print it out.
                    echo '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '</a></li>';
                }

                echo '</ul>';


                ?>
            </div>
        </div> <!-- .categoria-loop -->

        <div class="clear"></div>

        <div id="item-loop">

            <?php
            $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
            $wp_query  = new WP_Query( array( 
                'post_type'             => 'promociona',
                'post-category'         => array( $category_name ),
                'posts_per_page'        => 7,
                'ignore_sticky_posts'   => 1,
                'paged'                 => $paged
                )
            );

        if ( $wp_query->have_posts() ) :
            while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>

        <div class="cpindex">

            <div class="cpautor">

                <span class="avatar">
                    <a href="<?php echo bp_core_get_user_domain( get_the_author_meta( 'ID' ) ); ?>" title="<?php the_author_meta( 'display_name' ); ?>">
                        <?php bp_activity_avatar( array( 'user_id' => get_the_author_meta( 'ID' ) ) ); ?>
                    </a>
                </span>
                <span class="texto-publicado"><?php _e('Publicado por: ', 'ainder'); ?></span>
            </div> <!-- .cpautor -->

            <div class="cpthumbnail">
                <?php 
                if ( has_post_thumbnail() ) {
                    echo get_the_post_thumbnail( $post_id, array( 100, 100) );
                 } ?>
            </div>

            <div class="cptitle">
                <h5><?php echo get_the_title(); ?></h5>
            </div>

            <div class="cpcategories">

                <p class="custompostmetadata"><?php _e( 'CATEGORÍA:', 'ainder'); ?> <?php the_terms( get_the_ID(), 'categoria-promociona' ); ?></p>
            </div>

            <div class="cpcontent">

                <?php the_excerpt(); ?> <?php //the_content(); ?>
                <div class="cpmetas">

                    <span class="cplink"><?php _e( 'Link: ', 'ainder'); ?><a target="_blank" href="<?php echo get_post_meta( get_the_ID(), 'enlace_url', true ); ?>"><?php echo get_post_meta( get_the_ID(), 'enlace_url', true ); ?></a></span>
                    <br>
                    <span class="cpvideo"><?php _e( 'Video: ', 'ainder'); ?><a target="_blank" href="<?php echo get_post_meta( get_the_ID(), 'video_url', true ); ?>"><?php echo get_post_meta( get_the_ID(), 'video_url', true ); ?></a></span> 
                </div> <!-- .cpmetas -->
            </div> <!-- .cpcontent -->

            <div class="clear"></div>

        </div> <!-- .cpindex -->

    <?php endwhile;

    if (  $wp_query->max_num_pages > 1 ) { ?>
        <div id="nav-below" class="navigation">
            Paginación
            <div class="nav-previous"><?php next_posts_link( __( '<span class="meta-nav">&larr;</span> Anteriores', 'ainder' ) ); ?></div>
            <div class="nav-next"><?php previous_posts_link( __( 'Siguientes <span class="meta-nav">&rarr;</span>', 'ainder' ) ); ?></div>
        </div>
    <?php } // end if($loop-)
endif;
wp_reset_postdata();
?>

        </div>

    </div><!-- .content -->

<?php get_sidebar( 'buddypress' ); ?>
<?php get_footer( 'buddypress' ); ?>

Where the important point is this:

    // Para la imagen lo tenemos un poco más complicado
if ( !empty( $image ) ) {
    // Guardamos la ruta del directorio upload en una variable
    $upload_dir = wp_upload_dir();
    // Leemos el archivo y lo guardamos en una variable
    $image_data = file_get_contents($image);
    // Nombramos la imagen con el nombre del archivo
    $filename   = basename($image);

    if(wp_mkdir_p($upload_dir['path']))
        $file = $upload_dir['path'] . '/' . $filename;
    else
        $file = $upload_dir['basedir'] . '/' . $filename;

    file_put_contents($file, $image_data);

    $wp_filetype = wp_check_filetype($filename, null );

    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title'     => sanitize_file_name($filename),
        'post_content'   => '',
        'post_status'    => 'inherit'
    );

    $attach_id = wp_insert_attachment( $attachment, $file, $post_id );

    require_once(ABSPATH . 'wp-admin/includes/image.php');

    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );

    wp_update_attachment_metadata( $attach_id, $attach_data );

    set_post_thumbnail( $post_id, $attach_id );
} // end if (isset($image))

The problem is that, even though the picture is in the gallery of media, it does not look anywhere. I think it has to do with the time of reading the image file ($ image_data = file_get_contents ($ image);) or by inserting data file (file_put_contents ($ file, $ image_data);). Can anyone shed some light on the matter?

Thanks in advance

0

After two days looking for the solution and fighting with the code, I found the solution:

As I suspected, the problem was reading the file ($image_data = file_get_contents($image);).

The first error was not included in the form enctype =" multipart / form-data " to send files and data simultaneously.

The second error was that images are not loaded by $_POST, if not the global variable $_FILES (In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead of $_FILES).

And the last error was that we have to move the file to the directory uploads to read it from there with move_uploaded_file( $_FILES['imagen-promociona']['tmp_name'], $uploadfile )

I hope at least help others.

Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.