我编写了以下插件,它将字段添加到Media/附件条目中,并在一个短代码中返回所有信息。然而,随着可用条目的增加,此解决方案的工作速度相当缓慢。
我知道问题在于时间循环。20000只是一个很高的数字,以便搜索所有的帖子。但是,为了了解我试图实现的目标,我包含了整个代码:
defined( 'ABSPATH' ) or die( 'Are you ok?' );
/** ----- ADD FIELDS IN MEDIA LIBRARY ----- **/
function additionalMediaFields( $form_fields, $post ) {
$form_fields['copyright_author'] = array(
'label' => '© Autor',
'input' => 'text',
'value' => get_post_meta( $post->ID, 'copyright_author', true ),
);
$form_fields['copyright_description'] = array(
'label' => '© Beschreibung',
'input' => 'text',
'value' => get_post_meta( $post->ID, 'copyright_description', true ),
);
$form_fields['copyright_website'] = array(
'label' => '© Website',
'input' => 'text',
'value' => get_post_meta( $post->ID, 'copyright_website', true ),
);
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'additionalMediaFields', 10, 2 );
function storeAdditionalMediaFields( $post, $attachment ) {
if( isset( $attachment['copyright_author'] ) )
update_post_meta( $post['ID'], 'copyright_author', $attachment['copyright_author'] );
if( isset( $attachment['copyright_description'] ) )
update_post_meta( $post['ID'], 'copyright_description', $attachment['copyright_description'] );
if( isset( $attachment['copyright_website'] ) )
update_post_meta( $post['ID'], 'copyright_website', $attachment['copyright_website'] );
return $post;
}
add_filter( 'attachment_fields_to_save', 'storeAdditionalMediaFields', 10, 2 );
/** ----- SHOW THEM IN ONE SHORTCODE ----- **/
function listAllCopyrightInformation ($atts, $content = null) {
$i = 1;
while ( $i<=20000 ) {
$copyrightAuthor = get_post_meta($i, 'copyright_author', true );
$copyrightDescription = get_post_meta($i, 'copyright_description', true );
$copyrightWebsite = get_post_meta($i, 'copyright_website', true );
if ( !empty($copyrightAuthor)) {
if( !empty($copyrightDescription)) {
$CopyrightEntries .= $copyrightDescription . ': ';
}
$CopyrightEntries .= '© ';
$CopyrightEntries .= $copyrightAuthor;
if( !empty($copyrightWebsite)) {
$CopyrightEntries .= ' / ' . get_post_meta($i, 'copyright_website', true) . ' || ';
}
}
$i++;
}
$CopyrightReturn = substr($CopyrightEntries, 0, -8);
return $CopyrightReturn;
}
add_shortcode("show-all-copyrights", "listAllCopyrightInformation");提前谢谢。我很感激你的努力!
发布于 2020-07-01 21:14:13
如果在获取post元数据时不需要担心WordPress过滤器,那么您可能只需使用单个SQL语句并迭代结果,而不是依赖WordPress从数据库中获取值,因为这是20,000个sql语句,加上缓存所有数据的内存(当您为post获取post元数据时,WordPress会在幕后这样做)。
https://codereview.stackexchange.com/questions/234268
复制相似问题