Displaying images in atom feed - feed

I have problems with displaying images in atom file. It doesn't include images in feed in google reader, opera or firefox.
As a starting point I did everything like in Listing 6. at [An overview of the Atom 1.0 Syndication Format] But it doesn't work.
Update
It is not problem with hotlink protected images. Described here: How to display item photo in atom feed?
Later I changed feed according to description posted here.
I added:
<media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="path_to_image.jpg" />
But still it doesn't work

I had the same problem when trying to include images as enclosure, but it seemed that the easiest way for me was to include the image with the normal img tag to the html content.
(It's also wrapped in CDATA, which might affect the way Google Reader handles the content. I haven't tried without.)
The following example works for me to make atom feed images visible in Google Reader:
<content type="html">
<![CDATA[
<a href="http://test.lvh.me:3000/listings/341-test-pics?locale=en">
<img alt="test_pic" src="http://test.lvh.me:3000/system/images/20/medium/test_pic.jpg?1343246102" />
</a>
]]>
</content>

Wordpress uses the metafield enclosure to set the medias. This is the correct tag according to RSS specification. I have seen people suggest using media:content but if using that make sure to set the XML namespace for it.
Unfortunately due to some dodgy Wordpress code you can not set this dynamically. (Wordpress gets all metafields and then loops through them instead of calling the enclosure directly)
You can set the enclosure on save post. It should be an array with entries of the form "$url\n$length\n$type"
If you want to add the enclosure tags yourself you can do the following:
RSS
add_action( 'rss2_item', 'hughie_rss2_item_enclosure' );
function hughie_rss2_item_enclosure():void
{
$id = get_post_thumbnail_id();
$url = wp_get_attachment_url($id);
$length = filesize(get_attached_file($id));
$type = get_post_mime_type($id);
echo apply_filters( 'rss_enclosure', '<enclosure url="' . esc_url( $url ) . '" length="' . absint( $length ) . '" type="' . esc_attr( $type ) . '" />' . "\n" );
}
ATOM:
add_action( 'atom_entry', 'hughie_atom_entry_enclosure' );
function hughie_atom_entry_enclosure():void
{
$id = get_post_thumbnail_id();
$url = wp_get_attachment_url($id);
$length = filesize(get_attached_file($id));
$type = get_post_mime_type($id);
echo apply_filters( 'atom_enclosure', '<link rel="enclosure" href="' . esc_url( $url ) . '" length="' . absint( $length ) . '" type="' . esc_attr( $type ) . '" />' . "\n" );
}
The only way I found to set the enclosure dynamically is short-circuiting the get_metadata call. You can add checks to make sure that you are in a feed or even the check the stacktrace to make sure.
add_filter('get_post_metadata', 'hughie_get_post_metadata', 10, 5 );
function hughie_get_post_metadata($value, int $object_id, string $meta_key, bool $single, string $meta_type)
{
if (is_feed() && $meta_key === '') {
$backtrace = debug_backtrace();
if (isset($backtrace[7]['function']) && ( $backtrace[7]['function'] === 'rss_enclosure' || $backtrace[7]['function'] === 'atom_enclosure' ) ) {
if (!isset($value['enclosure'])) {
$value['enclosure'] = [];
}
$id = get_post_thumbnail_id();
$url = wp_get_attachment_url($id);
$length = filesize(get_attached_file($id));
$type = get_post_mime_type($id);
$value['enclosure'][] = "$url\n$length\n$type";
}
}
return $value;
}

Related

Auto complete/Suggest in Wordpress Form

