最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

posts - Function is printing twice - any suggestions?

programmeradmin2浏览0评论

My function is returning the results correctly, but for whatever reason it is returning them twice. Any suggestions? It's for a shortcode that queries and lists custom post types matching custom taxonomies.

function useful_tools_list($atts){
    $atts = shortcode_atts(
        array(
            'type'      => '',
            'desc'      => '',
            'ul'        => '',
            'li'        => '',
            'merge_tag' => '',
            'value'     => '',
            'tags'      => '',
         ), 
        $atts
    );
    
    $results = '';
    if (($atts['merge_tag']) && (!preg_match('/\b'.$atts['value'].'\b/', $atts['merge_tag']))) {
        $results .= '';
    } else {
        $all_terms = get_terms('types');

        foreach($all_terms as $term) {
            wp_reset_query();
            if (($atts['type']) && ($atts['type'] != "")) {
                $args = array('post_type' => 'useful-tools',
                    'tax_query' => array(
                        array(
                            'taxonomy' => 'types',
                            'field' => 'slug',
                            'terms' => $term->slug,
                        ),
                    ),
                    'types' => $atts['type'],
                    'tag' => $atts['tags'],
                 );
            } else {
                $args = array('post_type' => 'useful-tools',
                    'tax_query' => array(
                        array(
                            'taxonomy' => 'types',
                            'field' => 'slug',
                            'terms' => $term->slug,
                        ),
                    ),
                    'tag' => $atts['tags'],
                 );
            }

            $loop = new WP_Query($args);
            if($loop->have_posts()) {
                if ((!$atts['type']) || ($atts['type'] == "")) {
                    $results .= '<h2>'.$term->name.'</h2>';
                }
                if (($atts['ul']) && ($atts['ul'] == "true")) {
                    $results .= '<ul class="tools-type-ul">';
                }
                while($loop->have_posts()) : $loop->the_post();
                $postID = get_the_ID();
                $desc = '';
                $actualDesc = get_post_meta($postID, '_post_desc', true);
                if ($atts['desc'] == 'true' && $actualDesc != '') {
                    $desc = ' - '.get_post_meta($postID, '_post_desc', true);
                }
                if (($atts['li']) && ($atts['li'] == "true")) {
                    $results .= '<li><a href="'.get_post_meta($postID, '_post_url', true).'">'.get_the_title().'</a>'.$desc.'</li>';
                } else {
                    $results .= '<a href="'.get_post_meta($postID, '_post_url', true).'">'.get_the_title().'</a>'.$desc.'<br>';
                }
                endwhile;
                if (($atts['ul']) && ($atts['ul'] == "true")) {
                    $results .= '</ul>';
                }
            }
        }
    }
    return $results;
}
add_shortcode('useful-tools', 'useful_tools_list');

EDIT: Also tried this, which also outputs the correct results, but outputs twice.

