metabox – Add relationship from one post in a list to current post page by clicking a button


The idea is to add a relationship from a post to another from the frontend.
On a single post page (lets say “banana post”) a list of other posts are displayed (ananas, mangos …). Within each listed posts there is a button (see image), on the click of the button (on the listed post mangos for exemple) a relationship is created.

I’m using Metabox with MB Relationships and successfully setup the functionality for the backend.

The challenge is to get the ID of the listed post which the button is pressed. The part that is not working is retrieving the ID of the clicked post. Here is what I have so far.

//Add Relationship between offers 
add_action( 'manual_assign', 'connect_offers' );

//Get listed post ID, the part which is not working
$posts = get_posts();
foreach ( $posts as $item ) {
    $post_id  = get_post_meta( $item->ID, 'cat-to', true );
//Metabox functionality
function connect_offers(){
      $offerFrom = get_queried_object_id();
      $offerTo = $post_id; //The variable I'm trying to retrieve, working if inputing manually a post ID
      $offerId = 'offer_to_offer';
            $from = $offerFrom, 
            $to = $offerTo, 
            $id = $offerId, 
            $order_from = 1, 
            $order_to = 1 );
 } ;

The part that is displaying the posts list on the front

$homepageOffers = new WP_Query(array(
                      'posts_per_page' => 3,
                      'post_type' => 'offer',
                      'order' => 'ASC',
                while($homepageOffers->have_posts()) {  
                <form method="post">
                    <h5><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h5>
                    <p><?php if (has_excerpt()) {
                        echo get_the_excerpt();
                            } else {
                        echo wp_trim_words(get_the_content(), 18);
                        } ?><a href="<?php the_permalink(); ?>"> Learn more</a>
                    <input type="submit" name="btn-add-relationship" value="Propose Here"/>

And the button

        do_action( 'manual_assign' );

post and posts list exemple

mrdaco 2 years 2022-03-05T11:07:12-05:00 0 Answers 0 views 0

Leave an answer