I'm placing a search form of 6 fields on my home page which includes a text box field named course. I want to show course suggestions while user typing. One more is, I want to show/hide some fields according to the option of first field dropdown. Any help would be appreciated.
You can use jQuery Auto Suggest which is included with WordPress : wp_enqueue_script
With this you can write a form that does a Ajax lookup to the the Ajax URL handler. Which you can add_action onto. AJAX in Plugins
So you can ajax lookup and then on the action side you can just perform a get_posts to match titles, or a raw sql Query. And return what is needed. edit your functions.php.
add_action('wp_enqueue_scripts', 'se_wp_enqueue_scripts');
function se_wp_enqueue_scripts() {
wp_enqueue_script('suggest');
}
add_action('wp_head', 'se_wp_head');
function se_wp_head() {
?>
<script type="text/javascript">
var se_ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery(document).ready(function() {
jQuery('#se_search_element_id').suggest(se_ajax_url + '?action=se_lookup');
});
</script>
<?php
}
add_action('wp_ajax_se_lookup', 'se_lookup');
add_action('wp_ajax_nopriv_se_lookup', 'se_lookup');
function se_lookup() {
global $wpdb;
$search = like_escape($_REQUEST['q']);
$query = 'SELECT ID,post_title FROM ' . $wpdb->posts . '
WHERE post_title LIKE \'' . $search . '%\'
AND post_type = \'post_type_name\'
AND post_status = \'publish\'
ORDER BY post_title ASC';
foreach ($wpdb->get_results($query) as $row) {
$post_title = $row->post_title;
$id = $row->ID;
$meta = get_post_meta($id, 'YOUR_METANAME', TRUE);
echo $post_title . ' (' . $meta . ')' . "\n";
}
die();
}
Use ajax for both. You may have to write some mysql query to retrieve the required fields(post titles or whatever it is) from the table.

TYPO3: How to render translated content in extension

I am developing a TYPO3 6.0 plugin that shows the subpages of the current page as tabs. For example, on the following pages my plugin is inserted on TabRoot:
If TabRoot is requested, the plugin's ActionController looks up the database for the subpage titles and contents and passes all gathered data to a Fluid template. The page is then rendered like the following:
With JS in place I always hide/show content below based on the selection. My problem is that I want to show the translated content of the subpages based on the current language selection. How am I able to do this? I've tried it with several methods, but neither of them was flawless. These are the methods I've tried:
Using RECORDS This method is not affected by the selected language, it always returns the content in the default language:
//Get the ids of the parts of the page
$select_fields = "uid";
$from_table = "tt_content";
$where_clause = 'pid = ' . $pageId;
$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
$select_fields,
$from_table,
$where_clause,
$groupBy='',
$orderBy='sorting',
$limit=''
);
$ids = '';
$firstIteration = true;
while ( $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc( $res ) ) {
if (!$firstIteration) $ids .= ",";
$ids .= $row ['uid'];
$firstIteration = false;
}
$GLOBALS['TYPO3_DB']->sql_free_result( $res );
//Render the parts of the page
$conf ['tables'] = 'tt_content';
$conf ['source'] = $ids;
$conf ['dontCheckPid'] = 1;
$content = $this->cObj->cObjGetSingle ( 'RECORDS', $conf );
Using CONTENTS According to TYPO3: How to render localized tt_content in own extension, this is the way to do it, however for me this also returns the content rendered with the default language. It is not affected by a language change.
$conf = array(
'table' => 'tt_content',
'select.' => array(
'pidInList' => $pageId,
'orderBy' => 'sorting',
'languageField' => 'sys_language_uid'
)
);
$content = $this->cObj->cObjGetSingle ( 'CONTENT', $conf );
Using VHS: Fluid ViewHelpers I installed the vhs extension and tried to render the content with <v:content.render />. The result is the same as with CONTENTS; it only works with the default language.
{namespace v=Tx_Vhs_ViewHelpers}
...
<v:content.render column="0" order="'sorting'" sortDirection="'ASC'"
pageUid="{pageId}" render="1" hideUntranslated="1" />
Using my own SQL query I've tried to get the bodytext fields of the page and then render those with \TYPO3\CMS\Frontend\Plugin\AbstractPlugin::pi_RTEcssText(). This method returns the content based on the current language, however the problem is that bodytext's do not contain the complete content (images, other plugins, etc).
$select_fields = "bodytext";
$from_table = "tt_content";
$where_clause = 'pid = ' . $pageId
. ' AND sys_language_uid = ' . $GLOBALS ['TSFE']->sys_language_uid;
$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
$select_fields,
$from_table,
$where_clause,
$groupBy='',
$orderBy='sorting',
$limit=''
);
$content = '';
while ( $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc( $res ) ) {
$content .=
\TYPO3\CMS\Frontend\Plugin\AbstractPlugin::pi_RTEcssText( $row ['bodytext'] );
}
$GLOBALS['TYPO3_DB']->sql_free_result( $res );
What am I missing? Why isn't the content rendered with the current language in the case of the CONTENTS method?
Easiest way is to use the cObject viewhelper to render right from TypoScript.
And inside your TypoScript template provide the configuration:
lib.myContent = CONTENT
lib.myContent {
...
}
BTW, you are bypassing the TYPO3 CMS API. Please do not do so. Always use the API methods to query for data.
e.g. \TYPO3\CMS\core\Database\DatabaseConnection is always available at GLOBALS['TYPO3_DB']->. Do not use the the mysql function.
On top of that, I believe that you can archive whatever you are trying to do with pure TypoScript, without the need to program anything. Feel free to ask a new questions to get help on this.
In TYPO3 4.x you could use the following methods to load the translated record:
t3lib_pageSelect->getRecordOverlay
t3lib_pageSelect->getPageOverlay
They are also available at $GLOBALS['TSFE']->sys_page->getRecordOverlay().