$all_terms = get_terms('useful-tools');
        
        foreach($all_terms as $term) {
            wp_reset_query();
            if (($atts['type']) && ($atts['type'] != "")) {
                $args = array('post_type' => 'useful-tools',
                    'types' => $atts['type'],
                    'tag' => $atts['tags'],
                 );
                
            }

My function is returning the results correctly, but for whatever reason it is returning them twice. Any suggestions? It's for a shortcode that queries and lists custom post types matching custom taxonomies.

function useful_tools_list($atts){
    $atts = shortcode_atts(
        array(
            'type'      => '',
            'desc'      => '',
            'ul'        => '',
            'li'        => '',
            'merge_tag' => '',
            'value'     => '',
            'tags'      => '',
         ), 
        $atts
    );
    
    $results = '';
    if (($atts['merge_tag']) && (!preg_match('/\b'.$atts['value'].'\b/', $atts['merge_tag']))) {
        $results .= '';
    } else {
        $all_terms = get_terms('types');

        foreach($all_terms as $term) {
            wp_reset_query();
            if (($atts['type']) && ($atts['type'] != "")) {
                $args = array('post_type' => 'useful-tools',
                    'tax_query' => array(
                        array(
                            'taxonomy' => 'types',
                            'field' => 'slug',
                            'terms' => $term->slug,
                        ),
                    ),
                    'types' => $atts['type'],
                    'tag' => $atts['tags'],
                 );
            } else {
                $args = array('post_type' => 'useful-tools',
                    'tax_query' => array(
                        array(
                            'taxonomy' => 'types',
                            'field' => 'slug',
                            'terms' => $term->slug,
                        ),
                    ),
                    'tag' => $atts['tags'],
                 );
            }

            $loop = new WP_Query($args);
            if($loop->have_posts()) {
                if ((!$atts['type']) || ($atts['type'] == "")) {
                    $results .= '<h2>'.$term->name.'</h2>';
                }
                if (($atts['ul']) && ($atts['ul'] == "true")) {
                    $results .= '<ul class="tools-type-ul">';
                }
                while($loop->have_posts()) : $loop->the_post();
                $postID = get_the_ID();
                $desc = '';
                $actualDesc = get_post_meta($postID, '_post_desc', true);
                if ($atts['desc'] == 'true' && $actualDesc != '') {
                    $desc = ' - '.get_post_meta($postID, '_post_desc', true);
                }
                if (($atts['li']) && ($atts['li'] == "true")) {
                    $results .= '<li><a href="'.get_post_meta($postID, '_post_url', true).'">'.get_the_title().'</a>'.$desc.'</li>';
                } else {
                    $results .= '<a href="'.get_post_meta($postID, '_post_url', true).'">'.get_the_title().'</a>'.$desc.'<br>';
                }
                endwhile;
                if (($atts['ul']) && ($atts['ul'] == "true")) {
                    $results .= '</ul>';
                }
            }
        }
    }
    return $results;
}
add_shortcode('useful-tools', 'useful_tools_list');

EDIT: Also tried this, which also outputs the correct results, but outputs twice.

$all_terms = get_terms('useful-tools');
        
        foreach($all_terms as $term) {
            wp_reset_query();
            if (($atts['type']) && ($atts['type'] != "")) {
                $args = array('post_type' => 'useful-tools',
                    'types' => $atts['type'],
                    'tag' => $atts['tags'],
                 );
                
            }
Share Improve this question edited Aug 17, 2020 at 17:04 Michael asked Aug 17, 2020 at 15:20 MichaelMichael 2811 silver badge14 bronze badges 8
  • Your post you're using this on wouldn't happen to have 2 terms? e.g. 2 categories or a category and a tag? How are you using it? – Tom J Nowell Commented Aug 17, 2020 at 15:58
  • A category and a tag, yes. – Michael Commented Aug 17, 2020 at 16:23
  • Try outputting the contents of $all_terms to screen so you can see how many instances it has in it. As Tom suggests, you may have more terms in your results than you think. If there is more than one instance, you will get more than one foreach loop. – t2pe Commented Aug 17, 2020 at 16:51
  • $all_terms only outputs once. It's definitely in the query as $args outputs twice before looping. I have a custom post type called "useful-tools," which has a custom taxonomy called "types", and tags. – Michael Commented Aug 17, 2020 at 16:57
  • I only have 3 posts with different types and tags for testing. My shortcode: [useful-tools type="videos" ul="true" li="true" tags="mental-health"] should only output a single post, which it does, but outputs it twice. – Michael Commented Aug 17, 2020 at 17:06
 |  Show 3 more comments

1 Answer 1

Reset to default 0

After realizing that I was trying to use the same shortcode for two different types of lists, it was easier to just separate them in two different shortcodes.

To list all posts and break them up by type:

/**
 * Shortcode for listing all tools matching tags
 * Usage: [useful-tools-all desc="true" li="true" tags="health, teens"]
 * Alternative PHP Usage: useful_tools_listall(array(desc => 'true', li => 'true', 'tags' => 'health, teens' ))
 */
function useful_tools_listall($atts){
    $atts = shortcode_atts(
        array(
            'desc'      => '',
            'li'        => '',
            'tags'      => '',
         ), 
        $atts
    );
    
    $results = '';
    $all_terms = get_terms('types');

    foreach($all_terms as $term) {
        wp_reset_query();

        $args = array('post_type' => 'useful-tools',
            'tax_query' => array(
                array(
                    'taxonomy' => 'types',
                    'field' => 'slug',
                    'terms' => $term->slug,
                ),
            ),
            'tag' => $atts['tags'],
         );

        $loop = new WP_Query($args);
        if($loop->have_posts()) {
            $results .= '<h2>'.$term->name.'</h2>';
            if (($atts['li']) && ($atts['li'] == "true")) {
                $results .= '<ul class="tools-type-ul">';
            }
            while($loop->have_posts()) : $loop->the_post();

                $postID = get_the_ID();
                $desc = '';
                $actualDesc = get_post_meta($postID, '_post_desc', true);
                if ($atts['desc'] == 'true' && $actualDesc != '') {
                    $desc = ' - '.get_post_meta($postID, '_post_desc', true);
                }
                if (($atts['li']) && ($atts['li'] == "true")) {
                    $results .= '<li><a href="'.get_post_meta($postID, '_post_url', true).'">'.get_the_title().'</a>'.$desc.'</li>';
                } else {
                    $results .= '<a href="'.get_post_meta($postID, '_post_url', true).'">'.get_the_title().'</a>'.$desc.'<br>';
                }

            endwhile;
            if (($atts['li']) && ($atts['li'] == "true")) {
                $results .= '</ul>';
            }
        }
    }
    return $results;
}
add_shortcode('useful-tools-all', 'useful_tools_listall');

And to list posts without breaking them up by type (and without repeating them for each type):

/**
 * Shortcode for listing tools by type and tags
 * Usage: [useful-tools-only type="documents" desc="true" ul="" li="true" merge_tag="{:3:value}" value="B" tags="health, teens"]
 * Param "type" must be the taxonomy's exact slug name, not the display name, and it is case-sensitive
 * Params "ul" and "li" set to "true" if you want to include <ul> and <li> tags. 
 * Keep "ul" empty and set "li" true when using in Gravity Form confirmation.
 * Params "merge_tag" and "value" are for conditional components in Gravity Form confirmation.
 */
function useful_tools_listonly($atts){
    $atts = shortcode_atts(
        array(
            'type'      => '',
            'desc'      => '',
            'ul'        => '',
            'li'        => '',
            'merge_tag' => '',
            'value'     => '',
            'tags'      => '',
         ), 
        $atts
    );
    
    $results = '';
    if (($atts['merge_tag']) && (!preg_match('/\b'.$atts['value'].'\b/', $atts['merge_tag']))) {
        $results .= '';
    } else {
        
        $myposts = get_posts(
            array(
                'showposts' => -1,
                'post_type' => 'useful-tools',
                'tax_query' => array(
                    array(
                        'taxonomy' => 'types',
                        'field' => 'slug',
                        'terms' => $atts['type'],
                    )
                ),
                'tag' => $atts['tags'],
            )
        );

        if ((!$atts['type']) || ($atts['type'] == "")) {
            $results .= '<h2>'.$atts['type'].'</h2>';
        }
        if (($atts['ul']) && ($atts['ul'] == "true")) {
            $results .= '<ul class="tools-type-ul">';
        }
        
        foreach ($myposts as $mypost) {
            
            $postID = $mypost->ID;
            $desc = '';
            $actualDesc = get_post_meta($postID, '_post_desc', true);
            if ($atts['desc'] == 'true' && $actualDesc != '') {
                $desc = ' - '.get_post_meta($postID, '_post_desc', true);
            }
            if (($atts['li']) && ($atts['li'] == "true")) {
                $results .= '<li><a href="'.get_post_meta($postID, '_post_url', true).'">'.$mypost->post_title.'</a>'.$desc.'</li>';
            } else {
                $results .= '<a href="'.get_post_meta($postID, '_post_url', true).'">'.$mypost->post_title.'</a>'.$desc.'<br>';
            }
            
        }
        
        if (($atts['ul']) && ($atts['ul'] == "true")) {
            $results .= '</ul>';
        }
    }
    return $results;
}
add_shortcode('useful-tools-only', 'useful_tools_listonly');

Thanks for your help @t2pe and @Tom.

发布评论

评论列表(0)

  1. 暂无评论