• I would like to display the taxonomy term of the post type post besides the post type post title, separated by the “in” text string.

    There are two issues:

    1. only “array” is displayed instead of the term
    2. I don’t know how to code the “in” text string correctly, between the term and the title (they should be in the same row)

    Here is the (wrong) code in question:

    $output .= '<div>' . get_the_title() . '</div>'; in $output .= '<div>' . wp_get_post_terms( $post_id, $taxonomy = 'itemscategories') . '</div>';

    Embedded in this shortcode:

    function myprefix_custom_grid_shortcode( $atts ) {
    
        // Parse your shortcode settings with it's defaults
        $atts = shortcode_atts( array(
        
            'posts_per_page' => '-1',
            'term'           => ''
        ), $atts, 'myprefix_custom_grid' );
    $user_id = userpro_get_view_user( get_query_var('up_username') );
        // Extract shortcode atributes
        extract( $atts );
    
        // Define output var
        $output = '';
    
        
    
        // Define query
        $query_args = array(
        'author'=> $user_id,
            'post_type'      => 'items', // Change this to the type of post you want to show
            'posts_per_page' => $posts_per_page,
        );
    
        // Query by term if defined
        if ( $term ) {
    
            $query_args['tax_query'] = array(
                array(
                    'taxonomy' => 'category',
                    'field'    => 'ID',
                    'terms'    => $term,
                    
                ),
            );
    
        }
    
        // Query posts
        $custom_query = new WP_Query( $query_args );
    
        // Add content if we found posts via our query
        if ( $custom_query->have_posts() ) {
    
            // Open div wrapper around loop
            $output .= '<div>';
    
            // Loop through posts
            while ( $custom_query->have_posts() ) {
    
                // Sets up post data so you can use functions like get_the_title(), get_permalink(), etc
                $custom_query->the_post();
    
                // This is the output for your entry so what you want to do for each post.
                $output .= '<div>' . get_the_title() . '</div>'; in $output .= '<div>' . wp_get_post_terms( $post_id, $taxonomy = 'itemscategories') . '</div>';
    
            }
    
            // Close div wrapper around loop
            $output .= '</div>';
    
            // Restore data
            wp_reset_postdata();
    
        }
    
        // Return your shortcode output
        return $output;
    
    }
    add_shortcode( 'myprefix_custom_grid', 'myprefix_custom_grid_shortcode' );
