• Resolved jordiwordpress

    (@jordiwordpress)


    Hello,

    I have a CPT called “edicin”, and I’ve created a field with relationship with Users extended. The name of the field is “usuario”.

    I would like create a button in the “edicin” template for binding with one click the current post with the logged user.

    I’ve write this in the template:

    <?php // Agregar el botón que activa la función para vincular la "edicin" al usuario 
    
    echo '<form method="post">'; echo '<input type="hidden" name="vincular_edicin" value="' . get_the_ID() . '">'; echo '<input type="submit" value="Vincular a mi colección" class="button">'; echo '</form>'; ?>

    And this in the functions php:

    // boton de vinculacion
    function vincular_edicin_to_user() {
        if (isset($_POST['vincular_edicin']) && is_user_logged_in()) {
            $edicion_id = absint($_POST['vincular_edicin']);
            $user_id = get_current_user_id();
    
            // Aquí utilizamos el campo de relación "usuario" para vincular la "edicin" al usuario
            // Por ejemplo:
            $fields = array('usuario' => $user_id); // Donde 'usuario' es el nombre del campo de relación
            pods_api()->save_pod_item($edicin_id, 'edicin', $fields);
        }
    }
    add_action('init', 'vincular_edicin_to_user');
    

    When I click the button redirect me a page with the message “Invalid taxonomy”

    can you help me?

    Thanks

