custom post types – How to specify user ID for a CPT wp_insert_post when there’s no actual user (it’s programmatic)

Here’s what I hope is a simple question. When using wp_insert_post to add a custom post type record, if the post author isn’t an actual editorial user, but instead an externally-driven data item (in my case, a log entry), how should the post_author field be specified? Do I just pick a user ID, leave it blank, or set it to something like 1? Thanks!

plugin development – Update cpt post/page with current date & time if post custom field value match to cpt post/page CF Value

My question is – I have a CPT Post name Company (CF Value – Google) and a Page titled Role (CF V – Engineer). So I want to auto-update with Post published time and date to company post and Role page if published post custom field value match to Google and Engineer.

For example –

  • A Job Post published at 11:30:21PM, 13/09/2021, has two Custom Fields Title Company and Role which has Google and Engineer values.

  • Already published CPT Post Company has a post Google Jobs which has similar CF values Google.

  • Similarly already published page Engineer Jobs which has CF value Engineer.

So my all condition is satisfied because CF value matched, now the code should update Engineer Job (Page), Google Jobs (Post) date and time with recent published post date, time.

Any reference code or help will be appreciated, I want to implement code in my functions.php file.

custom post types – CPT ui, categories, taxonomies – 2 different archives child of a single page

i’m developing a website for a sports association, that offers courses for basket, volley, calisthenics and ballet (here’s the url: baldivive.it). I’m using elementor, cptui and acf.

I am having an hard time figuring out how i can have single pages for the activities (hence a /basket/ page, a /volley/, /ballet/, /calisthenics/) which display some info about the courses, but also have TWO different child archives in them, one for news related to that sport, and one for events related to it.

So what i need to achieve is this (let’s take basket for example):
baldivive.it/basket/news/post-name
and
baldivive.it/basket/events/post-name