Zend Framework 2 form element error-class + custom ViewHelper to render form

This is my third question this week (and overall) - hope I don't get banned here :D
Anyway, searched around and couldn't find an exact explanation to solve my issue(s).
A. I've searched around and found a custom ViewHelper to render my forms. What it does is recursively get all fieldsets and when it gets to the element level, it goes like this:
public function renderElement($element) {
$html = '
<div class="row">' .
'<label class="col-md-12" for="' . $element->getAttribute('id') . '">' . $element->getLabel() . '</label>' .
$this->view->formElement($element) .
$this->view->FormElementErrors($element) .
'<div class="clearfix" style="height: 15px;"></div>';
return $html . PHP_EOL;
}
Form renders ok, except:
1) How can I add an error class to the form element? (like if I use formRow helper in my view, it automatically ads an 'input-error' class, while also keeping the initial class specified in my fieldset when creating the element - 'attributes' => array('class' => 'some-class')), so the element's class attribute becomes "some-class input-error" in case it's invalid.
2) How can I set a class for the 'ul' containing the error messages (the 'ul' rendered by $this->view->FormElementErrors($element))? Hope this is a one-liner and I don't have to go message-by-message and compose the html for the error messages list, but if not so be it (I don't know how to do that either).
B. Let's say that sometimes I don't use this custom ViewHelper to render my form. Zend's formRow view helper can be handy sometimes. This brings me to the following code in my view:
echo $this->formRow($this->form->get('user_fieldset')->get('user_name'));
I've noticed this automatically adds 'input-error' class on my element (in case it's invalid) which is perfect, BUT how can I also tell formRow to give a class to the 'ul' that's displaying the error messages?
I'd go even further and ask how I can turn this:
echo $this->formLabel($this->form->get('user_fieldset')->get('user_name'));
echo $this->formInput($this->form->get('user_fieldset')->get('user_name'));
echo $this->formElementErrors($this->form->get('user_fieldset')->get('user_name'), array('class' => 'form-validation-error'));
into something that ads an error-class to the element as well, not just to the error messages list, but if anyone answers to point A I think it's the same issue.
I've managed to do it like this:
public function renderElement($element) {
// FORM ROW
$html = '<div class="form-group">';
// LABEL
$html .= '<label class="form-label" for="' . $element->getAttribute('id') . '">' . $element->getLabel() . '</label>';
// ELEMENT
/*
- Check if element has error messages
- If it does, add my error-class to the element's existing one(s),
to style the element differently on error
*/
if (count($element->getMessages()) > 0) {
$classAttribute = ($element->hasAttribute('class') ? $element->getAttribute('class') . ' ' : '');
$classAttribute .= 'input-error';
/*
* Normally, here I would have added a space in my string (' input-error')
* Logically, I would figure that if the element already has a class "cls"
* and I would do $element->getAttribute('class') . 'another-class'
* then the class attribute would become "clsanother-class"
* BUT it seems that, even if I don't intentionally add a space in my string,
* I still get "cls another-class" as the resulted concatenated string
* I assume that when building the form, ZF2 automatically
* adds spaces after attributes values? so you/it won't have to
* consider that later, when you'd eventually need to add another
* value to an attribute?
*/
$element->setAttribute('class', $classAttribute);
}
$html .= $this->view->formElement($element);
/*
* Of course, you could decide/need to do things differently,
* depending on the element's type
switch ($element->getAttribute('type')) {
case 'text':
case 'email': {
break;
}
default: {
}
}
*/
// ERROR MESSAGES
// Custom class (.form-validation-error) for the default html wrapper - <ul>
$html .= $this->view->FormElementErrors($element, array('class' => 'form-validation-error'));
$html .= '</div>'; # /.form-group
$html .= '<div class="clearfix" style="height: 15px;"></div>';
return $html . PHP_EOL;
}
I'm not to fond of this, but I suppose there is no shorter way. I thought ZF2 shoud have something like:
if ($element->hasErrors()) { $element->addClass('some-class'); }
right out of the box. That's the answer I would have expected, that it would simply be a method I missed/couldn't find. But it turns out that ZF2 doesn't have quite anything in the whole world that you might need right out of the box, you end up having to write the (more or less) occasional helpers.
Anyway, if someone ever needs it here's the entire RenderForm view helper:
namespace User\View\Helper;
use Zend\View\Helper\AbstractHelper;
class RenderForm extends AbstractHelper {
public function __invoke($form) {
$form->prepare();
$html = $this->view->form()->openTag($form) . PHP_EOL;
$html .= $this->renderFieldsets($form->getFieldsets());
$html .= $this->renderElements($form->getElements());
$html .= $this->view->form()->closeTag($form) . PHP_EOL;
return $html;
}
public function renderFieldsets($fieldsets) {
foreach ($fieldsets as $fieldset) {
if (count($fieldset->getFieldsets()) > 0) {
$html = $this->renderFieldsets($fieldset->getFieldsets());
} else {
$html = '<fieldset>';
// You can use fieldset's name for the legend (if that's not inappropriate)
$html .= '<legend>' . ucfirst($fieldset->getName()) . '</legend>';
// or it's label (if you had set one)
// $html .= '<legend>' . ucfirst($fieldset->getLabel()) . '</legend>';
$html .= $this->renderElements($fieldset->getElements());
$html .= '</fieldset>';
// I actually never use the <fieldset> html tag.
// Feel free to use anything you like, if you do have to
// make grouping certain elements stand out to the user
}
}
return $html;
}
public function renderElements($elements) {
$html = '';
foreach ($elements as $element) {
$html .= $this->renderElement($element);
}
return $html;
}
public function renderElement($element) {
// FORM ROW
$html = '<div class="form-group">';
// LABEL
$html .= '<label class="form-label" for="' . $element->getAttribute('id') . '">' . $element->getLabel() . '</label>'; # add translation here
// ELEMENT
/*
- Check if element has error messages
- If it does, add my error-class to the element's existing one(s),
to style the element differently on error
*/
if (count($element->getMessages()) > 0) {
$classAttribute = ($element->hasAttribute('class') ? $element->getAttribute('class') . ' ' : '');
$classAttribute .= 'input-error';
$element->setAttribute('class', $classAttribute);
}
$html .= $this->view->formElement($element);
// ERROR MESSAGES
$html .= $this->view->FormElementErrors($element, array('class' => 'form-validation-error'));
$html .= '</div>'; # /.row
$html .= '<div class="clearfix" style="height: 15px;"></div>';
return $html . PHP_EOL;
}
}
User is my module. I've created a 'viewhelper.config.php' in it's config folder:
return array(
'invokables' => array(
'renderForm' => 'User\View\Helper\RenderForm',
),
);
and in Module.php:
public function getViewHelperConfig() {
return include __DIR__ . '/config/viewhelper.config.php';
}
Then, in your view simply call:
$this->renderForm($form);
Of course, if you don't have many view helpers, you could not create a separate config file just for that, leave Module.php alone and simply add:
'view_helpers' => array(
'invokables' => array(
'renderForm' => 'User\View\Helper\RenderForm',
),
),
to any configuration file.
I use getMessages() method to check if an element has an validation message. for eg.
<div class="form-group <?=($this->form->get('user_fieldset')->get('user_name')->getMessages())?'has-error':'';?>">
...
</div>
This question seems to be very old and you must have solved it by yourself. :)

