简体   繁体   中英

Add custom field from plugin to joomla article loop

I created 3 custom fields for my joomla com_content articles like described in this tutorial: https://docs.joomla.org/Adding_custom_fields_to_core_components_using_a_plugin/de

Now i need to create an overview over all articles inside a category (43) and show these custom fields inside a joomla query.

My actual joomla query inside the template file override for articles:

        <?php 
            $catId = 43;
            $query = "SELECT * FROM #__content WHERE catid ='" . $catId . "'";
            $db = JFactory::getDBO();
            $db->setQuery($query); 
            $articles = $db->loadObjectList(); 
            foreach($articles as $article){
                echo 'ID: ' . $article->id;
                echo '<br />';
                echo 'Name: ' . $article->title;
                echo '<br />';
                echo '<a href="' . JRoute::_('index.php?option=com_content&view=article&id='.$article->id) . '">Link</a>';
                echo '<br /><br />';
            }
        ?>

Custom fields can be added to an article output with:

$this->params->get('custom_field_1');

But this is not working inside the loop. How can I add a custom field with the name custom_field_1 to this loop?

You should use method onContentPrepare of a content plugin, the same you used to add field in form :

public function onContentPrepare($context, &$row, $params, $page = 0){

    if ( JFactory::getApplication()->getTemplate() !== 'your_template_name' ){
        return;
    }

    $catId = 43;
    $query = "SELECT * FROM #__content WHERE catid ='" . $catId . "'";
    $db = JFactory::getDBO();
    $db->setQuery($query); 
    $row->articles = $db->loadObjectList(); 

}

Now in your item you've got a field articles with the list of all articles of category 43.

In your view, you'll be able to use $this->item->articles to retrieve this list.

You can try below code within loop-

<?php 
$attribs = json_decode($article->attribs); 
echo $attribs->custom_field_1; 
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM