如何在帖子中的第2段后显示Wordpress自定义字段
问题描述:
am using genesis framework. used this code in functions.php file. but displayed data in a table format at the end of post only. But i want to display data after Nth paragraph in a post only.
function add_product_spec_to_content($content) {
if(get_field('befestigung') || get_field('gurtsystem') || get_field('gruppe') || get_field('typ') || get_field('amazon') || get_field('bezug') || get_field('gewicht')) { $content = $content . '<table id="product-specification" cellspacing="0" border="0" style="border-collapse:collapse;"><tbody>'; }
if(get_field('befestigung')) { $content = $content . '<tr><td>Befestigung</td><td>' . get_field('befestigung') . '</td></tr>'; }
if(get_field('gurtsystem')) { $content = $content . '<tr><td>Gurtsystem</td><td>' . get_field('gurtsystem') . '</td></tr>'; }
if(get_field('bezug')) { $content = $content . '<tr><td>Bezug</td><td>' . get_field('bezug') . '</td></tr>'; }
if(get_field('gruppe')) { $content = $content . '<tr><td>Gruppe</td><td>' . get_field('gruppe') . '</td></tr>'; }
if(get_field('typ')) { $content = $content . '<tr><td>Typ</td><td>' . get_field('typ') . '</td></tr>'; }
if(get_field('gewicht')) { $content = $content . '<tr><td>Gewicht</td><td>' . get_field('gewicht') . ' kg</td></tr>'; }
if(get_field('amazon')) { $content = $content . '<tr><td>Preis</td><td>' . get_field('amazon') . '</td></tr>'; }
if(get_field('befestigung') || get_field('gurtsystem') || get_field('gruppe') || get_field('typ') || get_field('amazon') || get_field('bezug') || get_field('gewicht')) { $content = $content . '</tbody></table>'; }
return $content; } add_filter( 'the_content', 'add_product_spec_to_content', 1150 );
答
You can create a shortcode for this und place it where you want:
function sc_my_table( $atts ) {
$fields = array(
'befestigung' => 'Befestigung',
'gurtsystem' => 'Gurtsystem',
'bezug' => 'Bezug',
'gruppe' => 'Gruppe',
'typ' => 'Typ',
'gewicht' => 'Gewicht',
'amazon' => 'Preis',
);
$table_open = false;
$content = '';
foreach ( $fields as $field => $name ) {
if ( $value = get_field( $field ) ) {
if ( ! $table_open ) {
$content .= '<table id="product-specification" cellspacing="0" border="0" style="border-collapse:collapse;"><tbody>';
$table_open = true;
}
$content .= '<tr><td>'. $name .'</td><td>' . $value . '</td></tr>';
}
}
if ( $table_open ) {
$content .= '</tbody></table>';
}
return $content;
}
add_shortcode('my-table', 'sc_my_table');
Then use [my-table]
in text editor at the desired place.
Reference: add_shortcode()