0

I want to give users the ability to create various custom post from the frontend, but depending on the assigned taxonomy, return the custom post form linked to it. So after having obtained the selected taxonomy, it is impossible for me to check if it exists in the get_terms() request.
I thougt it was because the in_array() function doesn't do a great job when it is about multidimensional array. so I searched and find here a way to make another function that overcome that problem, but it stil doesn't work.
Here's my code:
<?php
    $cptTax = $_GET['choosetax'];

$tax1List = get_terms([
                        'taxonomy' => 'tax1',
                        'hide_empty' => false,
                    ]);

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }
    return false;
}

if( in_array_r($cptTax, $tax1List, false)): ?>
<form action="action" method="post" enctype="multipart/form-data">

I checked the $tax1List variable with a var_dump() and the slug is there... but the function return false.
Thanks for your help

1 Answer 1

0

If you just want to check if a term with a specific slug exists in the database, then you can use term_exists(). E.g.

<?php if ( term_exists( $cptTax, 'tax1' ) ) : ?>
    Your form here.
<?php endif; ?>

But if you do meant to check if the term is in a specific terms array, then you can use wp_list_filter() like so:

<?php
$found_terms = wp_list_filter( $tax1List, array( // set one or more conditions
    'slug' => $cptTax,
) );

if ( ! empty( $found_terms ) ) : ?>
    Your form here.
<?php endif; ?>

Or you could instead use array_filter() to use your own filter function, like this:

$found_terms = array_filter( $tax1List, function ( $term ) use ( $cptTax ) {
    return ( $cptTax === $term->slug ); // here, set your own custom logic
} );

if ( ! empty( $found_terms ) ) : ?>
    Your form here.
<?php endif; ?>

And just so you know, your custom function (in_array_r()) returned false because get_terms() by default returns an array of objects where each is an instance of the WP_Term class. So basically, the if in your function would need a condition that looks like ( is_object( $item ) && $needle === $item->slug ). However, for simple filtering, I would use the wp_list_filter() above.

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.