I’ve tried creating a custom post type for each activity, and then assign to all those custom post types a taxonomy of “type” with “news” and “events” value, but the url is incorrect and the taxonomy is not shown.
Another problem of this solution (somewhat illustrated here: https://www.youtube.com/watch?v=a2uabma0ML4) is that the menu item is a “custom link” linked to the post type slug (eg /basket/), to which i’ve assigned elementor builder archive template, and not a “real” page, which imho is not ideal.

I’ve then tried making the static page (/basket/ is now a static page) and create the post type “events” and “news”, but to no avail.

Regardless of what i’ve tried, which may be confusing for the sake of this help request, what would be the best way to proceed? I’ve already asked practically everywhere, but to no avail.
Any consistent help would be greatly appreciated!

Use custom post type taxonomy between cpt slug and name

I’m building a site for a car dealership and I’ve created a CPT: Cars and a Custom Taxonomy: Brand

Each car has one brand (Obviously), but I want to display them like this:
dealership.com/cars/%brand%/%car-name%

I’m currently using the Custom Post Type UI plugin but I’m completely comfortable with code.

Also, I don’t see the option for taxonomies to show as an archive.
The only way they show up is dealership.com/brand/%brand-name% but dealership.com/brands throws a 404. There seems to not be an archive page for taxonomies 🙁

plugins – Want to build parent-child relationships between custom post types created with CPT UI

I’ve gone through similar queries from the past but couldn’t find a solution that works for me.

So I created 3 different custom post types with the CPT UI plugin. They are called ‘careers’, ‘vacancies’, ‘our-staff’, respectively.

What I want to achieve is set ‘careers’ as the parent, and both ‘vacancies’ and ‘our-staff’ as children of ‘careers’, so that the breadcrumb lists on the children pages dynamically show as follows:

Home > Careers > Vacancies

Home > Careers > Our Staff

In the CPT UI interface, hierarchical is set to ‘true’ for all 3 custom post types.

For the two intended children pages ‘vacancies’ and ‘our staff’, ‘Parent’ is set as ‘careers’.

However the breadcrumb lists on the intended children pages still show as

Home > Vacancies

Home > Our Staff

i.e. skipping the parent page.

When I try getting the parent page ID of the children pages, it shows as “0” meaning the parent page is not set as intended.

I’ve tried using the Add-Hierarchy-Parent-to-Post plugin, but no luck….

Would be grateful for any tips, including workarounds to get the result I am hoping for.

filters – ACF Relationship Previous Next links of CPT

I have a CPT for artworks with custom taxonomy for artists. Then I have another CPT for artists. The artist pages are basically the the page title (artist name) and a relationship field where you add the artist’s artwork from the artworks CPT where you can filter by the custom taxonomy (since there are 50+ artists and 100s of artworks).

Each artwork is its own page as mentioned. When you click on the artwork from an artist page, we want to have the option of going to the next or previous artwork based on the order displayed on the artist page as determined by the order you set from its relationship field.

I’ve tried many solutions but none have worked yet. The only way I even get a hint of success is by adding a ACF field to the artworks post type that selects the artist post type via a post object field. I was using THIS PAGE as my guide.

There seems to be an issue with the following code. I’m note sure how $current_post_id applies to the array_search. If I print_r $current_index nothing appears. Same goes for $prev_module and $next_module. However, if I print_r $module_ids the array appears as it should in the order I set on the Artist page in the Relationship field. $first_module and $last_module show the correct IDs too. I just can’t seem to get the current post ID to then determine next and previous.

// create empty array for module ids
$module_ids = array();
             
// loop through modules and add them to array
foreach( $modules as $module ) :
    $module_ids() = $module->ID;
endforeach;
             
// get the current index
$current_index = array_search( $current_post_id, $module_ids );
             
// find the prev/next items
$prev_module = $current_index - 1;
$next_module = $current_index + 1;
             
// find first and last modules
$first_module = $module_ids(0);
$last_module = end($module_ids);

custom post types – CPT EVENT – listing by month and filtering by category and month – form select option

I am creating custom post type eventlist filter form. There is two options: category and months.
Following this advice List events by month I got display event categories by month. Meaning…

January

  • Event post 1
  • Event post 2

February

  • Event post 1
  • Event post 2

etc.

Category choosing works smoothly. Problem comes up when user choose month. By default events are listed by month. How can I reorder events using form options? Is it possible solve using meta_query compare or do I need some other solution?

<form method="get" action="<?php the_permalink();?>" name="tapahtumalista">
<select class="form-select" name="kat">

<?php 
$terms = get_terms( array(
    'taxonomy'      => 'kategori_tapahtumat',
));


// SELECT OPTION CATEGORY
?>

    <option value="">Valitse kategoria</option>
    <?php 
    
    foreach ($terms as $term) { ?>
        <option value="<?php echo $term->slug; ?>" <?php if(isset($_GET('kat')) && $_GET('kat') == $term->slug) { echo 'selected="selected"'; }?>>
        <?php echo $term->name; ?></option>
    <?php } ?>
</select>

<?php  // SELECT OPTION MONTH ?>
<select class="form-select" name="kk">
    <option value="">Valitse kuukausi</option>
    <?php 
    for ($i = 1; $i <= 12; $i++){
    $month_name = date_i18n('F', mktime(0, 0, 0, $i, 1, 2011)); 
    $month = !empty( $_GET('kk') ) ? $_GET('kk') : 0;
    $selected = $month_name == $month;
    ?>
    <option value="<?php echo $month_name; ?>" 
    <?php if(isset($_GET('kk')) && !empty($_GET('kk')) == $selected) { echo 'selected="selected"'; }?>
    <?php $selected ?>> 
        <?php echo $month_name; ?>
    </option>
    
    <?php }?>
</select>
<input type="submit" name="" value="Valitse">
// Selected category from form option 
if($_GET('kat') && !empty($_GET('kat'))) {
    $selected_cat = $_GET('kat');
}

//Selected month from form option
if($_GET('kk') && !empty($_GET('kk'))) {
    $selected_month = $_GET('kk');  
}


$today = date('Ymd');
$m = get_the_time('m');

$args =  (
    'post_type'         => 'tapahtumat',
    'post_status'       => 'publish',
    'posts_per_page'    => - 1,
    'meta_key'          => 'aloituspaiva', //event start date
    'meta_value'        => $today,
    'orderby'           => 'meta_value',
    'value'             => $today,
    'meta_compare'      => '>=',
    'type'              => 'DATE',
    'order'             => 'ASC',
    'tax_query'         => (
        (
            'taxonomy'  => 'kategori_tapahtumat',
            'field'     => 'slug',
            'terms'     => $selected_cat, //category get from form 
        )
    ),
    'meta_query'        => (
        'relation'      => 'OR',
        (
            
            'month'     => $m,
            'value'     => $selected_month, // get from form possible?
            'compare'   => '=',
        )

    )
);
$query = new WP_Query($args);

// List events by month (default view) - using dboris solution

$all_events = ();

if($query->have_posts()) :
    while ($query->have_posts() ) : $query->the_post();
        $date = strtotime(get_post_meta( get_the_ID(), 'aloituspaiva', true ) );
        $month_year = date( "F", $date );
        $all_events( $month_year )() = $query->post;    
    endwhile;
    // Sorting events by month

    foreach ( $all_events as $month_year => $events) : ?>
        <?php echo '<br><br><strong>' . $month_year . '</strong><br>';  ?>

        <?php foreach ( $events as $event ) : ?>
            <?php echo $event->post_title . '<br>';?>
        <?php endforeach;?>
    <?php endforeach;
else :
    echo ('No results.');
endif;

wp_reset_postdata(); 

wp query – Display related CPT with custom taxonomy

I have two custom post types: “storefront_location” and “services”

These are linked by a custom taxonomy “location”

I am building a post template for “storefront_location” and would like to display a listing of the “services” posts associated with any given storefront.

What I’m trying to achieve:

A “storefront-location” post, London, is categorized with “london” (“location” taxonomy).
I would like that London “storefront-location” post to display all “services” which are also categorized with “london” (“location” taxonomy). Users could then click on each service to read about it, since these are post types.

I’m trying to get the taxonomy information of the current post (London) and use tax-query to find all the services that share the same taxonomy with that specific London post.

Note: this is for a WP_query filter in Elementor, so the extra code for the Elementor query is from their tutorial here.

I’m fairly new to this, so there might be a newbie problem here. I’ve been trying to figure this out from other code examples here on stack exchange. I’d appreciate any help!

add_action( 'elementor/query/my_filter', function( $query ) {
//get the storefront-location post's location
   $custom_terms = wp_get_post_terms($post->ID, 'location');

if( $custom_terms ){

    //hold tax query parameters
    $tax_query = array();


    // loop through locations and build a tax query
    foreach( $custom_terms as $custom_term ) {

        $tax_query() = array(
            'taxonomy' => 'location',
            'field' => 'slug',
            'terms' => $custom_term->slug,
        );

    }

    // put all the WP_Query args together
    $args = array( 'post_type' => 'services',
                    'posts_per_page' => -1,
                    'tax_query' => $tax_query );

    // finally run the query
    $loop = new WP_Query($args);

    if( $loop->have_posts() ) {

        while( $loop->have_posts() ) : $loop->the_post(); ?>

        <div class="listing-title"><?php the_title(); ?></div>     
        <?php endwhile;
    }

    wp_reset_query();

}
});

custom post types – Combine multiple CPT names to create valid permalinks

I have three different Custom Post Types:

  1. Company
  2. Employee
  3. Project

They are connected with ACF relationship fields so as the Company can have multiple Employees and each Employee can have a project attached. The get_field() function retrieves attached post objects to create some sort of relationship.

What I need to do is create three permalink structures for these CPT:

  1. For Companies: www.somepage.com/%company_name%
  2. For Employees: www.somepage.com/%company_name%/%employee_name%
  3. For Projects: www.somepage.com/%company_name%/%employee_name%/%project_name%

What I have already managed to do is to set permalink structure to them with this piece of code:

function dd_custom_permalinks($permalink, $post, $leavename) {
    $post_id = $post->ID;
    if(($post->post_type != 'project' && $post->post_type != 'employee' && $post->post_type != 'company') || empty($permalink) || in_array($post->post_status, array('draft', 'pending', 'auto-draft')))
        return $permalink;

    if (get_field("employees", $post->ID)) {
        $permalink = str_replace('%company%', $post->post_name, $permalink);
    } elseif (get_field("company", $post->ID)) {
        $permalink = str_replace('%company%', get_field("company", $post->ID)(0)->post_name, $permalink);
        $permalink = str_replace('%employee%', $post->post_name, $permalink);
    } elseif (get_field("employee", $post->ID)) {
        $employee= get_field("employee", $post->ID)(0);
        $company= get_field("company", $employee->ID)(0);
        $permalink = str_replace('%company%', $company->post_name, $permalink);
        $permalink = str_replace('%employee%', $employee->post_name, $permalink);
        $permalink = str_replace('%project%', $post->post_name, $permalink);
    }

    return $permalink;
}
add_filter('post_type_link', 'dd_custom_permalinks', 10, 3);

The problem is I cannot find a way to make them valid, as the structure always leads to Company (first part of the custom url structure). Probably I have to bind the further with the CPT query somehow?

I have also tried using custom rewrite rules, but I can’t understand how should this be done to be fair. Here’s what I got so far (not working):

function dd_custom_rewrite_rules() {
    add_rewrite_tag('%company%', '((^/)+)', 'company=');
    add_permastruct('company', '/%company%', false);
    add_rewrite_rule('^company/((^/)+)/((^/)+)/?','index.php?company=$matches(2)','top');

    add_rewrite_tag('%employee%', '((^/)+)', 'employee=');
    add_permastruct('employee', '/%company%/%employee%', false);
    add_rewrite_rule('^employee/((^/)+)/((^/)+)/?','index.php?employee=$matches(2)','top');
    
    add_rewrite_tag('%project%', '((^/)+)', 'project=');
    add_permastruct('project', '/%company%/%employee%/%project%', false);
    add_rewrite_rule('^project/((^/)+)/((^/)+)/?','index.php?project=$matches(2)','top');

}
add_action( 'init', 'dd_custom_rewrite_rules' );

Any ideas how (or maybe IF) can I get this to work properly?

plugins – Would a custom table make more sense than a CPT in this case?

I am building a “multi vendor” type plugin to extend Woocommerce. There will be two types of new user roles: Vendor, and Non-Profit Org.

Vendors can list their products on the site, and users can choose at the checkout page which “Non-Profit Organization” they would like to donate part of their purchase to.

Ultimately, I would like the site owner to be able to have a curated list of all transactions, meaning how much is going to the Non Profit, how much goes to the Vendor. Preferably in chosen increments (monthly, daily, by individual order).

What’s got me stuck is figuring out how to let the “Vendor” and “Non Profit Org” accounts VIEW their respective transactions as well.

I don’t know if I should make two custom post types (Vendor Orders, Non Profit Orders) and just list extra info as Post Meta, as well as finding out a way to make sure ONLY the user assigned to the role can view orders for that role (in other words, one non profit can’t see records of another non profit).

Or, I am wondering if it makes more sense to create a custom table, which lists all valuable information (amount going to vendor, amount going to non profit, etc…) and just write custom queries to list the information based on the current user ID.