Setting the Value for a List-Type Attribute When Updating a Listing

Hi!

I am writing a custom function in PHP in the functions.php file (using the standard WordPress API) to add a listing to the website based on the received data.

I am able to create a listing, assign categories, name, description, and meta fields (attributes like number and text).

I want to assign a value to an attribute of type “list”.

I tried to do it similarly to categories, but it didn’t work:

wp_set_post_terms($post_id, array($tip_nedvigimosti_id), 'hp_listing_tipneruhomosti');

I also couldn’t access the values of the list-type attribute directly, so I manually assigned the ID values based on their labels:

$tip_nedvigimosti_id = get_or_create_tip_nedvigimosti($row['tip-nedvigimosti']);

function get_or_create_tip_nedvigimosti($tip_nedvigimosti) {
    $terms_map = array(
        '1+1'   => 100,
        '1+kk'  => 99,
        '2+1'   => 102,
        '2+kk'  => 101,
        '3+1'   => 104,
        '3+kk'  => 103,
        '4+1'   => 106,
        '4+kk'  => 105,
        '5+1'   => 108,
        '5+kk'  => 107,
        '6 і більше' => 109,
        'Атиповий' => 110,
        'Кімната' => 98
    );

    if (array_key_exists($tip_nedvigimosti, $terms_map)) {
        return $terms_map[$tip_nedvigimosti];
    } else {
        return false;
    }
}

Can you please advise how to assign a value to a list-type attribute?

It would be helpful to get access to the values of this attribute.

Is it possible to use a function from the theme itself? If so, could you provide a link to the syntax?

Thanks

Could someone please advise if they have encountered this task before? Does anyone have experience with this?

Thank you :slight_smile:

I’m sorry for the late reply, for some reason this ticket wasn’t assigned to me.

If it’s a listing attribute of Select (or selectable, e.g. Radio, Checkboxes) type then it’s implemented as a custom taxonomy of “hp_listing_attributenamehere” (check the attribute name in the Field Name of the attribute settings) type.

If you want to save it on WordPress level then this function should be ok wp_set_post_terms() – Function | Developer.WordPress.org Please make sure that you set the correct taxonomy name and term IDs.

I recommend using HivePress API, you can create a listing object by ID:

$listing=\HivePress\Models\Listing::query()->get_by_id(123);

And then simply set attributes this way:

$listing->set_categories([1,2,3])->save_categories();

Hope this helps

Thank you very much for the response.

I tried the wp_set_post_terms() function and received the following error:

Taxonomy does not exist: hp_listing_tipneruhomosti

Here’s a screenshot with the taxonomy name:”

Code:

function test_update_atribute_term_object_site () {
    $post_id = 15513; 
    $terms = '1+1'; 
    $taxonomy = 'hp_listing_tipneruhomosti'; 

    if (!taxonomy_exists($taxonomy)) {
        error_log('Taxonomy does not exist: ' . $taxonomy);
        return false;
    }

    $term = term_exists($terms, $taxonomy);
    if (!$term) {
        error_log('Term does not exist: ' . $terms);
        return false;
    }

    $result = wp_set_post_terms($post_id, $terms, $taxonomy);

    if (is_wp_error($result)) {
        error_log('Error setting terms: ' . $result->get_error_message());
    } else {
        error_log('Terms set successfully: ' . implode(', ', $result));
    }

    return true;
}

I’ll try to do it through the HivePress API.

I wrote the following function

function test_update_attribute_term_object_site_2() {
    $post_id = 15513; // ID of the post
    $terms = [100]; // IDs of the terms you want to set

    // Get the listing object by ID
    $listing = \HivePress\Models\Listing::query()->get_by_id($post_id);
    
    $listing->set_categories($terms)->save_categories();
    
    return true;
}

Unfortunately, it doesn’t work, and the attribute hp_listing_tipneruhomosti isn’t being assigned the value 1+1, even though this value has the ID of 100.

Here’s a screenshot.

The taxonomy name seems to be ok, please make sure that this function runs after all the post types and taxonomies are registered. The “taxonomy doesn’t exist” error may occur if the code runs before the attribute taxonomies are registered so I recommend hooking this function to a more late action, depends on where it’s run.

Thank you. I ran the function with a priority of 100, that helped.

This function worked

function test_update_attribute_term_object_site () {
    $post_id = 15513; 
    $terms = '1+1'; 
    $taxonomy = 'hp_listing_tipneruhomosti'; 


    if (!taxonomy_exists($taxonomy)) {
        error_log('Taxonomy does not exist: ' . $taxonomy);
        return false;
    }


    $term = term_exists($terms, $taxonomy);
    if (!$term) {
        error_log('Term does not exist: ' . $terms);
        return false;
    }


    $term_id = is_array($term) ? $term['term_id'] : $term;


    $result = wp_set_post_terms($post_id, [$term_id], $taxonomy);


    if (is_wp_error($result)) {
        error_log('Error setting terms: ' . $result->get_error_message());
    } else {
        if (!empty($result)) {
            error_log('Terms set successfully: ' . implode(', ', $result));
        } else {
            error_log('Terms were not set.');
        }
    }

    return true;
}
2 Likes

Hi!

I have photo files on my hosting.

I have an ad ID where these photos need to be added.

Please help me write a PHP snippet for functions.php for this.

If these files are not yet uploaded as WordPress attachments in WordPress/Media, then you can try this function wp_handle_sideload() – Function | Developer.WordPress.org You can check the example there which downloads a file by URL (you can do this from the same domain) and then creates an attachment. If you mean attaching these files to a listing you can set listing ID as post_parent for the uploaded attachment, also setting hp_model to listing and hp_field post meta to the attachment field name (e.g. images).