how to set a value for Zend_Form_Element_Submit (zendframework 1)

I have am having trouble setting the basic values of a zend form element submit button (Zendframework1). I basically want to set a unique id number in it and then retrieve this number once the button has been submitted.
Below is my code. you will nots that I tried to use the setValue() method but this did not work.
$new = new Zend_Form_Element_Submit('new');
$new
->setDecorators($this->_buttonDecorators)
->setValue($tieredPrice->sample_id)
->setLabel('New');
$this->addElement($new);
I would also appreciate any advice on what I use to receive the values. i.e what method I will call to retrieve the values?
The label is used as the value on submit buttons, and this is what is submitted. There isn't a way to have another value submitted as part of the button as well - you'd either need to change the submit name or value (= label).
What you probably want to do instead is add a hidden field to the form and give that your numeric value instead.
It's a little bit tricky but not impossible :
You need to implement your own view helper and use it with your element.
At first, you must add a custom view helper path :
How to add a view helper directory (zend framework)
Implement your helper :
class View_Helper_CustomSubmit extends Zend_View_Helper_FormSubmit
{
public function customSubmit($name, $value = null, $attribs = null)
{
if( array_key_exists( 'value', $attribs ) ) {
$value = $attribs['value'];
unset( $attribs['value'] );
}
$info = $this->_getInfo($name, $value, $attribs);
extract($info); // name, value, attribs, options, listsep, disable, id
// check if disabled
$disabled = '';
if ($disable) {
$disabled = ' disabled="disabled"';
}
if ($id) {
$id = ' id="' . $this->view->escape($id) . '"';
}
// XHTML or HTML end tag?
$endTag = ' />';
if (($this->view instanceof Zend_View_Abstract) && !$this->view->doctype()->isXhtml()) {
$endTag= '>';
}
// Render the button.
$xhtml = '<input type="submit"'
. ' name="' . $this->view->escape($name) . '"'
. $id
. ' value="' . $this->view->escape( $value ) . '"'
. $disabled
. $this->_htmlAttribs($attribs)
. $endTag;
return $xhtml;
}
}
So, you assign the helper to the element :
$submit = $form->createElement( 'submit', 'submitElementName' );
$submit->setAttrib( 'value', 'my value' );
$submit->helper = 'customSubmit';
$form->addELement( $submit );
This way, you can retrieve the value of the submitted form :
$form->getValue( 'submitElementName' );

