I'm always down to learn better ways of doing thing and I wanted to see if I can get an input from the community to see if there is a way that I can improve this function:
function pardot_dashboard_query()
{
$args = [
's' => '<!-- wp:acf/pardot-form ',
'sentence' => 1,
'post_type' => [
'post',
'page'
],
];
$pardot_posts = get_posts($args);
if (!$pardot_posts) {
echo 'There are no active Pardot Forms.';
return;
}
echo '<p>The Pardot Form is active on the following pages/posts:</p>'; ?>
<ul>
<?php foreach ($pardot_posts as $post): ?>
<li><a href="<?= $post->guid ?>"><?= $post->post_title ?: 'No title available' ?><?= ' (' . ucfirst($post->post_type) . ')' ?></a></li>
<?php endforeach; ?>
</ul>
<?php
}
If there are other means of outputs and or ways to shrink it down - All help will be appreciated!
1 Answer 1
I generally don't advocate for printing any content from within a function, but I'll not dwell on this because it is a somewhat common practice for WordPressers.
- Name your function to clearly express what it does. Please greater importance on clarity than brevity.
- declare the return value as
void
to help you and your IDE to better understand the function's behavior. - avoid single-use variable declarations unless they are valuably self-documenting.
- I don't see you using excessive spacing like many WP devs, so kudos for that.
- I prefer curly brace syntax for language construct looping. I don't personally find the verbose loop end to be valuable.
- use
printf()
andsprintf()
to elegantly marry variables and expressions into a template string. This is easier to read than a bunch of concatenation and interpolation. - I prefer not to jump in and out of php tags, so I'll demonstrate staying inside of PHP the whole time.
- I'm not sold on that
href
value being legit. Is that value actually a valid url?
Code:
function printPardotDashboardItems(): void
{
$pardot_posts = get_posts([
's' => '<!-- wp:acf/pardot-form ',
'sentence' => 1,
'post_type' => [
'post',
'page'
],
]);
if (!$pardot_posts) {
echo '<p>There are no active Pardot Forms.</p>';
} else {
$items = [];
foreach ($pardot_posts as $post) {
$items[] = sprintf(
'<li><a href="%s">%s (%s)</a></li>',
$post->guid,
$post->post_title ?: 'No title available',
ucfirst($post->post_type)
);
}
printf(
'<p>The Pardot Form is active on the following pages/posts:</p><ul>%s</ul>',
implode("\n", $items)
);
}
}
-
\$\begingroup\$ This works flawlessly! Thanks @mickmackusa, I learned something new with this technique - Surprisingly, the href actually does come back as an accurate return. \$\endgroup\$Glider– Glider2021年09月09日 12:08:23 +00:00Commented Sep 9, 2021 at 12:08