Viewing 5 replies - 1 through 5 (of 5 total)
  • Plugin Support Paul Clark

    (@pdclark)

    You’re likely looking for:

    pods( 'edicin', absint( $_POST['vincular_edicin'] ) )->save( ['usuario' => get_current_user_id()] );

    See pods()->save(), not pods_api()->save_pod_item()

    Thread Starter jordiwordpress

    (@jordiwordpress)

    Thanks, the message “Invalid taxonomy” has dissapeared but don’t biding the post with any user.

    I’ve think that another way would be write a form shortcode in “edicin” template, and include only @usuario field, but the list display all the users.
    Is there a way to make only the current user appear in the list?

    thanks

    Plugin Support Paul Clark

    (@pdclark)

    Here is a revision that assumes your usuario field on the edicin post type is specified as “Multiple Select” under “Relationship Options” under “Edit Field”. I expect this may be the case, as associating multiple users with the post would require this.

    The code below takes several things into consideration:

    • The first function adds the form to the end of all the edicin posts automatically. It is noted in the comments how to add to a PHP template instead, if that’s preferable.
    • The second function outputs a save button. If the user is not logged in, it provides a link to login that will redirect back to the post. If the user is already associated with the post, the button will remove from the relationship. If the user is not associated with the post, the button will add the user to the relationship. A _wpnonce field is also included, which is a way of verifying that the user actually clicked the button.
    • The third function processes the form. It is on ‘template_redirect’, which only runs on frontend templates, as apposed to ‘init’, which loads everywhere. It accounts for either possible setting you might have under Pods Admin > Settings > Performance > Watch WP Metadata Calls. It either adds the user to the relationship or removes them.

    Here is the example code:

    <?php
    
    /**
     * Ejemplo de agregar el botón al final del contenido para cada publicación de 'edición'.
     * 
     * Esto también podría agregarse a la plantilla PHP:
     *     echo apply_filters( 'edicin_save_button', '' );
     */
    add_filter(
    	'the_content',
    	function ( $content ) {
    		if ( 'edicin' !== get_post_type() ) {
    			return $content;
    		}
    		return sprintf(
    			'%s%s',
    			$content,
    			apply_filters( 'edicin_save_button', '' )
    		);
    	}
    );
    
    /**
     * Mostrar un botón para asociar la 'edición' actual con un usuario.
     * 
     * Uso en una plantilla:
     *     echo apply_filters( 'edicin_save_button', '' );
     */
    add_filter(
    	'edicin_save_button',
    	function( $default ) {
    		if ( 'edicin' !== get_post_type() ) {
    			return '';
    		}
    		if ( ! is_user_logged_in() ) {
    			return sprintf(
    				'<p class="notice">%s</p>',
    				sprintf(
    					__( 'Por favor, <a href="%s">inicia sesión</a> para guardar en tu colección.', 'edicin' ),
    					esc_url( wp_login_url( get_the_permalink() ) )
    				)
    			);
    		}
    		
    		/**
    		 * Esto supone que el campo 'usuario' es una relación "multi-select".
    		 */
    		$edicin_pod = pods( 'edicin', get_the_ID() );
    		$associated_user_ids = (array) $edicin_pod->field('usuario', false );
    
    		/**
    		 * This is necessary if "Pods Admin > Settings > Performance > Watch WP Metadata Calls" is set to:
    		 *     "Enable watching WP Metadata calls (may reduce performance with large processes)"
    		 */
    		if ( isset( $associated_user_ids[0] ) && is_array( $associated_user_ids[0] ) ) {
    			$associated_user_ids = wp_list_pluck( $associated_user_ids, 'ID' );
    		}
    		$is_in_user_collection = in_array( get_current_user_id(), (array) $associated_user_ids );
    
    		return sprintf(
    			'<form method="POST" action=".">
    				<input type="hidden" name="edicin_id" value="%d" />
    				<input type="hidden" name="action" value="%s" />
    				%s
    				<button type="submit">%s</button>
    			</form>',
    			get_the_ID(),
    			( $is_in_user_collection ) ? 'remove' : 'add',
    			wp_nonce_field( 'edicin-save', '_wpnonce', true, false ),
    			( $is_in_user_collection ) ? __( 'Eliminar de mi colección', 'edicin' ) : __( 'Vincular a mi colección', 'edicin' ),
    		);
    	}
    );
    
    /**
     * Procesar el formulario de guardado del usuario para la "edicin".
     * 
     * Esto supone que el campo 'usuario' es una relación "multi-select".
     */
    add_action(
    	'template_redirect',
    	function() {
    		if (
    			'edicin' !== get_post_type()
    			|| ! isset( $_POST['edicin_id'] )
    			|| ! isset( $_POST['action'] )
    			|| ! wp_verify_nonce( @$_POST['_wpnonce'], 'edicin-save' )
    			|| ! is_user_logged_in()
    		) {
    			return;
    		}
    
    		$edicin_pod = pods( 'edicin', absint( $_POST['edicin_id'] ) );
    
    		$associated_user_ids = (array) $edicin_pod->field('usuario', false );
    
    		/**
    		 * This is necessary if "Pods Admin > Settings > Performance > Watch WP Metadata Calls" is set to:
    		 *     "Enable watching WP Metadata calls (may reduce performance with large processes)"
    		 */
    		if ( isset( $associated_user_ids[0] ) && is_array( $associated_user_ids[0] ) ) {
    			$associated_user_ids = wp_list_pluck( $associated_user_ids, 'ID' );
    		}
    
    		if ( 'add' === $_POST['action'] ) {
    			$edicin_pod->save([
    				'usuario' => array_merge(
    					$associated_user_ids,
    					[ get_current_user_id() ],
    				)
    			]);	
    		}else if ( 'remove' === $_POST['action'] ) {
    			$edicin_pod->save([
    				'usuario' => array_diff(
    					$associated_user_ids,
    					[ get_current_user_id() ],
    				)
    			]);	
    		}
    		
    	}
    );
    
    Plugin Support Paul Clark

    (@pdclark)

    Also, given the nature of your data, I assume it may be desirable to display the edicin associated with the current user. To do this, you will need to have a bi-directional relationship between edicin > usuario and a multiple select relationship field for edicin on the user pod.

    In the below example, I have assumed the name of this of this field on user is edicin_collection. The two functions below set up a filter current_user_edicin_collection for use in a PHP template like echo apply_filters( 'current_user_edicin_collection', '' ); and a shortcode for use elsewhere, [current-user-edicin].

    The advantage of a filter over a shortcode for use in PHP templates is that if the functionality is disabled, the raw shortcode will not be displayed.

    <?php
    
    add_filter(
    	'current_user_edicin_collection',
    	function( $default ) {
    		if ( ! is_user_logged_in() ) {
    			return '';
    		}
    		ob_start();
    
    		$current_user_edicin_ids = (array) pods( 'user', get_current_user_id() )->field( 'edicin_collection' );
    
    		if ( isset( $current_user_edicin_ids[0] ) && is_array( $current_user_edicin_ids[0] ) ) {
    			$current_user_edicin_ids = wp_list_pluck( $current_user_edicin_ids, 'ID' );
    		}
    
    		printf(
    			'<h3>%s</h3>',
    			__( 'Mi colección', 'edicin' )
    		);		
    
    		if ( empty( $current_user_edicin_ids ) ) {
    			printf(
    				'<p>%s</p>',
    				__( 'Aún no se ha guardado nada.', 'edisin' )
    			);
    			return ob_get_clean();
    		}
    
    		echo '<ul class="edicin-collection">';
    		foreach( (array) $current_user_edicin_ids as $edicin_id ) {
    			printf(
    				'<li><a href="%s">%s</a></li>',
    				get_the_permalink( $edicin_id ),
    				get_the_title( $edicin_id )
    			);
    		}
    		echo '</ul>';
    
    		return ob_get_clean();
    	}
    );
    
    add_shortcode(
    	'current-user-edicin',
    	function( $atts, $content, $tag ) {
    		return apply_filters( 'current_user_edicin_collection', '' );
    	}
    );

    All that should be enough to get you going. If something doesn’t output as expected, double-check the names of the pods and fields. For example, I’ve used edicin because that is what was written in your original post, but I would expect edicion.

    Thread Starter jordiwordpress

    (@jordiwordpress)

    Fantastic!

    This is more than an answer, it’s really like a tutorial!!. You have created interesting tool for Pods.

    I have to try the code for display the data associated with the user, my next step will be create user page (author.php)

    Thank you so much

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Button for relationship’ is closed to new replies.