Adding an additional field to login with AWD Facebook Wordpress Plugin

I am using AWD Facebook wordpress plugin to allow my visitors to login with their Facebook account information. When a visitor registers on my site I automatically create a new post that is titled with their username and includes their Facebook profile picture as the content. The code for that is below:
function my_create_page($user_id){
$fbuide = 0;
$the_user = get_userdata($user_id);
$new_user_name = $the_user->user_login;
$new_user_avatar = get_avatar($the_user->user_email);
global $AWD_facebook;
$fbuide = $AWD_facebook->uid;
$headers = get_headers('http://graph.facebook.com/' . $fbuide . '/picture?type=large',1);
if(isset($headers['Location'])) {
$url = $headers['Location']; // string
} else {
$url = false;
}
$my_avatar = "<img src='" . $url . "' class='avatar AWD_fbavatar' alt='" . $alt . "' height='" . $size . "' />";
$my_post = array();
$my_post['post_title'] = $new_user_name;
$my_post['post_type'] = 'post';
$my_post['post_content'] = $my_avatar;
$my_post['post_status'] = 'publish';
wp_insert_post( $my_post );
}
add_action('user_register', 'my_create_page');
What I am looking to accomplish is a bit different though. I also want to include a brief biography about the user (currently the post is simply their picture). So when a visitor logs in with AWD Facebook, their needs to be an additional field that allows the user to type in their bio. Then I would be able to grab that info from their user profile and include it in the post. Any ideas on how I can accomplish this? Is there a different way to do this?
I would recommend storing their Facebook picture as metadata and use the content area as their bio for the automatically generated post. So something like this should get you started:
$my_post = array(
'post_title'=>$new_user_name,
'post_type'=>'post',
'post_content'=>'',
'post_status'=>'publish'
);
if( $id = wp_insert_post( $my_post ) ){
update_post_meta($id, 'avatar', $url);
}
Then you can generate the loop like so:
if ( have_posts() ) : while ( have_posts() ) : the_post();
//... stuff here
$avatar = get_post_meta($post->ID, 'avatar', 'true');
the_content();
echo '<img class="avatar AWD_fbavatar" src="'.$avatar.'" alt="'.$alt.'" height="'.$size.'" />';
endwhile;endif;