Viewing 15 replies - 16 through 30 (of 97 total)
  • Thread Starter berry metal

    (@erikalleman)

    I have added the hidden field containing the embed url and have given it a parameter name as shown in the screenshot https://i.imgur.com/NaFDxLm.png can you tell me how to call this parameter beside the post title? and does it need to be declared, and where?

    Moderator bcworkz

    (@bcworkz)

    Confirming what you have already discovered, WP does not have a built-in way to relate different post types. Using a custom field to create a relationship is fine, but its permalink is not optimal because it takes up space with redundant information. Better would to be only store the slug or ID. ID is preferable, but not as user friendly.

    Anyway, first you need to get posts whose post meta has the current post’s slug or ID as its post meta value. Obviously get_the_ID() works well for the current post ID. If you need it’s slug do something like

    global $post;
    $slug = $post->post_name;

    You can get all posts with slug or ID as the meta value with get_posts(), passing as args the “post_type” and “meta_key” and “meta_value” values. An array of found posts is returned. You can loop through the array using foreach to output each object’s title after the main post title. You can wrap it within span tags so they can be styled differently than other text on the page.

    Thread Starter berry metal

    (@erikalleman)

    Thanks. May I ask for a snippet applied to my code?
    I will get lost if I had to write it.
    If I read it, I will learn it.

    Thread Starter berry metal

    (@erikalleman)

    Wait, I’ll try first! I will write if i failed.

    • This reply was modified 4 years, 7 months ago by berry metal.
    Thread Starter berry metal

    (@erikalleman)

    I came up with this code, which is probably a disgrace of a php code, illustrating my level in php:

    $output .= '<div>' . esc_html( get_the_title() ) . esc_html( gravity_embed_post_id() )( global $post;
    $slug = $post->post_name, 'Posted in: ', ', ' ) . '</div>';

    gravity_embed_post_id being the parameter that I defined for the “embed post ID”, there is such option in Gravity Forms.

    Thread Starter berry metal

    (@erikalleman)

    May I get some help with this?

    Thread Starter berry metal

    (@erikalleman)

    I corrected it into this:

    $output .= '<div>' . esc_html( get_the_title() ) . get_the_ID()( $gravity_embed_post_id, 'itemscategories', 'Posted in: ', ', ' ) . '</div>';

    Is it better?

    Thread Starter berry metal

    (@erikalleman)

    It returns white space only, and it breaks the layout of the profile page.

    Thread Starter berry metal

    (@erikalleman)

    I don’t see in your explanation the procedure of converting the ID into the linked post title…
    can you elaborate on that ?

    Thanks!

    Moderator bcworkz

    (@bcworkz)

    I like that you’re willing to learn and are ambitious enough to dive in and give it a try without having all the information. You will do well once you acquire some more skills ??

    I’m not sure I’ve correctly grasped the specifics of what you want enough to reliably produce working code. Yet I think I know enough to give you most of it. It may need some adjustment to be fully functional. Getting related posts that WP does not by default relate gets a little involved. To the point it’d be better to off load the heavy lifting to a function and only include the function call in the shortcode handler itself. The function declaration can go in the same file as the shortcode handler. This helps make the shortcode handler code clearer down the line should future maintenance be needed.

    So the handler code would just be something like this:

    $output .= '<div class="sc-post">' . esc_html( get_the_title());
    $output .= ' <span class="sc-related">Related: ' . esc_html( sc_get_related( get_the_ID())) . '</span></div>';

    The related titles have their own span so they can be styled differently than the main post’s title

    I’m not sure how you decided to store the related post meta value. I’ll assume ID since it’s a bit easier to code. Adjusting the code to use the post slug is not a huge change.

    // get a list of itemscategories post titles whose 'gravity_embed_id'
    // post meta value matches the passed post ID
    function sc_get_related( $post_id ) {
      $list = '';
      $items = get_posts([
        'post_type' => 'itemscategories',
        'meta_key' => 'gravity_embed_id',
        'meta_value_num' => $post_id,
      ]);
      if ( 0 != count( $items ) {  // avoids throwing PHP warnings if no items found
        foreach ( $items as $item ) {
          $list .= $item->post_title . ' ';
        }
      }
      return $list;
    }

    If you want a separator between titles besides a space it’s better to push all the titles into an array for that purpose. When all titles are collected, use implode() to construct a list with a separator string. This avoids having a dangling separator at the end of the list. For example, a foreach statement for $color with $list .= $color . '|'; would yield “red|blue|green|” with an unwanted ‘|’ at the end.

    If instead we did $title[] = $color; in the foreach loop, then when finished do $list = implode('|', $title ); we get “red|blue|green”.

    Thread Starter berry metal

    (@erikalleman)

    Thanks!
    I was playing with it, the issue is that the “parent post” titles are not getting displayed.
    You called them related posts, but they are parent posts.
    You might have misunderstood something.

    Let me tell you what is happening on my site:

    The setup is like this:
    I have default posts, like all normal blogs.
    But I am fetching post type posts within these default posts, they are submitted dynamically by using the same form defined in the default post template, and after I approve the submitted post type posts, I have to assign them manually to their taxonomy (itemscategories) name, more exactly to that taxonomy name that is identic with the deafult post title where the named post type post is supposed to be displayed, because the post type posts are displayed with a grid that uses a dynamic query by matching the default post titles with the post type post taxonomy names in order to show the right post type posts in each default post.

    (I must call them “post type post” and “default post”, otherwise there might be confusion, so there are 2 kinds of posts, the default posts (post type:post) are the parent posts, and the post type posts (post type: item) are the children posts that are fetched in the parent posts by the grid using the dynamic query.)

    I did not manage yet to automate the post type post category assignment by Gravity forms (basically Gravity forms should look at the parent posts title [in the post where the form was embedded, same post as where the child post will be fetched], copy that string and give it as taxonomy name to the child post, automatically – is this possible?), so I have to peek into the created Gravity Forms entry and see the “embed url” of the form entry, and assign the post type post manually to the taxonomy name that matches the embed url (or default post title) name. And I do just that: I assign its taxonomy name manually before I approve the child post.

    And these parent post titles (with link) are that we are trying to display alongside the child post titles.

    The child post titles already are displayed just fine, using the code provided by you.
    But the parent post titles are not getting displayed.

    And I also got confused:
    – should I assign the field to the feed that creates the post, or to the form (which I suppose is the same as to the entry)?

    Because Gravity Forms creates the posts from the entries via a “feed”, and I think that those entries are also a separate post type.

    However I tried to assign a custom field with the value of the embed post ID (the post where the child post is embed) to the feed, and it returns white space only.

    Finally I assigned the same field to the form itself, and now the code you gave displays some old child posts titles alongside with the 3 newest child post titles.

    And I think this is because you misunderstood the situation.
    That’s why I described the circumstances above just to make sure.

    I corrected the post type to “items” in the function code. “itemscategories” is the taxonomy name of the “items” post type.

    Which post type’s ID is the “get_the_ID” of the handler code is getting?
    I think it’s getting the id of the “items” post type. That seems to be ok.

    And then it converts the number into the $post_id. Is this number converted into the parent post’s ID or into the hild post’s id?

    (is the child post ID called “$item_id” and the parent post ID “$post_id”? )

    Because that number must be converted to (or accounted as) the parent post id.

    (Well now it’s to easy to understand when I read your code.)

    Then the function code goes on and wants to display post titles of the post type “items” but that’s wrong, we need post titles of the post type “post”, the default post type, because those are the parent posts whose titles we need alongside the child post titles.

    I think the issue is that the ‘gravity_embed_id’
    // post meta value provided by Gravity Forms is accounted by the code as the ID of the child posts, not as the ID of the parent posts, of the posts where the form was embedded, as it should be.
    And that’s what we need. It just need to be converted into titles with links.

    So I tried to change this part of the function code

    if ( 0 != count( $items )) {  // avoids throwing PHP warnings if no items found
        foreach ( $items as $item ) {
          $list .= $item->post_title . ' ';

    into this

    if ( 0 != count( $post )) {  // avoids throwing PHP warnings if no items found
        foreach ( $posts as $post ) {
          $list .= $post->post_title . ' ';

    but it returns only whitespace.

    So the numeric value provided by the Gravity field is the ID of the post type “post”, not “items”.

    Even though that field belongs to the post type “items” (child post), it returns the ID of the post type “post”, the parent post.

    My correction was not successful.

    How to correct the function code so that the obtained numeric value will be accounted as ID of the post type “post”, and so that the function will finally derive and output the post titles of the post type “post” and not “items”?

    Here are the 2 screenshots of my current setup:

    flameshot_screenshot

    flameshot_screenshot

    So what is called parameter on the screenshot, you passed as “meta key”. I hope that is right…

    I checked the option “Allow field to be populated dynamically”, but I don’t know if they are actually automaticaly populated without adding a hook.

    But I think they are because the ID of the parent post is properly displayed in the form entry:

    flameshot_screenshot

    So I don’t think that I need to use a hook like this:
    https://docs.gravityforms.com/using-dynamic-population/#hooks

    Thanks! And thanks for telling extra advice that I did not even ask about. Have a nice evening, #stayhome.

    • This reply was modified 4 years, 7 months ago by berry metal.
    • This reply was modified 4 years, 7 months ago by berry metal.
    • This reply was modified 4 years, 7 months ago by berry metal.
    • This reply was modified 4 years, 7 months ago by berry metal.
    • This reply was modified 4 years, 7 months ago by berry metal.
    • This reply was modified 4 years, 7 months ago by berry metal.
    • This reply was modified 4 years, 7 months ago by berry metal.
    Moderator bcworkz

    (@bcworkz)

    Wow! That is quite the post scheme. I really appreciate the thorough explanation, but I’m afraid it’s left me more confused than ever ?? I should have asked for specifically what I needed to get the right output before going off on a coding exercise.

    get_the_ID() returns the post ID of whatever the current post is in the main loop. It doesn’t care what post type it is. If get_the_title() is returning the right post’s title, then get_the_ID() is getting the right ID. They work in the same way internally.

    Let’s put $items and $item back and not use $posts and $post. It really can be any variable we want, except $post. $post is easily confused with a global value and should be avoided unless the global is really being use. It can be $foobars and $foobar for all that matters, just not $post. The global is out of scope so $post is actually OK, but it can be confusing. If $items/$item is confusing because of the “item” post type, maybe use $related/$relation or something? Or $blogs/$blog? Anything but $post please ??

    We’re getting related post type “post” titles to go after the main title, is that right? If so use the arg 'post_type' => 'post'; in the query.

    And if I understood correctly, the posts that are related all have an ‘itemscategory` taxonomy term assigned that matches the title of the main post? Matching titles and term names is not that reliable because they are not necessarily unique and contain spaces. Can we relate post slugs to term slugs instead? That would be much more reliable.

    If that is correct, the changes needed are difficult to describe. I can rewrite what we have once you confirm this is correct.

    Thread Starter berry metal

    (@erikalleman)

    This is the grid filter wih the dynamic query that does the matching:

    function items_query_args($query_args, $grid_name ) {
        if ($grid_name == 'items_grid') {
    
            $query_args['tax_query'] = array(
            array(
                'taxonomy' => 'itemscategories',
                'field'    => 'slug',
                'terms' => get_post_field( 'post_name' ),
            ),
        );
        $query_args['post_type'] = 'items';
        
        }
    
        return $query_args;
    
    }
    add_filter('tg_wp_query_args', 'items_query_args', 10, 2);

    Is this query matching the slugs of the taxonomy names in the “items” post type with the parent post (default post, post type:post) slugs or with the parent post titles? I think with the slugs.

    So now I hope you know what is exactly matched. If you as me, I don’t remember exactly, but when I post, I just try both slug and title, and one of them works. That’s because I cannot remember everything about my site. And my code reading accuracy is not very high yet.

    Yes $items confused me because of the post type with the same name.

    So I corrected the query from “items” to “post”, and now I use the “thing/things” strings instead of “item/items”, like this:

    function sc_get_related( $post_id ) {
      $list = '';
      $things = get_posts([
        'post_type' => 'post',
        'meta_key' => 'gravity_embed_id',
        'meta_value_num' => $post_id,
      ]);
      if ( 0 != count( $things )) {  // avoids throwing PHP warnings if no items found
        foreach ( $things as $thing ) {
          $list .= $thing->post_title . ' ';
        }
      }
      return $list;
    }

    It only returns white space.

    And yes I can confirm that the slug of the “itemscategories” taxonomy term is matched against the parent default post (post type:post) title… or slug…. I am not sure which. But you can see what is matched in the query filter that I posted….My reading accuracy is not good enough to determine it with a high precision.

    If the query filter code is not the right one, please correct it to match post slugs with term slugs. (default post title slugs with “items” post type “itemscategories” taxonomy slugs) But I think it was corrected already.

    So yes I confirmed and I corrected the query in your function code from “items” to “post” post type.

    Since the titles we want to show alongside the children post titles are the parent post titles. The numerical value Gravity Forms is getting is the ID of the post where the guest post submit form (and the submitted children posts) are embed. So the ID the form is grabbing is that of the “post” post type.

    Thanks for helping with this.

    • This reply was modified 4 years, 7 months ago by berry metal.
    • This reply was modified 4 years, 7 months ago by berry metal.
    • This reply was modified 4 years, 7 months ago by berry metal.
    Moderator bcworkz

    (@bcworkz)

    Yeah, the name/slug referencing is confusing. I forget after a while and have to constantly double check myself. “post_name” for any post type is indeed its slug. But for any taxonomy term, “name” is the equivalent of “post_title” and a term’s slug is actually “slug”.

    I almost understand now, but I’m still not 100% sure. The following returns “post” post type titles of posts that have a certain “itemscategories” term assigned. I’m getting that term slug from the current “items” post’s slug, assuming they are the same. The $output part remains unchanged. The function to replace my previous version:

    function sc_get_related( $item_id ) {
      $list = '';
      $things = get_posts([
        'post_type' => 'post',
        'tax_query' => [[
            'taxonomy' => 'itemscategories',
            'field'    => 'slug',
            'terms' => get_post( $item_id )->post_name,
         ],],
      ]);
      if ( 0 != count( $things )) {  // avoids throwing PHP warnings if no items found
        foreach ( $things as $thing ) {
          $list .= $thing->post_title . ' ';
        }
      }
      return $list;
    }
    Thread Starter berry metal

    (@erikalleman)

    Thanks!
    The new function code still returns whitespace.

    The following returns “post” post type titles of posts that have a certain “itemscategories” term assigned.

    That is not correct, the post type “post” post titles we are looking after, they don’t have an “itemscategories” taxonomy. Their child posts (the posts fetched in them) have that taxonomy.

    But their taxonomy is irrelevant.
    The numerical value obtained by gravity forms (by checking in which post is the form embedded in) is the id of the post type “post”, and we simply need to display the title corresponding to that ID. So the taxonomy is irrelevant.

    The taxonomy is only relevant to the post type “items”, because the first title we want to display is the child posts title. But that is already done, they show just fine. ($output .= '<div class="sc-post">' . esc_html( get_the_title());)

    But in your new function code there is no meta key present.
    This parameter: $gravity_embed_id is a numerical value obtained by Gravity Forms, and that simply need to be converted into the post type “post” title.

    So all you have to code is to output the title corresponding to the $gravity_embed_id parameter.

    However this parameter is not mentioned or declared anywhere in my functions.php.

    It is only defined in my Gravity Forms settings as you see it on my screenshots.
    And the automatic population of this field works, because the IDs are returned properly in the form entries. The child posts are generated from these form entries. However I don’t think we need anything to do with the child posts anymore. Their titles are already displayed. It is the form that detects the parent posts ID, not the child post.

    Thanks! I hope now it’s clear. If not, just tell me what is unclear…

    If I am wrong about this, you hopefully could correct me, you have seen my latest screenshots sent about my Gravity Forms setup.

    This is the important thing here, that ve have a parameter passed over by Gravity Forms, that is a “post” post ID, and we need to show its linked title.

    Gravity Forms just let me assign a parameter name to the numerical value (“post” ID) obtained. How to pass that parameter correctly to your function, I don’t know…

    • This reply was modified 4 years, 7 months ago by berry metal.
Viewing 15 replies - 16 through 30 (of 97 total)
  • The topic ‘How do I display the taxonomy term alongside the post type post title?’ is closed to new replies.