Hope this helps

Thank you, your answer helped me :slight_smile:

Here is the code that worked:

function import_photos_to_site($id, $photos) {
    $args = array(
        'post_type'  => 'hp_listing',
        'post_status' => array('draft', 'pending', 'private', 'publish'), 
        'meta_query' => array(
            array(
                'key'   => 'hp_idobject',
                'value' => $id,
                'compare' => '='
            )
        )
    );

    $query = new WP_Query($args);

    if ($query->have_posts()) {
        $query->the_post();
        $listing_id = get_the_ID();

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

        foreach ($photos as $photo) {
            $attachment_id = upload_and_attach_photo($photo, $listing_id);
        }

        wp_reset_postdata();
        
        return true;

    } else {
        return false;
    }
}
function upload_and_attach_photo($photo_url, $listing_id) {
    $tmp = download_url($photo_url);

    if (is_wp_error($tmp)) {
        return false;
    }

    $file_array = array(
        'name'     => basename($photo_url),
        'tmp_name' => $tmp
    );

    $upload_overrides = array('test_form' => false);
    $file_data = wp_handle_sideload($file_array, $upload_overrides);

    @unlink($file_array['tmp_name']);

    if (isset($file_data['error'])) {
        return false;
    }

    $attachment = array(
        'guid'           => $file_data['url'],
        'post_mime_type' => $file_data['type'],
        'post_title'     => preg_replace('/\.[^.]+$/', '', basename($file_data['file'])),
        'post_content'   => '',
        'post_status'    => 'inherit',
        'post_parent'    => $listing_id
    );

    $attachment_id = wp_insert_attachment($attachment, $file_data['file'], $listing_id);

    if (!is_wp_error($attachment_id)) {
        $attach_data = wp_generate_attachment_metadata($attachment_id, $file_data['file']);
        wp_update_attachment_metadata($attachment_id, $attach_data);

        update_post_meta($attachment_id, 'hp_model', 'listing');
        update_post_meta($attachment_id, 'hp_field', 'images'); 

        return $attachment_id;
    } else {
        return false;
    }
}
2 Likes

Hi!

The code above adds images to the listing, and all added images are loaded on the individual listing page.

However, in the listing view, the object image does not load.

Here is an example:

Individual listing page:

https://noblessehomes.com/listing/kvartyra-1-1-22-m²-test/

Listing:

Could you please advise on how to fix this issue?

I don’t want to dive into the theme code and make rough changes as I want to continue updating it afterward.

There are 3 conditions for the listing gallery image attachments:

hp_model post meta set to “listing”
hp_field post meta set to “images”
post_parent set to the listing ID

Please make sure that these are set, if they still don’t show on the front-end then this may be due to caching, please try using this temporary snippet to check if the issue persists:

define('HP_CACHE', false);

Hi! Thanks!

I fixed my code, and everything worked.

The problem was that the main image wasn’t being assigned to the post.

Here is the final code:

function import_photos_to_site($id, $photos) {
    $args = array(
        'post_type'  => 'hp_listing',
        'post_status' => array('draft'),
        'meta_query' => array(
            array(
                'key'   => 'hp_idobject',
                'value' => $id,
                'compare' => '='
            )
        )
    );

    $query = new WP_Query($args);

    if ($query->have_posts()) {
        $query->the_post();
        $listing_id = get_the_ID();

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

        $all_photos_uploaded = true;
		$first_attachment_id = null;

        foreach ($photos as $photo) {
            $attachment_id = upload_and_attach_photo($photo, $listing_id);

            if ($attachment_id) {
				if (!$first_attachment_id) {
            		$first_attachment_id = $attachment_id;
        		}
            } else {
                $all_photos_uploaded = false;
            }
        }
		
		if ($first_attachment_id && !has_post_thumbnail($listing_id)) {
			set_post_thumbnail($listing_id, $first_attachment_id);
		}

        wp_reset_postdata();

        if ($all_photos_uploaded) {
			
            $post_data = array(
                'ID'           => $listing_id,
                'post_status'  => 'publish',
            );
            wp_update_post($post_data);

        }
        
        return true;

    } else {
        return false;
    }
}

function upload_and_attach_photo($photo_url, $listing_id) {

    $tmp = download_url($photo_url);

    if (is_wp_error($tmp)) {
        return false;
    }

    $file_array = array(
        'name'     => basename($photo_url),
        'tmp_name' => $tmp
    );

    $upload_overrides = array('test_form' => false);
    $file_data = wp_handle_sideload($file_array, $upload_overrides);

    @unlink($file_array['tmp_name']);

    if (isset($file_data['error'])) {
        return false;
    }

    $attachment = array(
        'guid'           => $file_data['url'],
        'post_mime_type' => $file_data['type'],
        'post_title'     => preg_replace('/\.[^.]+$/', '', basename($file_data['file'])),
        'post_content'   => '',
        'post_status'    => 'inherit',
        'post_parent'    => $listing_id
    );

    $attachment_id = wp_insert_attachment($attachment, $file_data['file'], $listing_id);

    if (!is_wp_error($attachment_id)) {
        $attach_data = wp_generate_attachment_metadata($attachment_id, $file_data['file']);
        wp_update_attachment_metadata($attachment_id, $attach_data);

        update_post_meta($attachment_id, 'hp_model', 'listing');
        update_post_meta($attachment_id, 'hp_field', 'images');

        return $attachment_id;
    } else {
        return false;
    }
}

Thanks!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.