qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
177,676 |
<p>I am trying to override wp menu markup and add additional div around each sub-menu ul. </p>
<p>Something like this</p>
<pre><code><ul>
<li><a>Coffee</li>
<li><a>Tea</a>
<div class="holder">
<ul class="sub-menu">
<li><a>Black tea</a></li>
<li><a>Green tea</a></li>
</ul>
</div>
</li>
<li><a>Milk</a>
<div class="holder">
<ul class="sub-menu">
<li><a>Red</a></li>
<li><a>Blue</a></li>
</ul>
</div>
</li>
</ul>
</code></pre>
<p>Is it possible to do this inside ?</p>
<pre><code>$defaults = array(
'theme_location' => 'primary',
'menu' => '',
'container' => 'div',
'container_class' => '',
'container_id' => 'mega-menu',
'menu_class' => 'mega',
'menu_id' => '',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' => '',
'after' => '',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'depth' => 0,
'walker' => ''
);
</code></pre>
<p>Any help is appreciated. </p>
|
[
{
"answer_id": 177679,
"author": "jdm2112",
"author_id": 45202,
"author_profile": "https://wordpress.stackexchange.com/users/45202",
"pm_score": 1,
"selected": false,
"text": "<p>I believe what you are looking for is a custom nav walker to control your HTML structure.</p>\n\n<p>The WP Codex article lists a good example for controlling the HTML structure of a menu <a href=\"http://codex.wordpress.org/Class_Reference/Walker#General_Menu_Example\" rel=\"nofollow\">http://codex.wordpress.org/Class_Reference/Walker#General_Menu_Example</a></p>\n\n<p>\n\n<pre><code>// Tell Walker where to inherit it's parent and id values\nvar $db_fields = array(\n 'parent' => 'menu_item_parent', \n 'id' => 'db_id' \n);\n\n/**\n * At the start of each element, output a <li> and <a> tag structure.\n * \n * Note: Menu objects include url and title properties, so we will use those.\n */\nfunction start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n $output .= sprintf( \"\\n<li><a href='%s'%s>%s</a></li>\\n\",\n $item->url,\n ( $item->object_id === get_the_ID() ) ? ' class=\"current\"' : '',\n $item->title\n );\n}\n</code></pre>\n\n<p>}</p>\n\n<p>I will see if I can test up an example that solves your submenu challenge directly.</p>\n"
},
{
"answer_id": 177681,
"author": "Benn",
"author_id": 67176,
"author_profile": "https://wordpress.stackexchange.com/users/67176",
"pm_score": 2,
"selected": false,
"text": "<p>OK got it. For anyone who needs to do this , it is best you extend Walker_Nav_Menu class if you just need to add things to existing wp menu structure. Otherwise if you are extending Walker class you kinda have to rebuild the menu completely. </p>\n\n<p>Include this class </p>\n\n<pre><code>class Walker_Extend_Menu extends Walker_Nav_Menu {\n\n // Tell Walker where to inherit it's parent and id values\n var $db_fields = array(\n 'parent' => 'menu_item_parent', \n 'id' => 'db_id' \n );\n\n /**\n * Starts the list before the elements are added.\n *\n * @see Walker::start_lvl()\n *\n * @since 3.0.0\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @param int $depth Depth of menu item. Used for padding.\n * @param array $args An array of arguments. @see wp_nav_menu()\n */\n public function start_lvl( &$output, $depth = 0, $args = array() ) {\n $indent = str_repeat(\"\\t\", $depth);\n $output .= \"\\n$indent<div class=\\\"holder\\\">\\n$indent<ul class=\\\"sub-menu\\\">\\n\";\n }\n\n /**\n * Ends the list of after the elements are added.\n *\n * @see Walker::end_lvl()\n *\n * @since 3.0.0\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @param int $depth Depth of menu item. Used for padding.\n * @param array $args An array of arguments. @see wp_nav_menu()\n */\n public function end_lvl( &$output, $depth = 0, $args = array() ) {\n $indent = str_repeat(\"\\t\", $depth);\n $output .= \"$indent</ul>\\n</div>\\n\";\n }\n\n}\n</code></pre>\n\n<p>And call your walker in wp_nav_menu</p>\n\n<pre><code>$defaults = array(\n 'theme_location' => 'primary',\n 'menu' => '',\n 'container' => 'div',\n 'container_class' => '',\n 'container_id' => 'mega-menu',\n 'menu_class' => 'mega',\n 'menu_id' => '',\n 'echo' => true,\n 'fallback_cb' => 'wp_page_menu',\n 'before' => '',\n 'after' => '',\n 'link_before' => '',\n 'link_after' => '',\n 'items_wrap' => '<ul id=\"%1$s\" class=\"%2$s\">%3$s</ul>',\n 'depth' => 0,\n 'walker' => new Walker_Extend_Menu ()\n);\n</code></pre>\n"
}
] |
2015/02/10
|
[
"https://wordpress.stackexchange.com/questions/177676",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67176/"
] |
I am trying to override wp menu markup and add additional div around each sub-menu ul.
Something like this
```
<ul>
<li><a>Coffee</li>
<li><a>Tea</a>
<div class="holder">
<ul class="sub-menu">
<li><a>Black tea</a></li>
<li><a>Green tea</a></li>
</ul>
</div>
</li>
<li><a>Milk</a>
<div class="holder">
<ul class="sub-menu">
<li><a>Red</a></li>
<li><a>Blue</a></li>
</ul>
</div>
</li>
</ul>
```
Is it possible to do this inside ?
```
$defaults = array(
'theme_location' => 'primary',
'menu' => '',
'container' => 'div',
'container_class' => '',
'container_id' => 'mega-menu',
'menu_class' => 'mega',
'menu_id' => '',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' => '',
'after' => '',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'depth' => 0,
'walker' => ''
);
```
Any help is appreciated.
|
OK got it. For anyone who needs to do this , it is best you extend Walker\_Nav\_Menu class if you just need to add things to existing wp menu structure. Otherwise if you are extending Walker class you kinda have to rebuild the menu completely.
Include this class
```
class Walker_Extend_Menu extends Walker_Nav_Menu {
// Tell Walker where to inherit it's parent and id values
var $db_fields = array(
'parent' => 'menu_item_parent',
'id' => 'db_id'
);
/**
* Starts the list before the elements are added.
*
* @see Walker::start_lvl()
*
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of arguments. @see wp_nav_menu()
*/
public function start_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<div class=\"holder\">\n$indent<ul class=\"sub-menu\">\n";
}
/**
* Ends the list of after the elements are added.
*
* @see Walker::end_lvl()
*
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of arguments. @see wp_nav_menu()
*/
public function end_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat("\t", $depth);
$output .= "$indent</ul>\n</div>\n";
}
}
```
And call your walker in wp\_nav\_menu
```
$defaults = array(
'theme_location' => 'primary',
'menu' => '',
'container' => 'div',
'container_class' => '',
'container_id' => 'mega-menu',
'menu_class' => 'mega',
'menu_id' => '',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' => '',
'after' => '',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'depth' => 0,
'walker' => new Walker_Extend_Menu ()
);
```
|
177,677 |
<p>I have created a custom template and trying to get a custom post of type "song", But it is displaying only the header and footer on the page. There is no post content coming. Even if I try to call general posts then also no content coming, Should I register this template anywhere in the theme? OR need to call anything here?</p>
<p>My code :</p>
<pre><code><?php
/* Template Name: song Page
*
* Selectable from a dropdown menu on the edit page screen.
*/
get_header(); ?>
<div>
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
query_posts( 'post_type=song');
} // end while
} // end if
?></div>
<?php get_footer(); ?>
</code></pre>
<p>Please help to correct my code. I want to display all posts of custom post type "songs".
I have already created a custom post type.</p>
<p>I am putting the above code in WordPress editor, I have installed a plugin called "PHP execution" so it executes PHP code.</p>
|
[
{
"answer_id": 177680,
"author": "vcamargo",
"author_id": 60070,
"author_profile": "https://wordpress.stackexchange.com/users/60070",
"pm_score": -1,
"selected": false,
"text": "<p>Have you tried <code>'post_type'=> 'songs'</code>?</p>\n\n<p>Reference: <a href=\"http://codex.wordpress.org/Post_Types#Querying_by_Post_Type\" rel=\"nofollow\">Querying by Post Type</a></p>\n"
},
{
"answer_id": 177725,
"author": "Mike",
"author_id": 67357,
"author_profile": "https://wordpress.stackexchange.com/users/67357",
"pm_score": -1,
"selected": false,
"text": "<p>Or even</p>\n\n<pre><code>query_posts( 'post_type=song');\n</code></pre>\n"
},
{
"answer_id": 177807,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": true,
"text": "<p>You really have two major flaws in your code:</p>\n\n<ul>\n<li><p><code>query_posts</code> needs to go before your loop, not inside it</p></li>\n<li><p>Never use <code>query_posts</code> in the first place unless you need to break something on your page</p></li>\n</ul>\n\n<p>To learn why not to use <code>query_posts</code> and when to use a custom query and how to use it, check <a href=\"https://wordpress.stackexchange.com/a/155976/31545\">this post</a> I have done a while ago</p>\n\n<p>So, in order to correct your code in your template, we are going to make use of <code>WP_Query</code> and <strong>not</strong> <code>query_posts</code>, and we are going to do the query <strong>before</strong> the loop</p>\n\n<p>Try something like this:</p>\n\n<pre><code><?php \n /* Template Name: song Page\n *\n * Selectable from a dropdown menu on the edit page screen.\n */\n?>\n\n<?php get_header(); ?>\n\n<div>\n\n <?php \n $args = array(\n 'post_type' => 'song'\n );\n $q = new WP_Query($args);\n if ( $q->have_posts() ) {\n while ( $q->have_posts() ) {\n $q->the_post(); \n\n //Add your template tags like below\n the_title();\n\n } // end while\n wp_reset_postdata();\n } // end if\n ?>\n\n</div>\n</code></pre>\n\n<p>Also, never forget to reset custom queries if you have used the loop or <code>setup_postdata($post)</code> with <code>wp_reset_postdata()</code></p>\n"
},
{
"answer_id": 177820,
"author": "Brad Dalton",
"author_id": 9884,
"author_profile": "https://wordpress.stackexchange.com/users/9884",
"pm_score": 1,
"selected": false,
"text": "<p>You don't need to create any templates if you simply want to list all pages in an archive for your custom post type:</p>\n\n<p>You simply go to <a href=\"http://example.com/songs\" rel=\"nofollow\">http://example.com/songs</a> and WordPress will display all your CPT pages in a standard archive according to the Template Hierarchy. Swap out example.com with your domain.</p>\n\n<p>You may need to re-save your Permalinks to flush your rewrite rules and include the following parameters in your register_post_type function:</p>\n\n<pre><code>'has_archive' => true,\n\n'rewrite' => array( 'slug' => 'songs', 'with_front' => false ),\n</code></pre>\n\n<p>If you want to create a custom page for your CPT archive, create a new file and name it archive-song.php in the root directory of your theme.</p>\n"
},
{
"answer_id": 377990,
"author": "gadolf",
"author_id": 197382,
"author_profile": "https://wordpress.stackexchange.com/users/197382",
"pm_score": 0,
"selected": false,
"text": "<p>Go to <em><strong>Settings > Permalinks</strong></em> and just click on "<strong>Save Changes</strong>" button.\nNow refresh the page.</p>\n"
}
] |
2015/02/10
|
[
"https://wordpress.stackexchange.com/questions/177677",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63934/"
] |
I have created a custom template and trying to get a custom post of type "song", But it is displaying only the header and footer on the page. There is no post content coming. Even if I try to call general posts then also no content coming, Should I register this template anywhere in the theme? OR need to call anything here?
My code :
```
<?php
/* Template Name: song Page
*
* Selectable from a dropdown menu on the edit page screen.
*/
get_header(); ?>
<div>
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
query_posts( 'post_type=song');
} // end while
} // end if
?></div>
<?php get_footer(); ?>
```
Please help to correct my code. I want to display all posts of custom post type "songs".
I have already created a custom post type.
I am putting the above code in WordPress editor, I have installed a plugin called "PHP execution" so it executes PHP code.
|
You really have two major flaws in your code:
* `query_posts` needs to go before your loop, not inside it
* Never use `query_posts` in the first place unless you need to break something on your page
To learn why not to use `query_posts` and when to use a custom query and how to use it, check [this post](https://wordpress.stackexchange.com/a/155976/31545) I have done a while ago
So, in order to correct your code in your template, we are going to make use of `WP_Query` and **not** `query_posts`, and we are going to do the query **before** the loop
Try something like this:
```
<?php
/* Template Name: song Page
*
* Selectable from a dropdown menu on the edit page screen.
*/
?>
<?php get_header(); ?>
<div>
<?php
$args = array(
'post_type' => 'song'
);
$q = new WP_Query($args);
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
//Add your template tags like below
the_title();
} // end while
wp_reset_postdata();
} // end if
?>
</div>
```
Also, never forget to reset custom queries if you have used the loop or `setup_postdata($post)` with `wp_reset_postdata()`
|
177,692 |
<p>I'm trying to track down why menu switching by language in the polylang filter is not working correctly.</p>
<p>I'm looking at the function nav_menu_locations which is added as a filter as such:</p>
<pre><code>add_filter('theme_mod_nav_menu_locations', array($this, 'nav_menu_locations'), 20);
</code></pre>
<p>and then defined subsequently as:</p>
<pre><code>public function nav_menu_locations($menus) {
...
return $menus;
}
</code></pre>
<p>I inserted statements to echo $menus at the start and just before the altered value is returned, and can confirm that the function is being called.</p>
<p>But the curious thing is that searching the entire plug-in code–and then the entire WordPress core–I can find no matching apply_filters for theme_mod_nav_menu_locations, and no direct calls to the function either as far as I can tell. So I can't see where the $menus parameter is being generated.</p>
<p>I thought I understood how filter hooks work, and yet can't see how the function nav_menu_locations is being run, although it clearly is.</p>
<p>It might not help me solve the problems with my menu switching, but I'd at least like to clarify how the filter is being triggered.</p>
|
[
{
"answer_id": 177680,
"author": "vcamargo",
"author_id": 60070,
"author_profile": "https://wordpress.stackexchange.com/users/60070",
"pm_score": -1,
"selected": false,
"text": "<p>Have you tried <code>'post_type'=> 'songs'</code>?</p>\n\n<p>Reference: <a href=\"http://codex.wordpress.org/Post_Types#Querying_by_Post_Type\" rel=\"nofollow\">Querying by Post Type</a></p>\n"
},
{
"answer_id": 177725,
"author": "Mike",
"author_id": 67357,
"author_profile": "https://wordpress.stackexchange.com/users/67357",
"pm_score": -1,
"selected": false,
"text": "<p>Or even</p>\n\n<pre><code>query_posts( 'post_type=song');\n</code></pre>\n"
},
{
"answer_id": 177807,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": true,
"text": "<p>You really have two major flaws in your code:</p>\n\n<ul>\n<li><p><code>query_posts</code> needs to go before your loop, not inside it</p></li>\n<li><p>Never use <code>query_posts</code> in the first place unless you need to break something on your page</p></li>\n</ul>\n\n<p>To learn why not to use <code>query_posts</code> and when to use a custom query and how to use it, check <a href=\"https://wordpress.stackexchange.com/a/155976/31545\">this post</a> I have done a while ago</p>\n\n<p>So, in order to correct your code in your template, we are going to make use of <code>WP_Query</code> and <strong>not</strong> <code>query_posts</code>, and we are going to do the query <strong>before</strong> the loop</p>\n\n<p>Try something like this:</p>\n\n<pre><code><?php \n /* Template Name: song Page\n *\n * Selectable from a dropdown menu on the edit page screen.\n */\n?>\n\n<?php get_header(); ?>\n\n<div>\n\n <?php \n $args = array(\n 'post_type' => 'song'\n );\n $q = new WP_Query($args);\n if ( $q->have_posts() ) {\n while ( $q->have_posts() ) {\n $q->the_post(); \n\n //Add your template tags like below\n the_title();\n\n } // end while\n wp_reset_postdata();\n } // end if\n ?>\n\n</div>\n</code></pre>\n\n<p>Also, never forget to reset custom queries if you have used the loop or <code>setup_postdata($post)</code> with <code>wp_reset_postdata()</code></p>\n"
},
{
"answer_id": 177820,
"author": "Brad Dalton",
"author_id": 9884,
"author_profile": "https://wordpress.stackexchange.com/users/9884",
"pm_score": 1,
"selected": false,
"text": "<p>You don't need to create any templates if you simply want to list all pages in an archive for your custom post type:</p>\n\n<p>You simply go to <a href=\"http://example.com/songs\" rel=\"nofollow\">http://example.com/songs</a> and WordPress will display all your CPT pages in a standard archive according to the Template Hierarchy. Swap out example.com with your domain.</p>\n\n<p>You may need to re-save your Permalinks to flush your rewrite rules and include the following parameters in your register_post_type function:</p>\n\n<pre><code>'has_archive' => true,\n\n'rewrite' => array( 'slug' => 'songs', 'with_front' => false ),\n</code></pre>\n\n<p>If you want to create a custom page for your CPT archive, create a new file and name it archive-song.php in the root directory of your theme.</p>\n"
},
{
"answer_id": 377990,
"author": "gadolf",
"author_id": 197382,
"author_profile": "https://wordpress.stackexchange.com/users/197382",
"pm_score": 0,
"selected": false,
"text": "<p>Go to <em><strong>Settings > Permalinks</strong></em> and just click on "<strong>Save Changes</strong>" button.\nNow refresh the page.</p>\n"
}
] |
2015/02/10
|
[
"https://wordpress.stackexchange.com/questions/177692",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35739/"
] |
I'm trying to track down why menu switching by language in the polylang filter is not working correctly.
I'm looking at the function nav\_menu\_locations which is added as a filter as such:
```
add_filter('theme_mod_nav_menu_locations', array($this, 'nav_menu_locations'), 20);
```
and then defined subsequently as:
```
public function nav_menu_locations($menus) {
...
return $menus;
}
```
I inserted statements to echo $menus at the start and just before the altered value is returned, and can confirm that the function is being called.
But the curious thing is that searching the entire plug-in code–and then the entire WordPress core–I can find no matching apply\_filters for theme\_mod\_nav\_menu\_locations, and no direct calls to the function either as far as I can tell. So I can't see where the $menus parameter is being generated.
I thought I understood how filter hooks work, and yet can't see how the function nav\_menu\_locations is being run, although it clearly is.
It might not help me solve the problems with my menu switching, but I'd at least like to clarify how the filter is being triggered.
|
You really have two major flaws in your code:
* `query_posts` needs to go before your loop, not inside it
* Never use `query_posts` in the first place unless you need to break something on your page
To learn why not to use `query_posts` and when to use a custom query and how to use it, check [this post](https://wordpress.stackexchange.com/a/155976/31545) I have done a while ago
So, in order to correct your code in your template, we are going to make use of `WP_Query` and **not** `query_posts`, and we are going to do the query **before** the loop
Try something like this:
```
<?php
/* Template Name: song Page
*
* Selectable from a dropdown menu on the edit page screen.
*/
?>
<?php get_header(); ?>
<div>
<?php
$args = array(
'post_type' => 'song'
);
$q = new WP_Query($args);
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
//Add your template tags like below
the_title();
} // end while
wp_reset_postdata();
} // end if
?>
</div>
```
Also, never forget to reset custom queries if you have used the loop or `setup_postdata($post)` with `wp_reset_postdata()`
|
177,703 |
<p>Every now and then some clients have multiple domains for the same site. For example domain.com and domain.org. Is it possible to have wordpress work with both domains at the same time? I typically see issues when trying to load resources because of Cross-domain access. I know that I could just point domain.com to domain.org in the domain settings, but I was wondering if that's the only way.</p>
<p>I searched for solutions here, but all questions are about how to setup multiple domains for multisites (which makes sense). Just to be clear, I am not running a multisite.</p>
|
[
{
"answer_id": 177704,
"author": "Austin Curtis",
"author_id": 67344,
"author_profile": "https://wordpress.stackexchange.com/users/67344",
"pm_score": 5,
"selected": true,
"text": "<p>Are you wanting for the exact same WordPress site to work on two different domain names, where all links and content would use either domain name?</p>\n\n<p>If this were the case, you would run into <a href=\"https://support.google.com/webmasters/answer/66359?hl=en\">Duplicate Content issues with Google</a>, hurting your SEO pretty badly.</p>\n\n<p>That being said, you still would have a very hard time getting WordPress to properly load your content off of either domain name. A variety of functionality uses the <a href=\"http://codex.wordpress.org/Function_Reference/get_site_url\">get_site_url</a> function to construct the links on your pages, so all of your links would be using only the one domain within your Siteurl setting.</p>\n\n<p>Even still, if you want to try and get really tricksy, you can use something like the following to define your Siteurl and Home in the wp-config.php based upon the Domain being passed to the site:</p>\n\n<pre><code>define('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST'] . '/path/to/wordpress');\ndefine('WP_HOME', 'http://' . $_SERVER['HTTP_HOST'] . '/path/to/wordpress');\n</code></pre>\n"
},
{
"answer_id": 367610,
"author": "Ashraf Sello",
"author_id": 188881,
"author_profile": "https://wordpress.stackexchange.com/users/188881",
"pm_score": 2,
"selected": false,
"text": "<p>Just check this <strong>WordPress Plugin</strong> it should resolve this issue easy way..</p>\n\n<h2><a href=\"https://wordpress.org/plugins/multiple-domain/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/multiple-domain/</a></h2>\n"
}
] |
2015/02/10
|
[
"https://wordpress.stackexchange.com/questions/177703",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/30984/"
] |
Every now and then some clients have multiple domains for the same site. For example domain.com and domain.org. Is it possible to have wordpress work with both domains at the same time? I typically see issues when trying to load resources because of Cross-domain access. I know that I could just point domain.com to domain.org in the domain settings, but I was wondering if that's the only way.
I searched for solutions here, but all questions are about how to setup multiple domains for multisites (which makes sense). Just to be clear, I am not running a multisite.
|
Are you wanting for the exact same WordPress site to work on two different domain names, where all links and content would use either domain name?
If this were the case, you would run into [Duplicate Content issues with Google](https://support.google.com/webmasters/answer/66359?hl=en), hurting your SEO pretty badly.
That being said, you still would have a very hard time getting WordPress to properly load your content off of either domain name. A variety of functionality uses the [get\_site\_url](http://codex.wordpress.org/Function_Reference/get_site_url) function to construct the links on your pages, so all of your links would be using only the one domain within your Siteurl setting.
Even still, if you want to try and get really tricksy, you can use something like the following to define your Siteurl and Home in the wp-config.php based upon the Domain being passed to the site:
```
define('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST'] . '/path/to/wordpress');
define('WP_HOME', 'http://' . $_SERVER['HTTP_HOST'] . '/path/to/wordpress');
```
|
177,723 |
<p>I know that the question was already asked but all the answer i found doesnt help me..</p>
<p>I made an HTML page that I would like to integrate in Wordpress.</p>
<p>The integration of the theme was done properly until I get to the posts part</p>
<p>I have a problem with algorithms to display posts so I know it comes from the Wordpress loop.</p>
<p>I have done several searches on Wordpress loops but I do not understand the different uses.</p>
<p>Here is the HTML code base that I would like to loop :</p>
<pre><code><div class="oeuvres">
<div class="line0"><!-- should be dynamic -->
<div class="oeuvre">
<img class="img-oeuvre" src="ressources/creations/lisemassages.png" alt="">
<div class="infos-oeuvre">
<p>Title</p>
<p>Content</p>
<a class="btn-oeuvre" href="" target="_blank">Voir le site</a>
</div>
</div>
<div class="oeuvre">
<img class="img-oeuvre" src="ressources/creations/centredesoi.png" alt="">
<div class="infos-oeuvre">
<p>Title</p>
<p>Content</p>
<a class="btn-oeuvre" href="" target="_blank">voir le site</a>
</div>
</div>
</div><!--class line0 -->
</div>
<div class="oeuvres">
<div class="line1"><!--Should be dynamic-->
<div class="oeuvre">
<div class="infos-oeuvre">
<p>title</p>
<p>Content</p>
<a class="btn-oeuvre" href="" target="_blank">Voir le site</a>
</div>
<img class="img-oeuvre" src="ressources/creations/comparepc.png" alt="">
</div>
<div class="oeuvre">
<div class="infos-oeuvre">
<p>Title</p>
<p>Content</p>
<a class="btn-oeuvre" href="" target="_blank">voir nos créations</a>
</div>
<img class="img-oeuvre" src="ressources/creations/wine&amp;sound.jpg" alt="">
</div>
</div><!--class line1 -->
</div>
</code></pre>
<p>Here's the code i've already done but i got some problem : there's only 3 articles which are repeated : </p>
<pre><code><?php
//Variables needed for the template
$req = new WP_Query('category_name=creations') ; //object with the posts
$cptPosts = $req->post_count ; //nomber of post
$cptOeuvres = $cptPosts/2 ; //number of div .Oeuvres needed
$iOeuvres = 1 ; //counter of div.oeuvres
$iPost = 1 ; //counter of posts
?>
<?php echo 'cptpost = '.$cptPosts ; echo 'cptoeuvres = '.$cptOeuvres ;// to check $cptPost/$cptoeuvres value ?>
<?php if ($req->have_posts()) : ?>
<?php while($iOeuvres <= $cptOeuvres): ?>
<?php //if $iOeuvres is pair use .line1 else .line2 ?>
<?php if($iOeuvres%2 == 0) : ?>
<div class = "oeuvres">
<div class ="line1">
<?php else : ?>
<div class = "oeuvres">
<div class ="line0">
<?php endif ;?>
<?php while($req->have_posts()) : $req->the_post() ; ?>
<?php //show only 2 posts per line?>
<?php if($iPost<=2):?>
<?php //if iOeuvres is pair, image goes before ?>
<?php if($iOeuvres%2 == 0) : ?>
<div class="oeuvre">
<img class="img-oeuvre" src="<?php bloginfo('stylesheet_directory');?>/ressources/creations/lisemassages.png" alt="">
<div class="infos-oeuvre">
<p><?php the_title() ; ?></p>
<p><?php the_content() ; ?></p>
<a class="btn-oeuvre" href="http://lisemassages.fr" target="_blank">Voir le site</a>
</div><!--fermeture div.infos oeuvre-->
</div><!--fermeture div .oeuvre-->
<?php else : ?>
<div class="oeuvre">
<div class="infos-oeuvre">
<p><?php the_title() ; ?></p>
<p><?php the_content() ; ?></p>
<a class="btn-oeuvre" href="http://lisemassages.fr" target="_blank">Voir le site</a>
</div><!--fermeture div.infos oeuvre-->
<img class="img-oeuvre" src="<?php bloginfo('stylesheet_directory');?>/ressources/creations/lisemassages.png" alt="">
</div><!--fermeture div .oeuvre-->
<?php endif ; ?>
<?php $iPost++ ;?>
<?php else : ?>
<!-- $iPost > 2 : close the bracket -->
<!--of div.line and div oeuvreS -> add 1 div .oeuvreS -->
</div><!--fermeture div .line0/1-->
</div><!--fermeture div .oeuvreS-->
<?php $iPost=1; endif ;?>
<?php endwhile; ?>
<?php $iOeuvres++ ; ?>
<?php endwhile ; ?>
<?php else : ?>
<!-- no post-->
<h1>Rien du tout</h1>
<?php endif ;?>
</code></pre>
<p>I dont know if my code is understable ...my english either... </p>
<p>But my main question is how to keep the value in a innerloop when those are in an another loop .(best example in my mind is like counting room in a hotel : floor 1 : you begin with 1,2....5 and floor 2, you continue with 6,7,8...)</p>
<p>Any help would be great ! </p>
|
[
{
"answer_id": 177978,
"author": "guidod",
"author_id": 14499,
"author_profile": "https://wordpress.stackexchange.com/users/14499",
"pm_score": 1,
"selected": false,
"text": "<p>[Edit]</p>\n\n<p>If I understand correctly, what you call the \"outer loop\" is just for building a two-column layout. If so, you don't need to call two WordPress loops, just open a \"fake\" oeuvres at the beginning, close a \"fake\" oeuvres at the end, do a single loop (a single while have_posts()) and close and re-open an oeuvres DIV every 2 posts (when $iOeuvres%2 == 0).</p>\n\n<p>Let me know if that makes sense.</p>\n\n<p>[original answer]</p>\n\n<p><strong>First problem:</strong> If you do two loops, you should be using different names for the WP_Query objects (for example, $req1 and $req2 instead of two $req). Otherwise, the inner one will override the values from the outer one.</p>\n\n<p><strong>Second problem:</strong> You are missing $req->the_post() on the outer query. That means posts will never advance.</p>\n\n<p>But do you really need a WP Loop within a WP Loop? I don't see any request for posts for the inner query, you only do a single call for WP_Query() on line 3. Maybe if you clarify what you are trying to fetch (which post types, how they nest, etc.) I can help more.</p>\n"
},
{
"answer_id": 178914,
"author": "skytorner",
"author_id": 66650,
"author_profile": "https://wordpress.stackexchange.com/users/66650",
"pm_score": 0,
"selected": false,
"text": "<p>here's the code which generate the right html. Maybe the code needs some improveme nts.</p>\n\n<pre><code> <?php\n\n reqCrea = new WP_Query('category_name=creations'); //objet contenant les posts de la categorie creations\n $cptPosts = $reqCrea->post_count; //nombre de post\n\n ?>\n <?php\n //echo 'cptpost = ' . $cptPosts; \n if ($reqCrea->have_posts()) :\n $i = 0;\n $ligne = 0;\n $sortie = false;\n while ($reqCrea->have_posts()) :\n\n $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail' );\n $url = $thumb['0'];\n echo '<div class=\"oeuvres\">' ; \n // Sortie en cas de nb pairs de post\n if ($i >= $cptPosts - 1 && ($cptPosts % 2 == 0))\n break;\n\n // Post de début de ligne\n the_post();\n\n $ligne = $ligne % 2;\n ?>\n <div class=\"line<?php echo $ligne; ?>\">\n <?php\n do {\n // Impair -> 2eme post sur une meme ligne\n if (($i % 2) != 0) {\n the_post();\n }\n ?> \n <div class=\"oeuvre\">\n <?php if ($ligne == 0): ?> \n <img class=\"img-oeuvre\" src=\"<?php echo $url ; ?>\" alt=\"\">\n <?php endif; ?> \n <div class=\"infos-oeuvre\">\n <p><?php the_title(); ?></p>\n <p><?php the_content(); ?></p>\n <a class=\"btn-oeuvre\" href=\"http://lisemassages.fr\" target=\"_blank\">Voir le site</a>\n </div>\n <?php if ($ligne != 0): ?> \n <img class=\"img-oeuvre\" src=\"<?php echo $url ; ?>\" alt=\"\">\n <?php endif; ?> \n </div>\n\n <?php\n // Sortie en cas de nb impairs de post\n if ($i >= $cptPosts - 1 && ($cptPosts % 2 != 0)) {\n $sortie = true;\n break;\n }\n\n if (($i % 2) == 0) {\n $i++;\n } else {\n $i++;\n break;\n }\n } while ($reqCrea->have_posts());\n if ($sortie)\n break;\n\n $ligne++;\n ?>\n </div>\n <?php\n endwhile;\n else :\n ?>\n </div>\n <h1>Rien du tout</h1>\n <?php endif; ?>\n</code></pre>\n"
}
] |
2015/02/10
|
[
"https://wordpress.stackexchange.com/questions/177723",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66650/"
] |
I know that the question was already asked but all the answer i found doesnt help me..
I made an HTML page that I would like to integrate in Wordpress.
The integration of the theme was done properly until I get to the posts part
I have a problem with algorithms to display posts so I know it comes from the Wordpress loop.
I have done several searches on Wordpress loops but I do not understand the different uses.
Here is the HTML code base that I would like to loop :
```
<div class="oeuvres">
<div class="line0"><!-- should be dynamic -->
<div class="oeuvre">
<img class="img-oeuvre" src="ressources/creations/lisemassages.png" alt="">
<div class="infos-oeuvre">
<p>Title</p>
<p>Content</p>
<a class="btn-oeuvre" href="" target="_blank">Voir le site</a>
</div>
</div>
<div class="oeuvre">
<img class="img-oeuvre" src="ressources/creations/centredesoi.png" alt="">
<div class="infos-oeuvre">
<p>Title</p>
<p>Content</p>
<a class="btn-oeuvre" href="" target="_blank">voir le site</a>
</div>
</div>
</div><!--class line0 -->
</div>
<div class="oeuvres">
<div class="line1"><!--Should be dynamic-->
<div class="oeuvre">
<div class="infos-oeuvre">
<p>title</p>
<p>Content</p>
<a class="btn-oeuvre" href="" target="_blank">Voir le site</a>
</div>
<img class="img-oeuvre" src="ressources/creations/comparepc.png" alt="">
</div>
<div class="oeuvre">
<div class="infos-oeuvre">
<p>Title</p>
<p>Content</p>
<a class="btn-oeuvre" href="" target="_blank">voir nos créations</a>
</div>
<img class="img-oeuvre" src="ressources/creations/wine&sound.jpg" alt="">
</div>
</div><!--class line1 -->
</div>
```
Here's the code i've already done but i got some problem : there's only 3 articles which are repeated :
```
<?php
//Variables needed for the template
$req = new WP_Query('category_name=creations') ; //object with the posts
$cptPosts = $req->post_count ; //nomber of post
$cptOeuvres = $cptPosts/2 ; //number of div .Oeuvres needed
$iOeuvres = 1 ; //counter of div.oeuvres
$iPost = 1 ; //counter of posts
?>
<?php echo 'cptpost = '.$cptPosts ; echo 'cptoeuvres = '.$cptOeuvres ;// to check $cptPost/$cptoeuvres value ?>
<?php if ($req->have_posts()) : ?>
<?php while($iOeuvres <= $cptOeuvres): ?>
<?php //if $iOeuvres is pair use .line1 else .line2 ?>
<?php if($iOeuvres%2 == 0) : ?>
<div class = "oeuvres">
<div class ="line1">
<?php else : ?>
<div class = "oeuvres">
<div class ="line0">
<?php endif ;?>
<?php while($req->have_posts()) : $req->the_post() ; ?>
<?php //show only 2 posts per line?>
<?php if($iPost<=2):?>
<?php //if iOeuvres is pair, image goes before ?>
<?php if($iOeuvres%2 == 0) : ?>
<div class="oeuvre">
<img class="img-oeuvre" src="<?php bloginfo('stylesheet_directory');?>/ressources/creations/lisemassages.png" alt="">
<div class="infos-oeuvre">
<p><?php the_title() ; ?></p>
<p><?php the_content() ; ?></p>
<a class="btn-oeuvre" href="http://lisemassages.fr" target="_blank">Voir le site</a>
</div><!--fermeture div.infos oeuvre-->
</div><!--fermeture div .oeuvre-->
<?php else : ?>
<div class="oeuvre">
<div class="infos-oeuvre">
<p><?php the_title() ; ?></p>
<p><?php the_content() ; ?></p>
<a class="btn-oeuvre" href="http://lisemassages.fr" target="_blank">Voir le site</a>
</div><!--fermeture div.infos oeuvre-->
<img class="img-oeuvre" src="<?php bloginfo('stylesheet_directory');?>/ressources/creations/lisemassages.png" alt="">
</div><!--fermeture div .oeuvre-->
<?php endif ; ?>
<?php $iPost++ ;?>
<?php else : ?>
<!-- $iPost > 2 : close the bracket -->
<!--of div.line and div oeuvreS -> add 1 div .oeuvreS -->
</div><!--fermeture div .line0/1-->
</div><!--fermeture div .oeuvreS-->
<?php $iPost=1; endif ;?>
<?php endwhile; ?>
<?php $iOeuvres++ ; ?>
<?php endwhile ; ?>
<?php else : ?>
<!-- no post-->
<h1>Rien du tout</h1>
<?php endif ;?>
```
I dont know if my code is understable ...my english either...
But my main question is how to keep the value in a innerloop when those are in an another loop .(best example in my mind is like counting room in a hotel : floor 1 : you begin with 1,2....5 and floor 2, you continue with 6,7,8...)
Any help would be great !
|
[Edit]
If I understand correctly, what you call the "outer loop" is just for building a two-column layout. If so, you don't need to call two WordPress loops, just open a "fake" oeuvres at the beginning, close a "fake" oeuvres at the end, do a single loop (a single while have\_posts()) and close and re-open an oeuvres DIV every 2 posts (when $iOeuvres%2 == 0).
Let me know if that makes sense.
[original answer]
**First problem:** If you do two loops, you should be using different names for the WP\_Query objects (for example, $req1 and $req2 instead of two $req). Otherwise, the inner one will override the values from the outer one.
**Second problem:** You are missing $req->the\_post() on the outer query. That means posts will never advance.
But do you really need a WP Loop within a WP Loop? I don't see any request for posts for the inner query, you only do a single call for WP\_Query() on line 3. Maybe if you clarify what you are trying to fetch (which post types, how they nest, etc.) I can help more.
|
177,784 |
<p>I am building a more-or-less distinguishing layout which forces me have a header far above the content in the DOM. A structure as follows:</p>
<pre><code><?php get_header(); ?>
<div id="wrapper">
<header class="entry-header" style="background-image:url({url-to-post-thumbnail-of-current-post});">
<h1 class="entry-title">{title-of-current-post}
<span class="date">
<time class="entry-date" datetime="{the-time-c}">{the-time}</time>
</span>
</h1>
</header><!-- .entry-header -->
<section id="main">
<div id="main-content">
<?php
while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
endwhile;
?>
</div>
</section>
<!-- section#main -->
<?php require_once(trailingslashit(get_template_directory()) . "php/single-secondary.php"); ?>
</div>
<!-- div#wrapper -->
<?php get_footer(); ?>
</code></pre>
<p>As you can see I need to get information of the current post in <code>header</code>, but it's outside the loop and I'm not sure how to get that information outside the loop. Maybe I can run an additional loop, but wouldn't that cause overhead? Or can I extend the loop in a way?</p>
|
[
{
"answer_id": 177764,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>The difference is that capabilities are part of the access permission system of the site, which utilize and can be changed by the built-in tools and APIs that are designed to handle permissions. You can create your own permission scheme but then it will not be easy to override with tools or code that expect access permissions to be handled in capabilities.</p>\n\n<p>By using meta fields instead of capabilities you also lose the ability to group users into roles, which might or might not be important.</p>\n\n<p>Your question highlights again one of the soft points in WordPress core, the lack of separation between content author and site user. When you think of a user as a user of the site, you should go capabilities, but if your code handles a user as a content author, you might do better by using meta fields.</p>\n\n<p>As for the specific example in the edit part. This falls nicely into access control and you even need it for actual roles, therefor capabilities is the way to go.</p>\n"
},
{
"answer_id": 177766,
"author": "Ruturaj",
"author_id": 43266,
"author_profile": "https://wordpress.stackexchange.com/users/43266",
"pm_score": 1,
"selected": false,
"text": "<p>User Capabilities will allow you set site-wide access settings for a specific User/User Account Type whereas the meta-data allows you to make settings individually for each Post/Page or anything that supports Meta in Wordpress. In other words, Capabilities are part of ACL (Access Control Layer) whereas Meta is best when used for Data Presentation.</p>\n\n<p>User Capabilities are best if you're writing an application that uses certain access control in global scope of your application whereas the User Meta is best if you want to apply restriction per Post/Page. Note that, if you control ACL using Capabilities, you will just need to create a User account of specific User Type in order to apply certain restrictions; however you will need to make sure you (manually) add specific Meta value to every Post, Page that you want to apply ACL to. </p>\n\n<p>Use of Capabilities and Meta is very much application specific and I'm afraid if I can generalize the best scenarios for you to define which is best among the two.</p>\n"
},
{
"answer_id": 177776,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 4,
"selected": true,
"text": "<p>There is no one answer, because both have pros and cons depending on what you want to store and why.</p>\n\n<p>A (probably non-exhaustive) list of differences to consider for a choice:</p>\n\n<ul>\n<li><p>Capabilities are designed to check if a user can <em>do</em> something or not. <code>user_can</code> and <code>current_user_can</code> are there to help you to check user permissions. You can implement that with user meta too, but makes no sense once you have that feature in core.</p></li>\n<li><p>There is no doubt that capabilities can be used to <em>group</em> users with similar characteristics, even if the groups are not related to permissions. In that case capabilities are for users somewhat similar to what taxonomy terms are for posts. <code>user_can</code> function can be used to check if a user has a capability or not (similar to <code>has_term</code>) but there is no core function that does the same for meta. However, retrieve a collection of users by capabilities is probably more expensive than retrieve users by a simple meta query (it's a guess, not based on real performance profiling data).</p></li>\n<li><p>To filter <em>on the fly</em> (without db change) <strong>all</strong> the capabilities assigned to a user is pretty easy (especially if cap are checked with <code>user_can</code> / <code>current_user_can</code> and there is no reason why not), while doing the same for meta is much harder.</p></li>\n<li><p>Meta can handle nested data (e.g. arrays and even different (sets of) values for same meta key). That's not possible with capabilities.</p></li>\n<li><p>Capabilities can be grouped in roles. And roles also have a UI in the backend that allows assigning a \"set\" of capabilities by assigning a role. There is no such benefit for meta.</p></li>\n<li><p>Capabilities are independent entities from users, and they survive users: if you delete all users that have a capability, it stays there. The same does not apply to meta: all meta goes with a user if it is deleted.</p></li>\n</ul>\n\n<h2>Edit</h2>\n\n<p>After the edit on the OP, I would say that capabilities are much better: you are implementing with meta something that core already does with capabilities, and is exactly what capabilities are intended to be.</p>\n\n<p>As example, think to <a href=\"https://developer.wordpress.org/reference/functions/add_menu_page/\" rel=\"nofollow\"><code>add_menu_page</code></a> function, it has a <code>$capability</code> argument that lets you show a menu page only to users that have that capability.</p>\n\n<p>This is only an example, there are different functions that accept capabilities as an argument.\nMoreover, as said in first point before the edit, it makes no sense to implement <em>from scratch</em> a feature that core already has.</p>\n"
}
] |
2015/02/11
|
[
"https://wordpress.stackexchange.com/questions/177784",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16574/"
] |
I am building a more-or-less distinguishing layout which forces me have a header far above the content in the DOM. A structure as follows:
```
<?php get_header(); ?>
<div id="wrapper">
<header class="entry-header" style="background-image:url({url-to-post-thumbnail-of-current-post});">
<h1 class="entry-title">{title-of-current-post}
<span class="date">
<time class="entry-date" datetime="{the-time-c}">{the-time}</time>
</span>
</h1>
</header><!-- .entry-header -->
<section id="main">
<div id="main-content">
<?php
while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
endwhile;
?>
</div>
</section>
<!-- section#main -->
<?php require_once(trailingslashit(get_template_directory()) . "php/single-secondary.php"); ?>
</div>
<!-- div#wrapper -->
<?php get_footer(); ?>
```
As you can see I need to get information of the current post in `header`, but it's outside the loop and I'm not sure how to get that information outside the loop. Maybe I can run an additional loop, but wouldn't that cause overhead? Or can I extend the loop in a way?
|
There is no one answer, because both have pros and cons depending on what you want to store and why.
A (probably non-exhaustive) list of differences to consider for a choice:
* Capabilities are designed to check if a user can *do* something or not. `user_can` and `current_user_can` are there to help you to check user permissions. You can implement that with user meta too, but makes no sense once you have that feature in core.
* There is no doubt that capabilities can be used to *group* users with similar characteristics, even if the groups are not related to permissions. In that case capabilities are for users somewhat similar to what taxonomy terms are for posts. `user_can` function can be used to check if a user has a capability or not (similar to `has_term`) but there is no core function that does the same for meta. However, retrieve a collection of users by capabilities is probably more expensive than retrieve users by a simple meta query (it's a guess, not based on real performance profiling data).
* To filter *on the fly* (without db change) **all** the capabilities assigned to a user is pretty easy (especially if cap are checked with `user_can` / `current_user_can` and there is no reason why not), while doing the same for meta is much harder.
* Meta can handle nested data (e.g. arrays and even different (sets of) values for same meta key). That's not possible with capabilities.
* Capabilities can be grouped in roles. And roles also have a UI in the backend that allows assigning a "set" of capabilities by assigning a role. There is no such benefit for meta.
* Capabilities are independent entities from users, and they survive users: if you delete all users that have a capability, it stays there. The same does not apply to meta: all meta goes with a user if it is deleted.
Edit
----
After the edit on the OP, I would say that capabilities are much better: you are implementing with meta something that core already does with capabilities, and is exactly what capabilities are intended to be.
As example, think to [`add_menu_page`](https://developer.wordpress.org/reference/functions/add_menu_page/) function, it has a `$capability` argument that lets you show a menu page only to users that have that capability.
This is only an example, there are different functions that accept capabilities as an argument.
Moreover, as said in first point before the edit, it makes no sense to implement *from scratch* a feature that core already has.
|
177,785 |
<p>I am trying to apply wordpress filter hook get_the_expert. My intention is to apply filter only when the category slug is "MY-CATEGORY-SLUG". How can I check the category slug inside the filter hook function.</p>
<p>Thanks</p>
|
[
{
"answer_id": 177793,
"author": "David Gard",
"author_id": 10097,
"author_profile": "https://wordpress.stackexchange.com/users/10097",
"pm_score": 0,
"selected": false,
"text": "<p>If I have understood your question correctly, this code below should help you (place it in <strong>functions.php</strong>).</p>\n\n<pre><code>function my_filter_the_excerpt($excerpt){\n\n global $post;\n\n /** Return the excerpt only if the post is in the category 'MY-CATEGORY-SLUG' */\n return (in_category('MY-CATEGORY-SLUG', $post) ? $excerpt : ''; \n\n}\n</code></pre>\n\n<p>Just in case you are unsure of where this code should go, I'd recommend addig the filter just before your Loop starts, and then removing it at the end -</p>\n\n<pre><code>add_filter('get_the_excerpt', 'my_filter_the_excerpt');\nif(have_posts()) : while(have_posts()) : the_post();\n\n { your code }\n\n endwhile;\nendif;\nremove_filter('get_the_excerpt', 'my_filter_the_excerpt');\n</code></pre>\n\n<p>For more information, I'd recommend having a look at the following documents -</p>\n\n<ul>\n<li><a href=\"http://codex.wordpress.org/Plugin_API/Filter_Reference/get_the_excerpt\" rel=\"nofollow\">The <code>get_the_excerpt</code> filter</a></li>\n<li><a href=\"http://codex.wordpress.org/Function_Reference/wp_get_post_categories\" rel=\"nofollow\">The <code>wp_get_post_categories()</code> function</a></li>\n</ul>\n"
},
{
"answer_id": 177796,
"author": "Pramod Sivadas",
"author_id": 47454,
"author_profile": "https://wordpress.stackexchange.com/users/47454",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks for the response David. I found the solution. I added the following code in functions.php</p>\n\n<pre><code>add_filter('get_the_excerpt', 'process_excerpt');\n\nfunction process_excerpt($param) {\n global $post;\n if(in_category('MY-CATEGORY-SLUG',$post))\n return 'adding some data'.$param;\n else\n return $param;\n}\n</code></pre>\n\n<p>This fixed my issue.</p>\n"
},
{
"answer_id": 177797,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 0,
"selected": false,
"text": "<p>As you are inside the loop and you want to <strong>apply the filter</strong> only when the current post is assigned to specific category, you could do something like this in the loop:</p>\n\n<pre><code>if( have_posts() ) {\n while( have_posts() ) {\n\n the_post();\n\n if( in_category( 'MY-CATEGORY-SLUG', get_the_ID() ) ) {\n //The post is assigned to \"MY-CATEGORY-SLUG\", add the filter\n add_filter('get_the_excerpt', 'filter_the_excerpt');\n } else {\n //The post is NOT assigned to \"MY-CATEGORY-SLUG\", remove the filter\n remove_filter('get_the_excerpt', 'filter_the_excerpt');\n }\n\n }\n}\n</code></pre>\n\n<p>But I think you should <strong>apply the filter always</strong> and check the category inside the filter, so you can avoid the checking in the loop in order to keep the loop and themplates clean:</p>\n\n<pre><code>add_filter('get_the_excerpt', 'filter_the_excerpt');\nfunction my_filter_the_excerpt( $excerpt ){\n\n if( in_category( 'MY-CATEGORY-SLUG', get_the_ID() ) ) {\n //The post is assigned to \"MY-CATEGORY-SLUG\"\n //Do whatever you want\n } else {\n //The post is NOT assigned to \"MY-CATEGORY-SLUG\"\n //Do whatever you want\n }\n\n\n}\n</code></pre>\n"
}
] |
2015/02/11
|
[
"https://wordpress.stackexchange.com/questions/177785",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47454/"
] |
I am trying to apply wordpress filter hook get\_the\_expert. My intention is to apply filter only when the category slug is "MY-CATEGORY-SLUG". How can I check the category slug inside the filter hook function.
Thanks
|
Thanks for the response David. I found the solution. I added the following code in functions.php
```
add_filter('get_the_excerpt', 'process_excerpt');
function process_excerpt($param) {
global $post;
if(in_category('MY-CATEGORY-SLUG',$post))
return 'adding some data'.$param;
else
return $param;
}
```
This fixed my issue.
|
177,823 |
<p>I've tried <code>get_site_url();</code>, <code>get_bloginfo('wpurl')</code> and <code>home_url();</code> but they're all giving me a link to the current page rather than the home page.</p>
|
[
{
"answer_id": 177824,
"author": "Badger",
"author_id": 66660,
"author_profile": "https://wordpress.stackexchange.com/users/66660",
"pm_score": 1,
"selected": false,
"text": "<p>Just figured out the answer. It needs to be echo'd, so <code>echo site_url</code> works. Or to use in a template <code><?= site_url(); ?></code></p>\n"
},
{
"answer_id": 178758,
"author": "MD MUSA",
"author_id": 65945,
"author_profile": "https://wordpress.stackexchange.com/users/65945",
"pm_score": 3,
"selected": true,
"text": "<p><code>echo esc_url( home_url( '/' ) );</code> this best practice.</p>\n\n<pre><code>get_bloginfo( $show, $filter );\n</code></pre>\n\n<p>It has lots of Parameters to get info so\nlet see the <strong>##SHOW(Parameters)</strong>:\nname,description,wpurl,url,admin_email,charset,version,html_type,text_direction,language,stylesheet_url,stylesheet_directory,template_url,pingback_url,atom_url,rdf_url,rss_url,rss2_url,comments_atom_url,comments_rss2_url,siteurl,home\nso if you want to use this finction you have to use like get_bloginfo('wpurl'); or get_bloginfo('url');</p>\n\n<p>These two functions home_url() and site_url() return the same value (WordPress address or URL) if WordPress hasn’t been given its own directory.Say you installed a WordPress blog in the root folder of example(dot)com but the core WordPress files was moved to a sub-directory named wp-core.The function home_url() will return example(dot)com and site_url() will return example(dot)com/wp-core.</p>\n\n<p><strong>A few notes:</strong></p>\n\n<ol>\n<li>home_url() will only return the mapped domain on or after the init has fired. Calling it before then will return the wordpress.com domain.</li>\n<li>If you accidentally use site_url() in your templates, theme-side links will still redirect correctly to the home_url() equivalent.</li>\n<li>home_url() is the preferred method, as it avoids the above redirect.</li>\n</ol>\n\n<p>I think you are clear about this what you need to use for your work :)\nHappy Coding :)\nMusa</p>\n"
}
] |
2015/02/11
|
[
"https://wordpress.stackexchange.com/questions/177823",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66660/"
] |
I've tried `get_site_url();`, `get_bloginfo('wpurl')` and `home_url();` but they're all giving me a link to the current page rather than the home page.
|
`echo esc_url( home_url( '/' ) );` this best practice.
```
get_bloginfo( $show, $filter );
```
It has lots of Parameters to get info so
let see the **##SHOW(Parameters)**:
name,description,wpurl,url,admin\_email,charset,version,html\_type,text\_direction,language,stylesheet\_url,stylesheet\_directory,template\_url,pingback\_url,atom\_url,rdf\_url,rss\_url,rss2\_url,comments\_atom\_url,comments\_rss2\_url,siteurl,home
so if you want to use this finction you have to use like get\_bloginfo('wpurl'); or get\_bloginfo('url');
These two functions home\_url() and site\_url() return the same value (WordPress address or URL) if WordPress hasn’t been given its own directory.Say you installed a WordPress blog in the root folder of example(dot)com but the core WordPress files was moved to a sub-directory named wp-core.The function home\_url() will return example(dot)com and site\_url() will return example(dot)com/wp-core.
**A few notes:**
1. home\_url() will only return the mapped domain on or after the init has fired. Calling it before then will return the wordpress.com domain.
2. If you accidentally use site\_url() in your templates, theme-side links will still redirect correctly to the home\_url() equivalent.
3. home\_url() is the preferred method, as it avoids the above redirect.
I think you are clear about this what you need to use for your work :)
Happy Coding :)
Musa
|
177,828 |
<p>I have a custom taxonomy which I want to appear under a custom menu. And I achieved that by specifying the custom menu as the parent. Here's the result:</p>
<p><img src="https://i.stack.imgur.com/0Wu5m.png" alt=""></p>
<p>However, when I click on it, the CSV Tag Upload menu collapses, and the taxonomy opens itself under the Posts menu:</p>
<p><img src="https://i.stack.imgur.com/Mhac2.png" alt="enter image description here"></p>
<p>Any idea why this happens and how I can fix it? I've been having this problem for a long time now, but it's becoming a problem now.</p>
<p><strong>EDIT:</strong>
Code for registering taxonomy:</p>
<pre><code>function csv_tags_taxonomy() {
$labels = array(
'name' => _x( 'CSV Tags', 'taxonomy general name' ),
'singular_name' => _x( 'Tag', 'taxonomy singular name' ),
'search_items' => __( 'Search Tags' ),
'popular_items' => __( 'Popular Tags' ),
'all_items' => __( 'All Tags' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit Tag' ),
'update_item' => __( 'Update Tag' ),
'add_new_item' => __( 'Add New Tag' ),
'new_item_name' => __( 'New Tag Name' ),
'separate_items_with_commas' => __( 'Separate tags with commas' ),
'add_or_remove_items' => __( 'Add or remove tags' ),
'choose_from_most_used' => __( 'Choose from the most used tags' ),
'menu_name' => __( 'CSV Tags' ),
);
register_taxonomy('csv_tags','post',array(
'hierarchical' => false,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'update_count_callback' => '_update_post_term_count',
'query_var' => true,
'rewrite' => array( 'slug' => 'csv-tags' ),
));
}
add_action('init', 'csv_tags_taxonomy');
</code></pre>
|
[
{
"answer_id": 177824,
"author": "Badger",
"author_id": 66660,
"author_profile": "https://wordpress.stackexchange.com/users/66660",
"pm_score": 1,
"selected": false,
"text": "<p>Just figured out the answer. It needs to be echo'd, so <code>echo site_url</code> works. Or to use in a template <code><?= site_url(); ?></code></p>\n"
},
{
"answer_id": 178758,
"author": "MD MUSA",
"author_id": 65945,
"author_profile": "https://wordpress.stackexchange.com/users/65945",
"pm_score": 3,
"selected": true,
"text": "<p><code>echo esc_url( home_url( '/' ) );</code> this best practice.</p>\n\n<pre><code>get_bloginfo( $show, $filter );\n</code></pre>\n\n<p>It has lots of Parameters to get info so\nlet see the <strong>##SHOW(Parameters)</strong>:\nname,description,wpurl,url,admin_email,charset,version,html_type,text_direction,language,stylesheet_url,stylesheet_directory,template_url,pingback_url,atom_url,rdf_url,rss_url,rss2_url,comments_atom_url,comments_rss2_url,siteurl,home\nso if you want to use this finction you have to use like get_bloginfo('wpurl'); or get_bloginfo('url');</p>\n\n<p>These two functions home_url() and site_url() return the same value (WordPress address or URL) if WordPress hasn’t been given its own directory.Say you installed a WordPress blog in the root folder of example(dot)com but the core WordPress files was moved to a sub-directory named wp-core.The function home_url() will return example(dot)com and site_url() will return example(dot)com/wp-core.</p>\n\n<p><strong>A few notes:</strong></p>\n\n<ol>\n<li>home_url() will only return the mapped domain on or after the init has fired. Calling it before then will return the wordpress.com domain.</li>\n<li>If you accidentally use site_url() in your templates, theme-side links will still redirect correctly to the home_url() equivalent.</li>\n<li>home_url() is the preferred method, as it avoids the above redirect.</li>\n</ol>\n\n<p>I think you are clear about this what you need to use for your work :)\nHappy Coding :)\nMusa</p>\n"
}
] |
2015/02/11
|
[
"https://wordpress.stackexchange.com/questions/177828",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67400/"
] |
I have a custom taxonomy which I want to appear under a custom menu. And I achieved that by specifying the custom menu as the parent. Here's the result:

However, when I click on it, the CSV Tag Upload menu collapses, and the taxonomy opens itself under the Posts menu:

Any idea why this happens and how I can fix it? I've been having this problem for a long time now, but it's becoming a problem now.
**EDIT:**
Code for registering taxonomy:
```
function csv_tags_taxonomy() {
$labels = array(
'name' => _x( 'CSV Tags', 'taxonomy general name' ),
'singular_name' => _x( 'Tag', 'taxonomy singular name' ),
'search_items' => __( 'Search Tags' ),
'popular_items' => __( 'Popular Tags' ),
'all_items' => __( 'All Tags' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit Tag' ),
'update_item' => __( 'Update Tag' ),
'add_new_item' => __( 'Add New Tag' ),
'new_item_name' => __( 'New Tag Name' ),
'separate_items_with_commas' => __( 'Separate tags with commas' ),
'add_or_remove_items' => __( 'Add or remove tags' ),
'choose_from_most_used' => __( 'Choose from the most used tags' ),
'menu_name' => __( 'CSV Tags' ),
);
register_taxonomy('csv_tags','post',array(
'hierarchical' => false,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'update_count_callback' => '_update_post_term_count',
'query_var' => true,
'rewrite' => array( 'slug' => 'csv-tags' ),
));
}
add_action('init', 'csv_tags_taxonomy');
```
|
`echo esc_url( home_url( '/' ) );` this best practice.
```
get_bloginfo( $show, $filter );
```
It has lots of Parameters to get info so
let see the **##SHOW(Parameters)**:
name,description,wpurl,url,admin\_email,charset,version,html\_type,text\_direction,language,stylesheet\_url,stylesheet\_directory,template\_url,pingback\_url,atom\_url,rdf\_url,rss\_url,rss2\_url,comments\_atom\_url,comments\_rss2\_url,siteurl,home
so if you want to use this finction you have to use like get\_bloginfo('wpurl'); or get\_bloginfo('url');
These two functions home\_url() and site\_url() return the same value (WordPress address or URL) if WordPress hasn’t been given its own directory.Say you installed a WordPress blog in the root folder of example(dot)com but the core WordPress files was moved to a sub-directory named wp-core.The function home\_url() will return example(dot)com and site\_url() will return example(dot)com/wp-core.
**A few notes:**
1. home\_url() will only return the mapped domain on or after the init has fired. Calling it before then will return the wordpress.com domain.
2. If you accidentally use site\_url() in your templates, theme-side links will still redirect correctly to the home\_url() equivalent.
3. home\_url() is the preferred method, as it avoids the above redirect.
I think you are clear about this what you need to use for your work :)
Happy Coding :)
Musa
|
177,852 |
<p>I changed my WordPress site to use child themes, but the parent theme style has priority over any change I make on the child theme CSS. I can work around it using <code>!important</code>, however this is a patchy solution and the child themes should work as the site's first resource. </p>
<p>For example, in <a href="http://blindalleycomic.com/" rel="noreferrer">my site</a>, the border that includes <code>.wp-caption</code> is the same color as the background using the <code>!important</code> tag, but won't work without it. </p>
<p>Does this have to do with the functions.php file?</p>
<p>This is the contents of my PHP file:</p>
<pre><code>add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
</code></pre>
|
[
{
"answer_id": 177858,
"author": "Twodogstar",
"author_id": 67417,
"author_profile": "https://wordpress.stackexchange.com/users/67417",
"pm_score": 0,
"selected": false,
"text": "<p>You can use a more specific selector in your child theme's CSS so that it takes precedence. </p>\n\n<p>So instead of:</p>\n\n<pre>\n\n.wp-caption {\n background: #2d2d2d !important;\n}\n\n</pre>\n\n<p>Use: </p>\n\n<pre>\n\n.entry .wp-caption {\n background: #2d2d2d;\n}\n\n</pre>\n\n<p>You'll also want to be sure to enqueue your child theme stylesheet in your functions.php file if you aren't already.</p>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/wp_enqueue_style\" rel=\"nofollow\">http://codex.wordpress.org/Function_Reference/wp_enqueue_style</a></p>\n"
},
{
"answer_id": 177861,
"author": "rambillo",
"author_id": 67420,
"author_profile": "https://wordpress.stackexchange.com/users/67420",
"pm_score": 6,
"selected": true,
"text": "<p>Try enqueuing your child theme's CSS like so:</p>\n\n<pre><code>// Queue parent style followed by child/customized style\nadd_action( 'wp_enqueue_scripts', 'theme_enqueue_styles', PHP_INT_MAX);\n\nfunction theme_enqueue_styles() {\n wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );\n wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/styles/child-style.css', array( 'parent-style' ) );\n}\n</code></pre>\n\n<p>Notice a few things:<br><br>\n1) PHP_INT_MAX as priority so that this runs last<br><br>\n2) get_stylesheet_directory_uri() vs. get_template_directory_uri() which will point to the child theme's template folder instead of the parents.<br><br>I added a subfolder there, as well <code>/styles/</code> because I keep my CSS in a subfolder of my theme normally.<br><br>\n3) followed by <code>array( 'parent-style' )</code> to make the child CSS have the parent CSS as a dependency, which has the effect of putting the parent theme first in the head and the child theme CSS following it. Because of that, whatever also appears in the child theme that is already in the parent theme will overwrite the parent theme's version.</p>\n"
},
{
"answer_id": 223104,
"author": "Henrik Erlandsson",
"author_id": 24829,
"author_profile": "https://wordpress.stackexchange.com/users/24829",
"pm_score": 2,
"selected": false,
"text": "<p>TLDR answer: first parameter of each <code>wp_enqueue_style()</code> should not be left as 'parent-style' and 'child-style'. They should be <strong><em>renamed</em></strong> to match the name of the parent theme and its child.</p>\n\n<p><strong>Problem</strong></p>\n\n<p>If you don't rename the parameters, you will get the child theme enqueued a second time can result in rules appearing twice in Firebug and changing values in the wrong one having no apparent effect, which may trick you into thinking your child rules don't override the parent.</p>\n\n<p><strong>The expectation</strong></p>\n\n<p>The <a href=\"http://codex.wordpress.org/Child_Themes\" rel=\"nofollow\">Codex page on Child Themes</a> correctly says that if you do nothing, the child CSS is linked automatically. It does, but only that. CSS workflow is a bit different: you want to override, not replace. It's logical (it works like the other theme files) but they could have had a note. </p>\n\n<p><strong>Solution</strong></p>\n\n<p>Rename the parameters. I do it like below to get (a little) more control, <strong>note</strong> that you should replace <em>twentysixteen</em> and <em>twentysixteen-child</em> with the names of your theme and child theme:</p>\n\n<pre><code>function theme_enqueue_scripts() {\n //FIRST\n wp_enqueue_style( 'twentysixteen-style', get_template_directory_uri() . '/style.css' );\n\n //...custom queueing of .js and .css for Javascript plugins and such here\n\n //LAST\n wp_enqueue_style( 'twentysixteen-child-style', get_stylesheet_directory_uri() . '/style.css', array( 'twentysixteen-style' ) );\n}\nadd_action( 'wp_enqueue_scripts', 'theme_enqueue_scripts' );\n</code></pre>\n\n<p>(Also note that you don't get control of the link order of some (all?) WP plugins in this action. They get linked after.)</p>\n\n<p>Happy selector-hunting ;)</p>\n"
},
{
"answer_id": 402533,
"author": "Azodium",
"author_id": 117416,
"author_profile": "https://wordpress.stackexchange.com/users/117416",
"pm_score": 0,
"selected": false,
"text": "<p>The solution proposed by Rambillo didn't work for me. I did this, and now it's ok :</p>\n<pre><code>function my_theme_enqueue_styles() {\n wp_enqueue_style( 'name-child-style', get_stylesheet_directory_uri() . '/style.css' );\n }\n add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', PHP_INT_MAX );\n</code></pre>\n"
}
] |
2015/02/11
|
[
"https://wordpress.stackexchange.com/questions/177852",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67414/"
] |
I changed my WordPress site to use child themes, but the parent theme style has priority over any change I make on the child theme CSS. I can work around it using `!important`, however this is a patchy solution and the child themes should work as the site's first resource.
For example, in [my site](http://blindalleycomic.com/), the border that includes `.wp-caption` is the same color as the background using the `!important` tag, but won't work without it.
Does this have to do with the functions.php file?
This is the contents of my PHP file:
```
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
```
|
Try enqueuing your child theme's CSS like so:
```
// Queue parent style followed by child/customized style
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles', PHP_INT_MAX);
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/styles/child-style.css', array( 'parent-style' ) );
}
```
Notice a few things:
1) PHP\_INT\_MAX as priority so that this runs last
2) get\_stylesheet\_directory\_uri() vs. get\_template\_directory\_uri() which will point to the child theme's template folder instead of the parents.
I added a subfolder there, as well `/styles/` because I keep my CSS in a subfolder of my theme normally.
3) followed by `array( 'parent-style' )` to make the child CSS have the parent CSS as a dependency, which has the effect of putting the parent theme first in the head and the child theme CSS following it. Because of that, whatever also appears in the child theme that is already in the parent theme will overwrite the parent theme's version.
|
177,864 |
<p>In 'Reading Settings' I have chosen the static-page drop-down menu of a page I created to be the post page. </p>
<p>I've put the html, php, and css from my page.php in index.php to style it. I'm unable to get the featured image. The php I use to get it on page.php isn't working. It's not rendering any html. Also <code><?php the_title(); ?></code> is pulling up the title of the most recent blog post, not the page title of the page I have switched over.</p>
<p>This is how I"m generating the featured image on page.php</p>
<pre><code> <div class="single-image-anchor">
<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<div class="single-image" style="background-image: url('<?php echo $image[0]; ?>')">
<?php endif; ?>
</div>
</code></pre>
<p>I am fairly new to Wordpress so thanks in advance. </p>
|
[
{
"answer_id": 177903,
"author": "Brad Dalton",
"author_id": 9884,
"author_profile": "https://wordpress.stackexchange.com/users/9884",
"pm_score": 0,
"selected": false,
"text": "<p>One example is Twenty Fifteen which uses a template tag in the content.php files like this:</p>\n\n<pre><code>twentyfifteen_post_thumbnail();\n</code></pre>\n\n<p>And then the function for the template tag in inc/template-tags.php:</p>\n\n<pre><code>if ( ! function_exists( 'twentyfifteen_post_thumbnail' ) ) :\n/**\n * Display an optional post thumbnail.\n *\n * Wraps the post thumbnail in an anchor element on index views, or a div\n * element when on single views.\n *\n * @since Twenty Fifteen 1.0\n */\nfunction twentyfifteen_post_thumbnail() {\n if ( post_password_required() || is_attachment() || ! has_post_thumbnail() ) {\n return;\n }\n\n if ( is_singular() ) :\n ?>\n\n <div class=\"post-thumbnail\">\n <?php the_post_thumbnail(); ?>\n </div><!-- .post-thumbnail -->\n\n <?php else : ?>\n\n <a class=\"post-thumbnail\" href=\"<?php the_permalink(); ?>\" aria-hidden=\"true\">\n <?php\n the_post_thumbnail( 'post-thumbnail', array( 'alt' => get_the_title() ) );\n ?>\n </a>\n\n <?php endif; // End is_singular()\n}\nendif;\n</code></pre>\n\n<p>Not sure i understand your title question however you can take a look in the archive.php file and you'll see this code to display the archive page title:</p>\n\n<pre><code><header class=\"page-header\">\n <?php\n the_archive_title( '<h1 class=\"page-title\">', '</h1>' );\n the_archive_description( '<div class=\"taxonomy-description\">', '</div>' );\n ?>\n </header><!-- .page-header -->\n</code></pre>\n"
},
{
"answer_id": 177986,
"author": "RLM",
"author_id": 60779,
"author_profile": "https://wordpress.stackexchange.com/users/60779",
"pm_score": 0,
"selected": false,
"text": "<pre><code> <div class=\"page-section clear\">\n <div class=\"single-image-anchor\">\n <?php if (get_option( 'page_for_posts' ) ): ?>\n <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( get_option( 'page_for_posts' )), 'single-post-thumbnail' ); ?>\n <div class=\"single-image\" style=\"background-image: url('<?php echo $image[0]; ?>')\">\n <?php endif; ?>\n </div>\n </div>\n <h1 class='title'><?php if(get_option( 'page_for_posts' ) ) echo get_the_title( get_option( 'page_for_posts' ) ); ?> </h2>\n <h1><?php _e( 'Latest Posts', 'html5blank' ); ?></h1> \n</code></pre>\n"
},
{
"answer_id": 239637,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>This is not trivial to do as once you have set a specific page to be an aggregation of posts (being a posts page), wordpress will \"forget\" the initial information it gets of the page itself and will behave like it was a normal home page of a blog. This means that all the global variables used in the loop will <strong>not</strong> be ralated and will not indicate the page itself, and therefor API like <code>the_title</code> that rely on the global information will not return the same values as it would have if it was a normal page.</p>\n\n<p>The way to solve this, is to create a specific page template to be used with this page, and in it use <code>get_option( 'page_for_posts' )</code> as the post id parameter used to all the API calls that you make, so instead of <code>has_post_thumbnail( $post->ID )</code> you will have <code>has_post_thumbnail( get_option( 'page_for_posts' ) )</code></p>\n"
}
] |
2015/02/12
|
[
"https://wordpress.stackexchange.com/questions/177864",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60779/"
] |
In 'Reading Settings' I have chosen the static-page drop-down menu of a page I created to be the post page.
I've put the html, php, and css from my page.php in index.php to style it. I'm unable to get the featured image. The php I use to get it on page.php isn't working. It's not rendering any html. Also `<?php the_title(); ?>` is pulling up the title of the most recent blog post, not the page title of the page I have switched over.
This is how I"m generating the featured image on page.php
```
<div class="single-image-anchor">
<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<div class="single-image" style="background-image: url('<?php echo $image[0]; ?>')">
<?php endif; ?>
</div>
```
I am fairly new to Wordpress so thanks in advance.
|
This is not trivial to do as once you have set a specific page to be an aggregation of posts (being a posts page), wordpress will "forget" the initial information it gets of the page itself and will behave like it was a normal home page of a blog. This means that all the global variables used in the loop will **not** be ralated and will not indicate the page itself, and therefor API like `the_title` that rely on the global information will not return the same values as it would have if it was a normal page.
The way to solve this, is to create a specific page template to be used with this page, and in it use `get_option( 'page_for_posts' )` as the post id parameter used to all the API calls that you make, so instead of `has_post_thumbnail( $post->ID )` you will have `has_post_thumbnail( get_option( 'page_for_posts' ) )`
|
177,872 |
<p>Alright I am starting a music blog and I am working hard at coding up this theme but I am wondering why I can't do this successfully within WordPress when I know for sure it's possible.</p>
<p>Alright so let's say that the first half of the title is the artist name and it's code looks something like what's shown below.</p>
<pre><code><b>Example Song Artist - </b>
</code></pre>
<p>After the <code>-</code> is what would start the song title and that would be in a different tag the <code><strong></code> tag would be used for that but... within css we have it set so that it's suppose to look like this.</p>
<pre><code>b {
color: black;
}
strong {
color: red;
}
</code></pre>
<p>above we state that we want the colors to be changed within those tags, how ever when I try and do this in wordpress with the <code><?php the_title(); ?></code> function it does not let me print the title in this format? Is there some way that I can create something within the upload panel which will allow me to do this? </p>
<p>Finished idea of how I want it to look for each title.
<img src="https://i.stack.imgur.com/h1EVM.jpg" alt="enter image description here"></p>
|
[
{
"answer_id": 177903,
"author": "Brad Dalton",
"author_id": 9884,
"author_profile": "https://wordpress.stackexchange.com/users/9884",
"pm_score": 0,
"selected": false,
"text": "<p>One example is Twenty Fifteen which uses a template tag in the content.php files like this:</p>\n\n<pre><code>twentyfifteen_post_thumbnail();\n</code></pre>\n\n<p>And then the function for the template tag in inc/template-tags.php:</p>\n\n<pre><code>if ( ! function_exists( 'twentyfifteen_post_thumbnail' ) ) :\n/**\n * Display an optional post thumbnail.\n *\n * Wraps the post thumbnail in an anchor element on index views, or a div\n * element when on single views.\n *\n * @since Twenty Fifteen 1.0\n */\nfunction twentyfifteen_post_thumbnail() {\n if ( post_password_required() || is_attachment() || ! has_post_thumbnail() ) {\n return;\n }\n\n if ( is_singular() ) :\n ?>\n\n <div class=\"post-thumbnail\">\n <?php the_post_thumbnail(); ?>\n </div><!-- .post-thumbnail -->\n\n <?php else : ?>\n\n <a class=\"post-thumbnail\" href=\"<?php the_permalink(); ?>\" aria-hidden=\"true\">\n <?php\n the_post_thumbnail( 'post-thumbnail', array( 'alt' => get_the_title() ) );\n ?>\n </a>\n\n <?php endif; // End is_singular()\n}\nendif;\n</code></pre>\n\n<p>Not sure i understand your title question however you can take a look in the archive.php file and you'll see this code to display the archive page title:</p>\n\n<pre><code><header class=\"page-header\">\n <?php\n the_archive_title( '<h1 class=\"page-title\">', '</h1>' );\n the_archive_description( '<div class=\"taxonomy-description\">', '</div>' );\n ?>\n </header><!-- .page-header -->\n</code></pre>\n"
},
{
"answer_id": 177986,
"author": "RLM",
"author_id": 60779,
"author_profile": "https://wordpress.stackexchange.com/users/60779",
"pm_score": 0,
"selected": false,
"text": "<pre><code> <div class=\"page-section clear\">\n <div class=\"single-image-anchor\">\n <?php if (get_option( 'page_for_posts' ) ): ?>\n <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( get_option( 'page_for_posts' )), 'single-post-thumbnail' ); ?>\n <div class=\"single-image\" style=\"background-image: url('<?php echo $image[0]; ?>')\">\n <?php endif; ?>\n </div>\n </div>\n <h1 class='title'><?php if(get_option( 'page_for_posts' ) ) echo get_the_title( get_option( 'page_for_posts' ) ); ?> </h2>\n <h1><?php _e( 'Latest Posts', 'html5blank' ); ?></h1> \n</code></pre>\n"
},
{
"answer_id": 239637,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>This is not trivial to do as once you have set a specific page to be an aggregation of posts (being a posts page), wordpress will \"forget\" the initial information it gets of the page itself and will behave like it was a normal home page of a blog. This means that all the global variables used in the loop will <strong>not</strong> be ralated and will not indicate the page itself, and therefor API like <code>the_title</code> that rely on the global information will not return the same values as it would have if it was a normal page.</p>\n\n<p>The way to solve this, is to create a specific page template to be used with this page, and in it use <code>get_option( 'page_for_posts' )</code> as the post id parameter used to all the API calls that you make, so instead of <code>has_post_thumbnail( $post->ID )</code> you will have <code>has_post_thumbnail( get_option( 'page_for_posts' ) )</code></p>\n"
}
] |
2015/02/12
|
[
"https://wordpress.stackexchange.com/questions/177872",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65897/"
] |
Alright I am starting a music blog and I am working hard at coding up this theme but I am wondering why I can't do this successfully within WordPress when I know for sure it's possible.
Alright so let's say that the first half of the title is the artist name and it's code looks something like what's shown below.
```
<b>Example Song Artist - </b>
```
After the `-` is what would start the song title and that would be in a different tag the `<strong>` tag would be used for that but... within css we have it set so that it's suppose to look like this.
```
b {
color: black;
}
strong {
color: red;
}
```
above we state that we want the colors to be changed within those tags, how ever when I try and do this in wordpress with the `<?php the_title(); ?>` function it does not let me print the title in this format? Is there some way that I can create something within the upload panel which will allow me to do this?
Finished idea of how I want it to look for each title.

|
This is not trivial to do as once you have set a specific page to be an aggregation of posts (being a posts page), wordpress will "forget" the initial information it gets of the page itself and will behave like it was a normal home page of a blog. This means that all the global variables used in the loop will **not** be ralated and will not indicate the page itself, and therefor API like `the_title` that rely on the global information will not return the same values as it would have if it was a normal page.
The way to solve this, is to create a specific page template to be used with this page, and in it use `get_option( 'page_for_posts' )` as the post id parameter used to all the API calls that you make, so instead of `has_post_thumbnail( $post->ID )` you will have `has_post_thumbnail( get_option( 'page_for_posts' ) )`
|
177,908 |
<p>Is it possible with the standard build-in tools in Wordpress to get <code>wp_query</code> to only return the count of an query?</p>
<p>Right now, I’ve a query which has several meta_queries but what the only thing I’m interested in is the actually count of the query. </p>
<p>I know that I can use the found_posts property but the query itself generates a big overhead by query <code>SELECT *</code> and thus returns the whole object.</p>
<p>I could just as easy query the DB with a custom query using <code>$wpdb</code> but I would like to utilize the build-in query system if possible..</p>
<p>I’ve been looking for the answer for this on SE and Google but came on empty. </p>
<p>If I've explained myself poorly, please let me know and I'll try to elaborate.</p>
<p>Cheers</p>
|
[
{
"answer_id": 177910,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 5,
"selected": true,
"text": "<p>There is no build in function to achieve what you want, at least not for complicated meta queries like this. If you need to use build in functions for this, the best will be to make use of <code>WP_Query</code>. </p>\n\n<p>To make the query faster and to skip the unwanted returned array of <code>WP_Post</code> properties, and because you are only interested in post count, you can use the following in your parameters in your arguments</p>\n\n<pre><code>'fields' => 'ids',\n'no_found_rows' => true,\n</code></pre>\n\n<p>This might even be a bit faster than a custom SQL query, and the results from <code>WP_Query</code> is cached as well. </p>\n"
},
{
"answer_id": 178251,
"author": "cristian.raiber",
"author_id": 52524,
"author_profile": "https://wordpress.stackexchange.com/users/52524",
"pm_score": 0,
"selected": false,
"text": "<p>I know this has been answered and since your question was based off on using <code>WP_Query</code>, my answer is probably a long-shot but you could also try to use this: </p>\n\n<pre><code>wp_count_posts( $type, $perm );\n</code></pre>\n\n<p>where <code>$type = post_type (post, page, 'custom-post-type-slug')</code> and where <code>$perm</code> = To include private posts readable by the current user, set to 'readable'</p>\n\n<p>I've used this in the past with great success :) </p>\n\n<pre><code>wp_count_posts('post')->publish -> returns only the count for published posts.\n</code></pre>\n"
},
{
"answer_id": 390968,
"author": "Chad Reitsma",
"author_id": 160601,
"author_profile": "https://wordpress.stackexchange.com/users/160601",
"pm_score": 0,
"selected": false,
"text": "<p>If you need a complete example - building on Pieter's notes:</p>\n<pre><code>$query = new WP_Query(\n array(\n 'post_type' => 'post_type_goes_here',\n 'posts_per_page' => -1,\n 'no_found_rows' => true,\n 'fields' => 'ids',\n )\n);\n\nif ($query->have_posts()) echo count($query->posts);\nelse echo "0";\n</code></pre>\n"
},
{
"answer_id": 405582,
"author": "Faraz Ahmad",
"author_id": 183383,
"author_profile": "https://wordpress.stackexchange.com/users/183383",
"pm_score": 0,
"selected": false,
"text": "<p>I would write a simple function that would return the posts count as well as the posts (based on @Pieter's answer)</p>\n<pre><code>function get_posts_with_count($query_args, $page, $per_page)\n{\n // count posts\n $posts_query = new WP_Query(\n $query_args,\n );\n $posts_count = count($posts_query->get_posts());\n $max_pages = ceil($posts_count / $page);\n\n // now actually get the posts\n $query_args['posts_per_page'] = $per_page;\n $query_args['paged'] = $page;\n unset($query_args['fields']);\n $posts_query = new WP_Query(\n $query_args\n );\n $posts = $posts_query->get_posts();\n\n return array(\n 'posts_count' => $posts_count,\n 'max_pages' => $max_pages,\n 'data' => $posts\n );\n}\n</code></pre>\n"
}
] |
2015/02/12
|
[
"https://wordpress.stackexchange.com/questions/177908",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/6751/"
] |
Is it possible with the standard build-in tools in Wordpress to get `wp_query` to only return the count of an query?
Right now, I’ve a query which has several meta\_queries but what the only thing I’m interested in is the actually count of the query.
I know that I can use the found\_posts property but the query itself generates a big overhead by query `SELECT *` and thus returns the whole object.
I could just as easy query the DB with a custom query using `$wpdb` but I would like to utilize the build-in query system if possible..
I’ve been looking for the answer for this on SE and Google but came on empty.
If I've explained myself poorly, please let me know and I'll try to elaborate.
Cheers
|
There is no build in function to achieve what you want, at least not for complicated meta queries like this. If you need to use build in functions for this, the best will be to make use of `WP_Query`.
To make the query faster and to skip the unwanted returned array of `WP_Post` properties, and because you are only interested in post count, you can use the following in your parameters in your arguments
```
'fields' => 'ids',
'no_found_rows' => true,
```
This might even be a bit faster than a custom SQL query, and the results from `WP_Query` is cached as well.
|
177,919 |
<p>I'm just starting out with making plugins and I'm trying to make a simple one that will mail a notification to subscribers whenever I publish a new post.</p>
<p>My code so far:</p>
<pre><code>add_action( 'publish_post', 'vb_esa_update_email' );
function vb_esa_update_email( $post_id ) {
//verify post is not a revision
if ( !wp_is_post_revision( $post_id ) ) {
//gets subscirbers to send email to
// WP_User_Query arguments
$args = array (
'role' => 'Subscriber',
);
// The User Query
$user_query = new WP_User_Query( $args );
$post_title = get_the_title( $post_id );
$post_url = get_permalink( $post_id );
$subject = 'A post has been updated';
$message = "A post has been updated on your website:\n\n";
$message .= "<a href='". $post_url. "'>" .$post_title. "</a>\n\n";
//send email to
foreach($args as $email_address)
{
wp_mail($email_address, $subject, $message );
}
}
}
</code></pre>
<p>How do I go about filling up an array with the list of subscribers to send the notifications to?</p>
|
[
{
"answer_id": 177924,
"author": "thomascharbit",
"author_id": 35003,
"author_profile": "https://wordpress.stackexchange.com/users/35003",
"pm_score": 1,
"selected": false,
"text": "<p>You were on the right track when you built your WP_User_Query, but you are not using the result of this query. See this:</p>\n\n<pre><code> //verify post is not a revision \nif ( !wp_is_post_revision( $post_id ) ) { \n\n //gets subscirbers to send email to\n // WP_User_Query arguments\n $args = array (\n 'role' => 'Subscriber',\n );\n\n\n // The User Query\n $user_query = new WP_User_Query( $args );\n\n // get email addresses from user objects\n $email_addresses = array();\n foreach ( $user_query->results as $user ) {\n $email_addresses[] = $user->user_email;\n }\n\n // build message\n $post_title = get_the_title( $post_id ); \n $post_url = get_permalink( $post_id ); \n $subject = 'A post has been updated'; \n $message = \"A post has been updated on your website:\\n\\n\";\n $message .= \"<a href='\". $post_url. \"'>\" .$post_title. \"</a>\\n\\n\"; \n\n //send email to all emails\n wp_mail($email_addresses, $subject, $message );\n\n}\n</code></pre>\n\n<ul>\n<li>we loop all users and build an array with each email address</li>\n<li>we use this array directly as a parameter of <code>wp_mail()</code> (it supports arrays)</li>\n</ul>\n\n<p>Note that you would probably need to use a third-party service to send many mails at once, or you could have problem with your hosting provider. Have a look at <a href=\"http://mandrill.com/\" rel=\"nofollow noreferrer\">Mandrill</a>. They have a WordPress plugin that works well with the <code>wp_mail()</code> function.</p>\n"
},
{
"answer_id": 177925,
"author": "David Gard",
"author_id": 10097,
"author_profile": "https://wordpress.stackexchange.com/users/10097",
"pm_score": 0,
"selected": false,
"text": "<p>You're almost there but you were not actually picking up any of email addresses from your <strong>User Query</strong></p>\n\n<p>This code should do what you want, however if my understanding of your question is correct you want to send an individual email to each Subscriber, which is not efficient.</p>\n\n<p>It would be better to add all email addresses to an array and send the emails in one go (the <code>wp_mail</code> function will seperate them correctly for you). Better yet, add the addresses to the BCC field, then your Subscribers will not be able to see the addresses of all the other subscribers.</p>\n\n<pre><code>add_action('publish_post', 'vb_esa_update_email'); \nfunction vb_esa_update_email($post_id){ \n\n /** Ensure that the post is not a revision */\n if(wp_is_post_revision($post_id)) :\n return;\n\n /** Query all users who have the role 'Subscriber' */\n $args = array (\n 'role' => 'Subscriber',\n );\n $user_query = new WP_User_Query($args);\n\n /** Check to see if there are any matching users */\n if(!empty($user_query->results)) : \n\n /** Set up the email subject and message */\n $post_title = get_the_title( $post_id ); \n $post_url = get_permalink( $post_id ); \n $subject = 'A post has been updated'; \n $message = \"A post has been updated on your website:\\n\\n\";\n $message.= \"<a href='\". $post_url. \"'>\" .$post_title. \"</a>\\n\\n\"; \n\n /** Send an individual message to each user */\n foreach($user_query->results as $user) :\n\n wp_mail($user->data->user_email, $subject, $message);\n\n endforeach;\n\n endif;\n\n}\n</code></pre>\n"
},
{
"answer_id": 334240,
"author": "Qaisar Feroz",
"author_id": 161501,
"author_profile": "https://wordpress.stackexchange.com/users/161501",
"pm_score": 0,
"selected": false,
"text": "<p>Here is an <a href=\"https://wordpress.stackexchange.com/a/332567/161501\"><strong>answer to a similar question</strong></a> that may help.\nYou should adjust the code in above answer to select users with role <code>subscriber</code>. </p>\n"
}
] |
2015/02/12
|
[
"https://wordpress.stackexchange.com/questions/177919",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67445/"
] |
I'm just starting out with making plugins and I'm trying to make a simple one that will mail a notification to subscribers whenever I publish a new post.
My code so far:
```
add_action( 'publish_post', 'vb_esa_update_email' );
function vb_esa_update_email( $post_id ) {
//verify post is not a revision
if ( !wp_is_post_revision( $post_id ) ) {
//gets subscirbers to send email to
// WP_User_Query arguments
$args = array (
'role' => 'Subscriber',
);
// The User Query
$user_query = new WP_User_Query( $args );
$post_title = get_the_title( $post_id );
$post_url = get_permalink( $post_id );
$subject = 'A post has been updated';
$message = "A post has been updated on your website:\n\n";
$message .= "<a href='". $post_url. "'>" .$post_title. "</a>\n\n";
//send email to
foreach($args as $email_address)
{
wp_mail($email_address, $subject, $message );
}
}
}
```
How do I go about filling up an array with the list of subscribers to send the notifications to?
|
You were on the right track when you built your WP\_User\_Query, but you are not using the result of this query. See this:
```
//verify post is not a revision
if ( !wp_is_post_revision( $post_id ) ) {
//gets subscirbers to send email to
// WP_User_Query arguments
$args = array (
'role' => 'Subscriber',
);
// The User Query
$user_query = new WP_User_Query( $args );
// get email addresses from user objects
$email_addresses = array();
foreach ( $user_query->results as $user ) {
$email_addresses[] = $user->user_email;
}
// build message
$post_title = get_the_title( $post_id );
$post_url = get_permalink( $post_id );
$subject = 'A post has been updated';
$message = "A post has been updated on your website:\n\n";
$message .= "<a href='". $post_url. "'>" .$post_title. "</a>\n\n";
//send email to all emails
wp_mail($email_addresses, $subject, $message );
}
```
* we loop all users and build an array with each email address
* we use this array directly as a parameter of `wp_mail()` (it supports arrays)
Note that you would probably need to use a third-party service to send many mails at once, or you could have problem with your hosting provider. Have a look at [Mandrill](http://mandrill.com/). They have a WordPress plugin that works well with the `wp_mail()` function.
|
177,937 |
<p>I've had a blog on Azure for quite a while, and despite optimisation attempts, it's still pretty slow. The initial TTFB seems to be a significant time sink.</p>
<p><img src="https://i.stack.imgur.com/7GISa.png" alt="Time check"></p>
<h2>Azure setup</h2>
<p>It's quite a small blog and relatively low traffic so sits on an Azure s1 instance with auto-scale on for CPU usage. Additionally I migrated the Db away from clear DB instead putting it on a linux vm on azure.</p>
<h2>Looking through the logs</h2>
<p>I'm getting this error very frequently:</p>
<pre><code>[19-Feb-2015 17:26:51 UTC] PHP Fatal error: Maximum execution time of 300 seconds exceeded in D:\home\site\wwwroot\wp-includes\class-http.php on line 1511
</code></pre>
<h2>Checks run</h2>
<p>I have created and tested:</p>
<ol>
<li>a simple html page</li>
<li>a simple php page</li>
<li>a simple php page with a db connection test</li>
</ol>
<p>None of these experienced delays </p>
<h2>How to resolve</h2>
<p>Looking at this <a href="http://azure.microsoft.com/blog/2014/05/13/how-to-run-wordpress-site-on-azure-websites/" rel="nofollow noreferrer">enterprise grade wordpress on azure</a> article it mentions the removal of ARR however the link is broken and other articles I've found don't dumb it down or relate it to php/ wordpress enough for me to use them.</p>
<p>I've also seen an <a href="https://wordpress.stackexchange.com/questions/14186/long-waiting-times-on-godaddy">SO relating to GoDaddy</a> who are my DNS provider can be responsible for slow performance but that seems to apply when they are hosts, not DNS owners.</p>
<p><strong>How does a person reduce this wait time for Wordpress websites on Azure?</strong></p>
|
[
{
"answer_id": 177933,
"author": "mor7ifer",
"author_id": 11740,
"author_profile": "https://wordpress.stackexchange.com/users/11740",
"pm_score": 1,
"selected": false,
"text": "<p>What you likely need is the function <a href=\"http://codex.wordpress.org/Function_Reference/wp_insert_post\" rel=\"nofollow noreferrer\"><code>wp_insert_post()</code></a>. In your backend (not the WordPress backend, just so we're clear), you'll need to do a minimal load of WordPress to allow <a href=\"http://codex.wordpress.org/Function_Reference/wp_insert_post\" rel=\"nofollow noreferrer\"><code>wp_insert_post()</code></a> to work. You can do this by <code>define( 'SHORTINT', true )</code>.</p>\n\n<p>Some additional reading on doing a minimal load of WordPress:</p>\n\n<ul>\n<li><a href=\"https://wordpress.stackexchange.com/questions/47863/load-minimum-wordpress-environment\">Load minimum WordPress environment</a></li>\n<li><a href=\"https://wordpress.stackexchange.com/questions/41808/ajax-takes-10x-as-long-as-it-should-could\">Ajax takes 10x as long as it should/could</a></li>\n<li><a href=\"https://wordpress.stackexchange.com/questions/103896/minimal-wordpress-load-for-only-get-option-to-work-because-ajax\">Minimal wordpress load for only `get_option` to work (because ajax...)</a></li>\n</ul>\n\n<p>In these questions you will also find information how to do this asynchronously, should you desire to do it that way.</p>\n"
},
{
"answer_id": 178115,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 0,
"selected": false,
"text": "<p>You should without a doubt use the <a href=\"http://codex.wordpress.org/XML-RPC_WordPress_API\" rel=\"nofollow\">WordPress XML RPC</a>. No need for direct database connections and crafting manual queries that might break on future updates.</p>\n\n<p>Not to mention any plugins/themes you use on your WordPress site that depend on database-related actions/filters will function as normal.</p>\n\n<p>This is the whole reason why an API like this exists. It's what the iOS/Android WordPress apps use, among many other popular 3rd party products that interact with your WordPress site.</p>\n"
}
] |
2015/02/12
|
[
"https://wordpress.stackexchange.com/questions/177937",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44562/"
] |
I've had a blog on Azure for quite a while, and despite optimisation attempts, it's still pretty slow. The initial TTFB seems to be a significant time sink.

Azure setup
-----------
It's quite a small blog and relatively low traffic so sits on an Azure s1 instance with auto-scale on for CPU usage. Additionally I migrated the Db away from clear DB instead putting it on a linux vm on azure.
Looking through the logs
------------------------
I'm getting this error very frequently:
```
[19-Feb-2015 17:26:51 UTC] PHP Fatal error: Maximum execution time of 300 seconds exceeded in D:\home\site\wwwroot\wp-includes\class-http.php on line 1511
```
Checks run
----------
I have created and tested:
1. a simple html page
2. a simple php page
3. a simple php page with a db connection test
None of these experienced delays
How to resolve
--------------
Looking at this [enterprise grade wordpress on azure](http://azure.microsoft.com/blog/2014/05/13/how-to-run-wordpress-site-on-azure-websites/) article it mentions the removal of ARR however the link is broken and other articles I've found don't dumb it down or relate it to php/ wordpress enough for me to use them.
I've also seen an [SO relating to GoDaddy](https://wordpress.stackexchange.com/questions/14186/long-waiting-times-on-godaddy) who are my DNS provider can be responsible for slow performance but that seems to apply when they are hosts, not DNS owners.
**How does a person reduce this wait time for Wordpress websites on Azure?**
|
What you likely need is the function [`wp_insert_post()`](http://codex.wordpress.org/Function_Reference/wp_insert_post). In your backend (not the WordPress backend, just so we're clear), you'll need to do a minimal load of WordPress to allow [`wp_insert_post()`](http://codex.wordpress.org/Function_Reference/wp_insert_post) to work. You can do this by `define( 'SHORTINT', true )`.
Some additional reading on doing a minimal load of WordPress:
* [Load minimum WordPress environment](https://wordpress.stackexchange.com/questions/47863/load-minimum-wordpress-environment)
* [Ajax takes 10x as long as it should/could](https://wordpress.stackexchange.com/questions/41808/ajax-takes-10x-as-long-as-it-should-could)
* [Minimal wordpress load for only `get\_option` to work (because ajax...)](https://wordpress.stackexchange.com/questions/103896/minimal-wordpress-load-for-only-get-option-to-work-because-ajax)
In these questions you will also find information how to do this asynchronously, should you desire to do it that way.
|
177,941 |
<p>I have a very simple jQuery function that is supposed to toggle a div's visibility:</p>
<pre><code>jQuery( ".signUp" ).click(function() {
$('.signUpForm').toggle();
});
</code></pre>
<p>The HTML is a simple signup form (hidden fields left out for brevity):</p>
<pre><code><p><a class="signUp" href="#">Sign Up!</a></p>
<div class="signUpForm">
<h3 class="title">Join our email list!</h3>
<form action="<url goes here>" method="POST">
<label for="email">Email:</label><input type="text" id="email" name="Email"/></br><br />
<input type="Submit" value="Submit" /><br />
</form>
</div>
</code></pre>
<p>The script looks like it was enqueued properly, but it's not working on the WP page. It does work just fine on JSFiddle (<a href="http://jsfiddle.net/danromanchik/6taton4p/" rel="nofollow">http://jsfiddle.net/danromanchik/6taton4p/</a>). </p>
<p>Any ideas what I'm doing wrong?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 178093,
"author": "Rachel Baker",
"author_id": 8054,
"author_profile": "https://wordpress.stackexchange.com/users/8054",
"pm_score": 3,
"selected": true,
"text": "<p>You need to wrap your jQuery click event in a DOM ready function.</p>\n\n<pre><code>(function($) {\n $('.signUp').click(function() {\n $('.signUpForm').toggle();\n });\n})(jQuery);\n</code></pre>\n"
},
{
"answer_id": 222871,
"author": "maheshwaghmare",
"author_id": 52167,
"author_profile": "https://wordpress.stackexchange.com/users/52167",
"pm_score": 0,
"selected": false,
"text": "<p>You need to add your script though:</p>\n\n<ol>\n<li>Using <code>wp_enqueue_script()</code> in themes <code>function.php</code>\nor</li>\n<li>Use <code>wp_footer</code> action to add your <code>jQuery</code> script.</li>\n</ol>\n\n<p>If your html in a shortcode then register your script using <code>wp_register_script('YOUR_HANDLE_NAME)</code></p>\n\n<p>and use <code>wp_enqueue_script('YOUR_HANDLE_NAME)</code></p>\n\n<p>Hope It helps...</p>\n"
}
] |
2015/02/12
|
[
"https://wordpress.stackexchange.com/questions/177941",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67455/"
] |
I have a very simple jQuery function that is supposed to toggle a div's visibility:
```
jQuery( ".signUp" ).click(function() {
$('.signUpForm').toggle();
});
```
The HTML is a simple signup form (hidden fields left out for brevity):
```
<p><a class="signUp" href="#">Sign Up!</a></p>
<div class="signUpForm">
<h3 class="title">Join our email list!</h3>
<form action="<url goes here>" method="POST">
<label for="email">Email:</label><input type="text" id="email" name="Email"/></br><br />
<input type="Submit" value="Submit" /><br />
</form>
</div>
```
The script looks like it was enqueued properly, but it's not working on the WP page. It does work just fine on JSFiddle (<http://jsfiddle.net/danromanchik/6taton4p/>).
Any ideas what I'm doing wrong?
Thanks.
|
You need to wrap your jQuery click event in a DOM ready function.
```
(function($) {
$('.signUp').click(function() {
$('.signUpForm').toggle();
});
})(jQuery);
```
|
177,943 |
<p>I have two CPT: Listings and Events. In Events I have custom fields for the start and end dates. What I need is a way to filter out any events that are past the current date.</p>
<p>What I have right now is: </p>
<pre><code>function search_pre_get_posts( $query ) {
if ( is_search() && $query->is_main_query() ) {
$currentdate = current_time('Ymd');
global $wp_query;
$args = array_merge(
$wp_query->query_vars,
array(
'meta_query'=> array( array(
'key' => 'DTEND',
'compare' => '>=',
'value' => $currentdate,
)),
)
);
query_posts( $args );
}
}
add_action( 'pre_get_posts', 'search_pre_get_posts' );
</code></pre>
<p>This does filter out the past events, but it also removes all Listings. What I need is a way to add an <code>IF</code> statement to run this meta query only for 'events'.</p>
<p>Anyone have an idea of how to do this? Whenever I put an <code>IF</code> statement anywhere in there, using a <code>get_post_type()</code>, like <code>'events' == get_post_type()</code>, it breaks the whole filter.</p>
|
[
{
"answer_id": 177958,
"author": "Jen",
"author_id": 13810,
"author_profile": "https://wordpress.stackexchange.com/users/13810",
"pm_score": 2,
"selected": true,
"text": "<p>You could add a second array to check if the 'DTEND' value is not set:</p>\n\n<pre><code> $args = array_merge( \n $wp_query->query_vars, \n array(\n 'meta_query'=> array( \n 'relation' => 'OR',\n array(\n 'key' => 'DTEND',\n 'compare' => '>=',\n 'value' => $currentdate,\n ),\n array(\n 'key' => 'DTEND',\n 'compare' => 'NOT EXISTS',\n )\n ),\n )\n );\n</code></pre>\n\n<p>That way, any custom posts without a <code>DTEND</code> meta value will also be allowed.</p>\n"
},
{
"answer_id": 178453,
"author": "Aaron",
"author_id": 36436,
"author_profile": "https://wordpress.stackexchange.com/users/36436",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, @guiniveretoo nailed it, with a couple edits:</p>\n\n<p>Ok, @guiniveretoo, you nailed it!</p>\n\n<p>With a couple tweaks, this is what I used and it works:</p>\n\n<pre><code>function search_pre_get_posts( $query ) {\nglobal $wp_query;\nif ( is_search() && $query->is_main_query() ) {\n\n$currentdate = current_time('Ymd');\n\n$args = array_merge( \n $wp_query->query_vars, \n array(\n 'meta_query'=> array( \n 'relation' => 'OR',\n array(\n 'key' => 'DTEND',\n 'compare' => '>=',\n 'value' => $currentdate,\n ),\n array(\n 'key' => 'DTEND',\n 'compare' => 'NOT EXISTS',\n )\n ),\n )\n);\n\n query_posts( $args );\n\n}\n\n}\n\nadd_action( 'pre_get_posts', 'search_pre_get_posts' );'\n</code></pre>\n\n<p>Now, i just need to figure out how to sort the 'events' CPT by a meta key 'DTSTART', so the events that are coming up get listed first....</p>\n"
},
{
"answer_id": 178456,
"author": "Manny Fleurmond",
"author_id": 2234,
"author_profile": "https://wordpress.stackexchange.com/users/2234",
"pm_score": 0,
"selected": false,
"text": "<p>@Aaron, here is an alternate version of your solution, including sorting:</p>\n\n<pre><code>function search_pre_get_posts( $query ) {\n if ( $query->is_search() && $query->is_main_query() ) { \n $currentdate = current_time('Ymd');\n $query->set( \n 'meta_query',\n array(\n 'relation' => 'OR',\n array(\n 'key' => 'DTEND',\n 'compare' => '>=',\n 'value' => $currentdate,\n ),\n array(\n 'key' => 'DTEND',\n 'compare' => 'NOT EXISTS',\n )\n )\n );\n\n $query->set( 'orderby', 'meta_value' );\n }\n}\n\nadd_action( 'pre_get_posts', 'search_pre_get_posts' );'\n</code></pre>\n\n<p>Big difference: <code>$query</code> is passed by reference, so you don't need to call <code>$wp_query</code> or <code>query_posts</code> (which you should never call anyway). Also, setting <code>orderby</code> by <code>meta_value</code> will sort the posts by the meta value.</p>\n"
}
] |
2015/02/12
|
[
"https://wordpress.stackexchange.com/questions/177943",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/36436/"
] |
I have two CPT: Listings and Events. In Events I have custom fields for the start and end dates. What I need is a way to filter out any events that are past the current date.
What I have right now is:
```
function search_pre_get_posts( $query ) {
if ( is_search() && $query->is_main_query() ) {
$currentdate = current_time('Ymd');
global $wp_query;
$args = array_merge(
$wp_query->query_vars,
array(
'meta_query'=> array( array(
'key' => 'DTEND',
'compare' => '>=',
'value' => $currentdate,
)),
)
);
query_posts( $args );
}
}
add_action( 'pre_get_posts', 'search_pre_get_posts' );
```
This does filter out the past events, but it also removes all Listings. What I need is a way to add an `IF` statement to run this meta query only for 'events'.
Anyone have an idea of how to do this? Whenever I put an `IF` statement anywhere in there, using a `get_post_type()`, like `'events' == get_post_type()`, it breaks the whole filter.
|
You could add a second array to check if the 'DTEND' value is not set:
```
$args = array_merge(
$wp_query->query_vars,
array(
'meta_query'=> array(
'relation' => 'OR',
array(
'key' => 'DTEND',
'compare' => '>=',
'value' => $currentdate,
),
array(
'key' => 'DTEND',
'compare' => 'NOT EXISTS',
)
),
)
);
```
That way, any custom posts without a `DTEND` meta value will also be allowed.
|
177,947 |
<p>I'm developing four websites which are separate, besides the Events (custom post type). Three of the websites are WP, and I've got them in a Network. I would like Events to show up in all three Admin interfaces with the same data. All being able to create and edit. Is it possible? It's all the same DB..</p>
|
[
{
"answer_id": 177958,
"author": "Jen",
"author_id": 13810,
"author_profile": "https://wordpress.stackexchange.com/users/13810",
"pm_score": 2,
"selected": true,
"text": "<p>You could add a second array to check if the 'DTEND' value is not set:</p>\n\n<pre><code> $args = array_merge( \n $wp_query->query_vars, \n array(\n 'meta_query'=> array( \n 'relation' => 'OR',\n array(\n 'key' => 'DTEND',\n 'compare' => '>=',\n 'value' => $currentdate,\n ),\n array(\n 'key' => 'DTEND',\n 'compare' => 'NOT EXISTS',\n )\n ),\n )\n );\n</code></pre>\n\n<p>That way, any custom posts without a <code>DTEND</code> meta value will also be allowed.</p>\n"
},
{
"answer_id": 178453,
"author": "Aaron",
"author_id": 36436,
"author_profile": "https://wordpress.stackexchange.com/users/36436",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, @guiniveretoo nailed it, with a couple edits:</p>\n\n<p>Ok, @guiniveretoo, you nailed it!</p>\n\n<p>With a couple tweaks, this is what I used and it works:</p>\n\n<pre><code>function search_pre_get_posts( $query ) {\nglobal $wp_query;\nif ( is_search() && $query->is_main_query() ) {\n\n$currentdate = current_time('Ymd');\n\n$args = array_merge( \n $wp_query->query_vars, \n array(\n 'meta_query'=> array( \n 'relation' => 'OR',\n array(\n 'key' => 'DTEND',\n 'compare' => '>=',\n 'value' => $currentdate,\n ),\n array(\n 'key' => 'DTEND',\n 'compare' => 'NOT EXISTS',\n )\n ),\n )\n);\n\n query_posts( $args );\n\n}\n\n}\n\nadd_action( 'pre_get_posts', 'search_pre_get_posts' );'\n</code></pre>\n\n<p>Now, i just need to figure out how to sort the 'events' CPT by a meta key 'DTSTART', so the events that are coming up get listed first....</p>\n"
},
{
"answer_id": 178456,
"author": "Manny Fleurmond",
"author_id": 2234,
"author_profile": "https://wordpress.stackexchange.com/users/2234",
"pm_score": 0,
"selected": false,
"text": "<p>@Aaron, here is an alternate version of your solution, including sorting:</p>\n\n<pre><code>function search_pre_get_posts( $query ) {\n if ( $query->is_search() && $query->is_main_query() ) { \n $currentdate = current_time('Ymd');\n $query->set( \n 'meta_query',\n array(\n 'relation' => 'OR',\n array(\n 'key' => 'DTEND',\n 'compare' => '>=',\n 'value' => $currentdate,\n ),\n array(\n 'key' => 'DTEND',\n 'compare' => 'NOT EXISTS',\n )\n )\n );\n\n $query->set( 'orderby', 'meta_value' );\n }\n}\n\nadd_action( 'pre_get_posts', 'search_pre_get_posts' );'\n</code></pre>\n\n<p>Big difference: <code>$query</code> is passed by reference, so you don't need to call <code>$wp_query</code> or <code>query_posts</code> (which you should never call anyway). Also, setting <code>orderby</code> by <code>meta_value</code> will sort the posts by the meta value.</p>\n"
}
] |
2015/02/12
|
[
"https://wordpress.stackexchange.com/questions/177947",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67457/"
] |
I'm developing four websites which are separate, besides the Events (custom post type). Three of the websites are WP, and I've got them in a Network. I would like Events to show up in all three Admin interfaces with the same data. All being able to create and edit. Is it possible? It's all the same DB..
|
You could add a second array to check if the 'DTEND' value is not set:
```
$args = array_merge(
$wp_query->query_vars,
array(
'meta_query'=> array(
'relation' => 'OR',
array(
'key' => 'DTEND',
'compare' => '>=',
'value' => $currentdate,
),
array(
'key' => 'DTEND',
'compare' => 'NOT EXISTS',
)
),
)
);
```
That way, any custom posts without a `DTEND` meta value will also be allowed.
|
177,954 |
<p>Unable to login because <code>wp-login.php</code> redirects to <strong>homepage</strong>. </p>
<p>I tried deactivating all plugins but nothing worked. </p>
<p>I didn't install any plugins or make any changes recently.</p>
|
[
{
"answer_id": 177969,
"author": "Ferrmolina",
"author_id": 67194,
"author_profile": "https://wordpress.stackexchange.com/users/67194",
"pm_score": 1,
"selected": true,
"text": "<p>Update your DOMAIN site.</p>\n\n<p>Put this in your <code>wp-config.php</code> file</p>\n\n<pre><code>define('WP_HOME','http://example.com');\ndefine('WP_SITEURL','http://example.com');\n</code></pre>\n\n<p>Probably thats fix your problem.\nWherever, you can revert back to the Default Theme, renaming the folder of your current theme in <code>/wp-content/themes/</code> directory.</p>\n\n<p>Trying too deleting your <code>.htaccess</code> file</p>\n\n<p>Regards.</p>\n"
},
{
"answer_id": 254692,
"author": "user112225",
"author_id": 112225,
"author_profile": "https://wordpress.stackexchange.com/users/112225",
"pm_score": 1,
"selected": false,
"text": "<p>For me it was that the permissions were not set to 755 on the wp-admin folder.</p>\n"
}
] |
2015/02/12
|
[
"https://wordpress.stackexchange.com/questions/177954",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
Unable to login because `wp-login.php` redirects to **homepage**.
I tried deactivating all plugins but nothing worked.
I didn't install any plugins or make any changes recently.
|
Update your DOMAIN site.
Put this in your `wp-config.php` file
```
define('WP_HOME','http://example.com');
define('WP_SITEURL','http://example.com');
```
Probably thats fix your problem.
Wherever, you can revert back to the Default Theme, renaming the folder of your current theme in `/wp-content/themes/` directory.
Trying too deleting your `.htaccess` file
Regards.
|
177,998 |
<p>I want to add small jQuery script in my WordPress how to do that?</p>
<p>Here's the JQuery script that I want to add:</p>
<pre><code> ( function( window ) {
'use strict';
function classReg( className ) {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}
var hasClass, addClass, removeClass;
if ( 'classList' in document.documentElement ) {
hasClass = function( elem, c ) {
return elem.classList.contains( c );
};
addClass = function( elem, c ) {
elem.classList.add( c );
};
removeClass = function( elem, c ) {
elem.classList.remove( c );
};
}
else {
hasClass = function( elem, c ) {
return classReg( c ).test( elem.className );
};
addClass = function( elem, c ) {
if ( !hasClass( elem, c ) ) {
elem.className = elem.className + ' ' + c;
}
};
removeClass = function( elem, c ) {
elem.className = elem.className.replace( classReg( c ), ' ' );
};
}
function toggleClass( elem, c ) {
var fn = hasClass( elem, c ) ? removeClass : addClass;
fn( elem, c );
}
var classie = {
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
toggleClass: toggleClass,
has: hasClass,
add: addClass,
remove: removeClass,
toggle: toggleClass
};
if ( typeof define === 'function' && define.amd ) {
define( classie );
} else {
window.classie = classie;
}
})( window );
var $ = function(selector){
return document.querySelector(selector);
}
var accordion = $('.accordion');
accordion.addEventListener("click",function(e) {
e.stopPropagation();
e.preventDefault();
if(e.target && e.target.nodeName == "A") {
var classes = e.target.className.split(" ");
if(classes) {
for(var x = 0; x < classes.length; x++) {
if(classes[x] == "accordionTitle") {
var title = e.target;
var content = e.target.parentNode.nextElementSibling;
classie.toggle(title, 'accordionTitleActive');
if(classie.has(content, 'accordionItemCollapsed')) {
if(classie.has(content, 'animateOut')){
classie.remove(content, 'animateOut');
}
classie.add(content, 'animateIn');
}else{
classie.remove(content, 'animateIn');
classie.add(content, 'animateOut');
}
classie.toggle(content, 'accordionItemCollapsed');
}
}
}
}
});
</code></pre>
|
[
{
"answer_id": 178000,
"author": "Vincent Wong",
"author_id": 66041,
"author_profile": "https://wordpress.stackexchange.com/users/66041",
"pm_score": -1,
"selected": false,
"text": "<p>You can add them into functions.php file, code below:</p>\n\n<pre><code> //load js\n\n function load_js(){\n if(is_page(Page ID, Page Title or Page Slug)){\n //put your js code here\n }\n }\n\n add_action('wp_footer', 'load_js', 20); //for footer \n add_action('wp_head', 'load_js', 8); //for head\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>function load_js(){\n if(is_page(19)){\n wp_enqueue_script('UniqueName', 'jsfilepath', false, 'version number', true ); // the last parameter true for footer false for head\n }\n}\n\nadd_action( 'wp_enqueue_scripts', 'load_js')\n</code></pre>\n\n<p>Code have been tested. It's OK!</p>\n"
},
{
"answer_id": 178005,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": true,
"text": "<p>If you are going to add a inline script that depends on jQuery, the best and correct way is to use <code>wp_enqeue_scripts</code> action hook, or <code>wp_footer</code>, depends on the situation, combined with <code>wp_script_is()</code> function:</p>\n\n<pre><code>add_action( 'wp_footer', 'cyb_print_inline_script' );\nfunction cyb_print_inline_script() {\n //Check that jQuery has been printed\n if ( wp_script_is( 'jquery', 'done' ) ) {\n ?>\n <script>\n // js code goes here\n </script>\n <?php\n }\n}\n</code></pre>\n\n<p>But you can end up with issues because you are not managing depdencies correctly. The really correct way is to <strong>not print inline scripts that has dependencies</strong>. Instead, enqueue it in a file.</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'cyb_enqueue_scripts' );\nfunction cyb_enqueue_scripts() {\n\n wp_enqueue_script(\n //Name to handle your script\n 'my-script-handle',\n //URL to the script file\n get_stylesheet_directory_uri() . '/my-script.js',\n //Set the dependencies\n array( 'jquery' ),\n //Version\n '1.0',\n //In footer: true to print the script in footer, false to print it on head\n true\n );\n\n}\n</code></pre>\n\n<p>If you need to pass variables to your script, use <a href=\"http://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow\"><code>wp_localize_script</code></a> as follow:</p>\n\n<pre><code>add_action( 'wp_enqeue_scripts', 'cyb_enqueue_scripts' );\nfunction cyb_enqueue_scripts() {\n\n //Register the js file\n wp_register_script(\n //Name to handle your script\n 'my-script-handle',\n //URL to the script file\n get_stylesheet_directory_uri() . '/my-script.js',\n //Set the dependencies\n array( 'jquery' ),\n //Version\n '1.0',\n //In footer: true to print the script in footer, false to print it on head\n true\n );\n\n\n //Localize the needed variables\n $script_vars = array(\n 'some_var' => 'some value',\n 'another_var' => 'another value'\n );\n wp_localize_script( 'my-script-handle', 'object_name_passed_to_script', $script_vars );\n\n //Enqueue the script\n wp_enqueue_script('my-script-handle');\n\n}\n</code></pre>\n"
}
] |
2015/02/13
|
[
"https://wordpress.stackexchange.com/questions/177998",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62417/"
] |
I want to add small jQuery script in my WordPress how to do that?
Here's the JQuery script that I want to add:
```
( function( window ) {
'use strict';
function classReg( className ) {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}
var hasClass, addClass, removeClass;
if ( 'classList' in document.documentElement ) {
hasClass = function( elem, c ) {
return elem.classList.contains( c );
};
addClass = function( elem, c ) {
elem.classList.add( c );
};
removeClass = function( elem, c ) {
elem.classList.remove( c );
};
}
else {
hasClass = function( elem, c ) {
return classReg( c ).test( elem.className );
};
addClass = function( elem, c ) {
if ( !hasClass( elem, c ) ) {
elem.className = elem.className + ' ' + c;
}
};
removeClass = function( elem, c ) {
elem.className = elem.className.replace( classReg( c ), ' ' );
};
}
function toggleClass( elem, c ) {
var fn = hasClass( elem, c ) ? removeClass : addClass;
fn( elem, c );
}
var classie = {
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
toggleClass: toggleClass,
has: hasClass,
add: addClass,
remove: removeClass,
toggle: toggleClass
};
if ( typeof define === 'function' && define.amd ) {
define( classie );
} else {
window.classie = classie;
}
})( window );
var $ = function(selector){
return document.querySelector(selector);
}
var accordion = $('.accordion');
accordion.addEventListener("click",function(e) {
e.stopPropagation();
e.preventDefault();
if(e.target && e.target.nodeName == "A") {
var classes = e.target.className.split(" ");
if(classes) {
for(var x = 0; x < classes.length; x++) {
if(classes[x] == "accordionTitle") {
var title = e.target;
var content = e.target.parentNode.nextElementSibling;
classie.toggle(title, 'accordionTitleActive');
if(classie.has(content, 'accordionItemCollapsed')) {
if(classie.has(content, 'animateOut')){
classie.remove(content, 'animateOut');
}
classie.add(content, 'animateIn');
}else{
classie.remove(content, 'animateIn');
classie.add(content, 'animateOut');
}
classie.toggle(content, 'accordionItemCollapsed');
}
}
}
}
});
```
|
If you are going to add a inline script that depends on jQuery, the best and correct way is to use `wp_enqeue_scripts` action hook, or `wp_footer`, depends on the situation, combined with `wp_script_is()` function:
```
add_action( 'wp_footer', 'cyb_print_inline_script' );
function cyb_print_inline_script() {
//Check that jQuery has been printed
if ( wp_script_is( 'jquery', 'done' ) ) {
?>
<script>
// js code goes here
</script>
<?php
}
}
```
But you can end up with issues because you are not managing depdencies correctly. The really correct way is to **not print inline scripts that has dependencies**. Instead, enqueue it in a file.
```
add_action( 'wp_enqueue_scripts', 'cyb_enqueue_scripts' );
function cyb_enqueue_scripts() {
wp_enqueue_script(
//Name to handle your script
'my-script-handle',
//URL to the script file
get_stylesheet_directory_uri() . '/my-script.js',
//Set the dependencies
array( 'jquery' ),
//Version
'1.0',
//In footer: true to print the script in footer, false to print it on head
true
);
}
```
If you need to pass variables to your script, use [`wp_localize_script`](http://codex.wordpress.org/Function_Reference/wp_localize_script) as follow:
```
add_action( 'wp_enqeue_scripts', 'cyb_enqueue_scripts' );
function cyb_enqueue_scripts() {
//Register the js file
wp_register_script(
//Name to handle your script
'my-script-handle',
//URL to the script file
get_stylesheet_directory_uri() . '/my-script.js',
//Set the dependencies
array( 'jquery' ),
//Version
'1.0',
//In footer: true to print the script in footer, false to print it on head
true
);
//Localize the needed variables
$script_vars = array(
'some_var' => 'some value',
'another_var' => 'another value'
);
wp_localize_script( 'my-script-handle', 'object_name_passed_to_script', $script_vars );
//Enqueue the script
wp_enqueue_script('my-script-handle');
}
```
|
178,007 |
<p>I'm currently deciding whether or not to use WordPress or write my own code for a future website but I need to know one thing before I can make my final decision.</p>
<p>Is it possible, with WordPress, to insert PHP scripts into a single page. About 40% of my pages will have their own PHP script behind it and I need to know if such a thing is possible (and if so, what I should be looking at).</p>
<p>Thanks.</p>
|
[
{
"answer_id": 178021,
"author": "efreeman",
"author_id": 59490,
"author_profile": "https://wordpress.stackexchange.com/users/59490",
"pm_score": 0,
"selected": false,
"text": "<p>Every page can use it's own individual template if needed, have a look at the wordpress template heirarchy image for a bit more info. Basically a page will default to using page.php but if you provide page-{slug}.php where {slug} is the slug of the page, it will use that template instead.</p>\n\n<p>So it's entirely feasible to have a separate 'page' file for each and every page, with code specific to that page on it.</p>\n\n<p>Additionally, if some of the code is shared between multiple pages, just set up a custom page template and assign that template to those pages that use it.</p>\n\n<p>Wordpress template heirarchy: <a href=\"http://codex.wordpress.org/Template_Hierarchy\" rel=\"nofollow\">http://codex.wordpress.org/Template_Hierarchy</a></p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 178032,
"author": "Brad Dalton",
"author_id": 9884,
"author_profile": "https://wordpress.stackexchange.com/users/9884",
"pm_score": 1,
"selected": false,
"text": "<p>Rather than insert PHP scripts into each page what you could do is execute PHP scripts using action <a href=\"http://codex.wordpress.org/Plugin_API/Hooks\" rel=\"nofollow\"><code>hooks</code></a> with conditional tags or modify the default output of an existing function using a filter hook with <a href=\"http://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow\"><code>conditional tag</code></a> for each page.</p>\n\n<p>You could also create template tags or write your own functions in a separate file and execute on any page in a custom function with conditional tag using the page I.D.</p>\n\n<p><strong>Filter Example</strong></p>\n\n<pre><code>add_filter( 'the_content', 'execute_before_content' ); \n\nfunction execute_before_content( $content ) { \n\nif ( is_singular('page') && function_exists('your_function')) {\n\n $before_content = your_function();\n\n $content = $before_content . $content;\n\n }\n\nreturn $content;\n}\n</code></pre>\n\n<p><strong>Action Hook Example:</strong></p>\n\n<pre><code>add_action( 'loop_start', 'your_function' );\nfunction your_function() {\nif ( is_page('007') && function_exists('your_template_tag')): \n your_template_tag();\nendif; \n}\n</code></pre>\n"
},
{
"answer_id": 178054,
"author": "tonymazz",
"author_id": 67509,
"author_profile": "https://wordpress.stackexchange.com/users/67509",
"pm_score": 0,
"selected": false,
"text": "<p>Can you elaborate on the use-case? As Brad stated, using hooks is the the best method to accomplish this functionally. You probably would want to create a plugin that you could maintain, upgrade and reuse... especially if this is for a client! </p>\n\n<p><a href=\"http://codex.wordpress.org/Writing_a_Plugin\" rel=\"nofollow\">http://codex.wordpress.org/Writing_a_Plugin</a></p>\n"
}
] |
2015/02/13
|
[
"https://wordpress.stackexchange.com/questions/178007",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/59902/"
] |
I'm currently deciding whether or not to use WordPress or write my own code for a future website but I need to know one thing before I can make my final decision.
Is it possible, with WordPress, to insert PHP scripts into a single page. About 40% of my pages will have their own PHP script behind it and I need to know if such a thing is possible (and if so, what I should be looking at).
Thanks.
|
Rather than insert PHP scripts into each page what you could do is execute PHP scripts using action [`hooks`](http://codex.wordpress.org/Plugin_API/Hooks) with conditional tags or modify the default output of an existing function using a filter hook with [`conditional tag`](http://codex.wordpress.org/Conditional_Tags) for each page.
You could also create template tags or write your own functions in a separate file and execute on any page in a custom function with conditional tag using the page I.D.
**Filter Example**
```
add_filter( 'the_content', 'execute_before_content' );
function execute_before_content( $content ) {
if ( is_singular('page') && function_exists('your_function')) {
$before_content = your_function();
$content = $before_content . $content;
}
return $content;
}
```
**Action Hook Example:**
```
add_action( 'loop_start', 'your_function' );
function your_function() {
if ( is_page('007') && function_exists('your_template_tag')):
your_template_tag();
endif;
}
```
|
178,020 |
<p>I am trying to add static menu item to Wordpress Menu.I am using filter 'wp_nav_menu_items' for this in functions.php. It works but it doesn't put it under menu container tag.</p>
<pre><code>function add_nav_menu_items( $items , $args ) { ?>
<ul>
<li><a href="#">PRODUCTS</a>
<ul>
<li><a href="<?php echo esc_url(get_category_link(get_cat_ID('Sci-Fi')));?>">SCI-FI</a>
<ul>
<?php query_posts( array ('post_type'=>'scifi','showposts'=>-1,'order'=>'ASC') ); while ( have_posts() ) : the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; wp_reset_query(); ?>
</ul>
</li>
<li><a href="<?php echo esc_url(get_category_link(get_cat_ID('Drama')));?>">Drama</a>
<ul>
<?php query_posts( array ('post_type'=>'drama','showposts'=>-1,'order'=>'ASC') ); while ( have_posts() ) : the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; wp_reset_query(); ?>
</ul>
</li>
<li><a href="<?php echo esc_url(get_category_link(get_cat_ID('Horror')));?>">HORROR</a>
<ul>
<?php query_posts( array ('post_type'=>'horror','showposts'=>-1,'order'=> 'ASC') ); while ( have_posts() ) : the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; wp_reset_query(); ?>
</ul>
</li>
</ul>
</li>
</ul>
<?php return $items;}
add_filter( 'wp_nav_menu_items', 'add_nav_menu_items',10,2);
</code></pre>
<p>When i put the code online firebug show it like this</p>
<pre><code><div id="navigation_top">
<div id="navmenu_top">
<ul> **-->> This is my static menu**
<li>
</ul>
<ul id="menu-menu-1" class="menu-container"> **-->> This is WP_nav_menu**
<li class="type menu-item-object-page menu-item-587">
<li class="type menu-item-object-page menu-item-122">
<li class="type menu-item-object-page menu-item-121">
**I want my menu appear here **
</ul>
</div>
</div>
</code></pre>
<p>Is there anyway i can do this???</p>
<p>Thanks for any advice...</p>
|
[
{
"answer_id": 178021,
"author": "efreeman",
"author_id": 59490,
"author_profile": "https://wordpress.stackexchange.com/users/59490",
"pm_score": 0,
"selected": false,
"text": "<p>Every page can use it's own individual template if needed, have a look at the wordpress template heirarchy image for a bit more info. Basically a page will default to using page.php but if you provide page-{slug}.php where {slug} is the slug of the page, it will use that template instead.</p>\n\n<p>So it's entirely feasible to have a separate 'page' file for each and every page, with code specific to that page on it.</p>\n\n<p>Additionally, if some of the code is shared between multiple pages, just set up a custom page template and assign that template to those pages that use it.</p>\n\n<p>Wordpress template heirarchy: <a href=\"http://codex.wordpress.org/Template_Hierarchy\" rel=\"nofollow\">http://codex.wordpress.org/Template_Hierarchy</a></p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 178032,
"author": "Brad Dalton",
"author_id": 9884,
"author_profile": "https://wordpress.stackexchange.com/users/9884",
"pm_score": 1,
"selected": false,
"text": "<p>Rather than insert PHP scripts into each page what you could do is execute PHP scripts using action <a href=\"http://codex.wordpress.org/Plugin_API/Hooks\" rel=\"nofollow\"><code>hooks</code></a> with conditional tags or modify the default output of an existing function using a filter hook with <a href=\"http://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow\"><code>conditional tag</code></a> for each page.</p>\n\n<p>You could also create template tags or write your own functions in a separate file and execute on any page in a custom function with conditional tag using the page I.D.</p>\n\n<p><strong>Filter Example</strong></p>\n\n<pre><code>add_filter( 'the_content', 'execute_before_content' ); \n\nfunction execute_before_content( $content ) { \n\nif ( is_singular('page') && function_exists('your_function')) {\n\n $before_content = your_function();\n\n $content = $before_content . $content;\n\n }\n\nreturn $content;\n}\n</code></pre>\n\n<p><strong>Action Hook Example:</strong></p>\n\n<pre><code>add_action( 'loop_start', 'your_function' );\nfunction your_function() {\nif ( is_page('007') && function_exists('your_template_tag')): \n your_template_tag();\nendif; \n}\n</code></pre>\n"
},
{
"answer_id": 178054,
"author": "tonymazz",
"author_id": 67509,
"author_profile": "https://wordpress.stackexchange.com/users/67509",
"pm_score": 0,
"selected": false,
"text": "<p>Can you elaborate on the use-case? As Brad stated, using hooks is the the best method to accomplish this functionally. You probably would want to create a plugin that you could maintain, upgrade and reuse... especially if this is for a client! </p>\n\n<p><a href=\"http://codex.wordpress.org/Writing_a_Plugin\" rel=\"nofollow\">http://codex.wordpress.org/Writing_a_Plugin</a></p>\n"
}
] |
2015/02/13
|
[
"https://wordpress.stackexchange.com/questions/178020",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67493/"
] |
I am trying to add static menu item to Wordpress Menu.I am using filter 'wp\_nav\_menu\_items' for this in functions.php. It works but it doesn't put it under menu container tag.
```
function add_nav_menu_items( $items , $args ) { ?>
<ul>
<li><a href="#">PRODUCTS</a>
<ul>
<li><a href="<?php echo esc_url(get_category_link(get_cat_ID('Sci-Fi')));?>">SCI-FI</a>
<ul>
<?php query_posts( array ('post_type'=>'scifi','showposts'=>-1,'order'=>'ASC') ); while ( have_posts() ) : the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; wp_reset_query(); ?>
</ul>
</li>
<li><a href="<?php echo esc_url(get_category_link(get_cat_ID('Drama')));?>">Drama</a>
<ul>
<?php query_posts( array ('post_type'=>'drama','showposts'=>-1,'order'=>'ASC') ); while ( have_posts() ) : the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; wp_reset_query(); ?>
</ul>
</li>
<li><a href="<?php echo esc_url(get_category_link(get_cat_ID('Horror')));?>">HORROR</a>
<ul>
<?php query_posts( array ('post_type'=>'horror','showposts'=>-1,'order'=> 'ASC') ); while ( have_posts() ) : the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; wp_reset_query(); ?>
</ul>
</li>
</ul>
</li>
</ul>
<?php return $items;}
add_filter( 'wp_nav_menu_items', 'add_nav_menu_items',10,2);
```
When i put the code online firebug show it like this
```
<div id="navigation_top">
<div id="navmenu_top">
<ul> **-->> This is my static menu**
<li>
</ul>
<ul id="menu-menu-1" class="menu-container"> **-->> This is WP_nav_menu**
<li class="type menu-item-object-page menu-item-587">
<li class="type menu-item-object-page menu-item-122">
<li class="type menu-item-object-page menu-item-121">
**I want my menu appear here **
</ul>
</div>
</div>
```
Is there anyway i can do this???
Thanks for any advice...
|
Rather than insert PHP scripts into each page what you could do is execute PHP scripts using action [`hooks`](http://codex.wordpress.org/Plugin_API/Hooks) with conditional tags or modify the default output of an existing function using a filter hook with [`conditional tag`](http://codex.wordpress.org/Conditional_Tags) for each page.
You could also create template tags or write your own functions in a separate file and execute on any page in a custom function with conditional tag using the page I.D.
**Filter Example**
```
add_filter( 'the_content', 'execute_before_content' );
function execute_before_content( $content ) {
if ( is_singular('page') && function_exists('your_function')) {
$before_content = your_function();
$content = $before_content . $content;
}
return $content;
}
```
**Action Hook Example:**
```
add_action( 'loop_start', 'your_function' );
function your_function() {
if ( is_page('007') && function_exists('your_template_tag')):
your_template_tag();
endif;
}
```
|
178,126 |
<p>I have 2 dropdown lists, when a user select value in the first list, there is an ajax call to a function using <code>WP_query</code> which send results to populate the second dropdown.</p>
<p>My <code>WP_query</code> is not returning any result. I'm new to <code>WP_query</code> so I should have made a mistake somewhere.</p>
<p>The query should return the posts having the meta_key <code>_wpcf_belongs_marque-type_id</code> with the meta_value equal to the parent id sent by ajax. The posts should also have the post_type 'aromes-type'.</p>
<p>Here is the function located in my <code>functions.php</code>:</p>
<pre><code>wp_enqueue_script( 'my-ajax-request', get_template_directory_uri() . '/js/ajax.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
add_action( 'wp_ajax_brand_children', 'GetBrandChildren');
add_action( 'wp_ajax_nopriv_brand_children', 'GetBrandChildren');
function GetBrandChildren() {
$output = '';
//retrieve POST data sent by AJAX
$parent_id = $_GET['parent_id'];
//Define query arguments
$args = array(
'post_type' => 'aromes-type',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => '_wpcf_belongs_marque-type_id',
'value' => $parent_id
),
),
'posts_per_page' => -1
);
//Create the query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$output .= '<option>' . get_the_title() . '</option>';
endwhile;
else:
$output = '<option>No flavors found...</option>';
endif;
echo $output;
// Reset Post Data
wp_reset_postdata();
wp_die();
}
</code></pre>
<p>The JQuery making the call :</p>
<pre><code>//On selected brand, update flavors list
$(document).on('change', "select[id^='marque']", function() {
var $brandid = $(this).val();
var $brand_dd_id = $(this).attr('id');
var $flav_dd_id = $brand_dd_id.substr($brand_dd_id.length-1);
//Make AJAX request, using the selected value as the GET
$.ajax({
url: MyAjax.ajaxurl,
beforeSend: function(){$("#arome"+$flav_dd_id+".ul.select2-results").empty();},
data: {
'parent_id': $brandid,
'action': 'brand_children'
},
success: function(output) {
console.log(output);
$("#arome"+$flav_dd_id+".ul.select2-results").append(output);
$("#arome"+$flav_dd_id).trigger("chosen:updated");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " "+ thrownError);
}});
});
</code></pre>
|
[
{
"answer_id": 178131,
"author": "Bruno Rodrigues",
"author_id": 42886,
"author_profile": "https://wordpress.stackexchange.com/users/42886",
"pm_score": 1,
"selected": true,
"text": "<p>Try using this:</p>\n\n<pre><code>$args = array(\n 'post_type' => YOUR_POST_TYPE,\n 'meta_query' => array(\n array(\n 'key' => '_wpcf_belongs_marque-type_id',\n 'value' => $parent_id\n )\n )\n);\n</code></pre>\n\n<p>In your loop set an <code>else</code> statement just to sure that you query isn't returning zero results:</p>\n\n<pre><code>if ( $the_query->have_posts() ) :\n while ( $the_query->have_posts() ) : $the_query->the_post();\n $output .= '<li class=\"active-results\">' . the_title() . '</li>';\n endwhile;\nelse:\n $output = 'No items here :(';\nendif;\n</code></pre>\n\n<p>Hope it helps.</p>\n"
},
{
"answer_id": 178474,
"author": "user3515709",
"author_id": 67069,
"author_profile": "https://wordpress.stackexchange.com/users/67069",
"pm_score": 1,
"selected": false,
"text": "<p>You right Bruno, the AND is optional, I tried without it and it is now working, not sure why, here is the code :</p>\n\n<pre><code>function GetBrandChildren() {\n\n $output = '';\n //retrieve POST data sent by AJAX\n $parent_id = $_GET['parent_id'];\n\n //Define query arguments\n $args = array(\n 'post_type' => 'aromes-type',\n 'meta_query' => array(\n array(\n 'key' => '_wpcf_belongs_marque-type_id',\n 'value' => $parent_id\n ),\n ),\n 'posts_per_page' => -1\n );\n\n\n //Create the query\n $the_query = new WP_Query( $args );\n\n // The Loop\n if ( $the_query->have_posts() ) :\n while ( $the_query->have_posts() ) : $the_query->the_post();\n $output .= '<option>' . get_the_title() . '</option>';\n endwhile;\n else:\n $output = '<option>No flavors found...</option>';\n endif;\n\n echo $output;\n\n // Reset Post Data\n wp_reset_postdata();\n wp_die();\n}\n</code></pre>\n"
}
] |
2015/02/14
|
[
"https://wordpress.stackexchange.com/questions/178126",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67069/"
] |
I have 2 dropdown lists, when a user select value in the first list, there is an ajax call to a function using `WP_query` which send results to populate the second dropdown.
My `WP_query` is not returning any result. I'm new to `WP_query` so I should have made a mistake somewhere.
The query should return the posts having the meta\_key `_wpcf_belongs_marque-type_id` with the meta\_value equal to the parent id sent by ajax. The posts should also have the post\_type 'aromes-type'.
Here is the function located in my `functions.php`:
```
wp_enqueue_script( 'my-ajax-request', get_template_directory_uri() . '/js/ajax.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
add_action( 'wp_ajax_brand_children', 'GetBrandChildren');
add_action( 'wp_ajax_nopriv_brand_children', 'GetBrandChildren');
function GetBrandChildren() {
$output = '';
//retrieve POST data sent by AJAX
$parent_id = $_GET['parent_id'];
//Define query arguments
$args = array(
'post_type' => 'aromes-type',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => '_wpcf_belongs_marque-type_id',
'value' => $parent_id
),
),
'posts_per_page' => -1
);
//Create the query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$output .= '<option>' . get_the_title() . '</option>';
endwhile;
else:
$output = '<option>No flavors found...</option>';
endif;
echo $output;
// Reset Post Data
wp_reset_postdata();
wp_die();
}
```
The JQuery making the call :
```
//On selected brand, update flavors list
$(document).on('change', "select[id^='marque']", function() {
var $brandid = $(this).val();
var $brand_dd_id = $(this).attr('id');
var $flav_dd_id = $brand_dd_id.substr($brand_dd_id.length-1);
//Make AJAX request, using the selected value as the GET
$.ajax({
url: MyAjax.ajaxurl,
beforeSend: function(){$("#arome"+$flav_dd_id+".ul.select2-results").empty();},
data: {
'parent_id': $brandid,
'action': 'brand_children'
},
success: function(output) {
console.log(output);
$("#arome"+$flav_dd_id+".ul.select2-results").append(output);
$("#arome"+$flav_dd_id).trigger("chosen:updated");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " "+ thrownError);
}});
});
```
|
Try using this:
```
$args = array(
'post_type' => YOUR_POST_TYPE,
'meta_query' => array(
array(
'key' => '_wpcf_belongs_marque-type_id',
'value' => $parent_id
)
)
);
```
In your loop set an `else` statement just to sure that you query isn't returning zero results:
```
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$output .= '<li class="active-results">' . the_title() . '</li>';
endwhile;
else:
$output = 'No items here :(';
endif;
```
Hope it helps.
|
178,132 |
<p>I do not want to have a function loaded by my theme on a page template. </p>
<ol>
<li>Is this the correct syntax?</li>
<li>What does 99 mean here? <code>add_filter('the_content', 'oswc_formatter', 99);</code></li>
<li>Could I apply the condition on the <code>add_filter</code> instead of what I did? </li>
</ol>
<p>This is my code:</p>
<pre><code>function oswc_formatter($content) {
if( !is_page_template( 'template-flat.php' ) ) {
$new_content = '';
/* Matches the contents and the open and closing tags */
$pattern_full = '{(\[raw\].*?\[/raw\])}is';
/* Matches just the contents */
$pattern_contents = '{\[raw\](.*?)\[/raw\]}is';
/* Divide content into pieces */
$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);
/* Loop over pieces */
foreach ($pieces as $piece) {
/* Look for presence of the shortcode */
if (preg_match($pattern_contents, $piece, $matches)) {
/* Append to content (no formatting) */
$new_content .= $matches[1];
} else {
/* Format and append to content */
$new_content .= wptexturize(wpautop($piece));
}
}
return $new_content;
}
}
// Before displaying for viewing, apply this function
add_filter('the_content', 'oswc_formatter', 99);
add_filter('widget_text', 'oswc_formatter', 99);
</code></pre>
|
[
{
"answer_id": 178131,
"author": "Bruno Rodrigues",
"author_id": 42886,
"author_profile": "https://wordpress.stackexchange.com/users/42886",
"pm_score": 1,
"selected": true,
"text": "<p>Try using this:</p>\n\n<pre><code>$args = array(\n 'post_type' => YOUR_POST_TYPE,\n 'meta_query' => array(\n array(\n 'key' => '_wpcf_belongs_marque-type_id',\n 'value' => $parent_id\n )\n )\n);\n</code></pre>\n\n<p>In your loop set an <code>else</code> statement just to sure that you query isn't returning zero results:</p>\n\n<pre><code>if ( $the_query->have_posts() ) :\n while ( $the_query->have_posts() ) : $the_query->the_post();\n $output .= '<li class=\"active-results\">' . the_title() . '</li>';\n endwhile;\nelse:\n $output = 'No items here :(';\nendif;\n</code></pre>\n\n<p>Hope it helps.</p>\n"
},
{
"answer_id": 178474,
"author": "user3515709",
"author_id": 67069,
"author_profile": "https://wordpress.stackexchange.com/users/67069",
"pm_score": 1,
"selected": false,
"text": "<p>You right Bruno, the AND is optional, I tried without it and it is now working, not sure why, here is the code :</p>\n\n<pre><code>function GetBrandChildren() {\n\n $output = '';\n //retrieve POST data sent by AJAX\n $parent_id = $_GET['parent_id'];\n\n //Define query arguments\n $args = array(\n 'post_type' => 'aromes-type',\n 'meta_query' => array(\n array(\n 'key' => '_wpcf_belongs_marque-type_id',\n 'value' => $parent_id\n ),\n ),\n 'posts_per_page' => -1\n );\n\n\n //Create the query\n $the_query = new WP_Query( $args );\n\n // The Loop\n if ( $the_query->have_posts() ) :\n while ( $the_query->have_posts() ) : $the_query->the_post();\n $output .= '<option>' . get_the_title() . '</option>';\n endwhile;\n else:\n $output = '<option>No flavors found...</option>';\n endif;\n\n echo $output;\n\n // Reset Post Data\n wp_reset_postdata();\n wp_die();\n}\n</code></pre>\n"
}
] |
2015/02/14
|
[
"https://wordpress.stackexchange.com/questions/178132",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40727/"
] |
I do not want to have a function loaded by my theme on a page template.
1. Is this the correct syntax?
2. What does 99 mean here? `add_filter('the_content', 'oswc_formatter', 99);`
3. Could I apply the condition on the `add_filter` instead of what I did?
This is my code:
```
function oswc_formatter($content) {
if( !is_page_template( 'template-flat.php' ) ) {
$new_content = '';
/* Matches the contents and the open and closing tags */
$pattern_full = '{(\[raw\].*?\[/raw\])}is';
/* Matches just the contents */
$pattern_contents = '{\[raw\](.*?)\[/raw\]}is';
/* Divide content into pieces */
$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);
/* Loop over pieces */
foreach ($pieces as $piece) {
/* Look for presence of the shortcode */
if (preg_match($pattern_contents, $piece, $matches)) {
/* Append to content (no formatting) */
$new_content .= $matches[1];
} else {
/* Format and append to content */
$new_content .= wptexturize(wpautop($piece));
}
}
return $new_content;
}
}
// Before displaying for viewing, apply this function
add_filter('the_content', 'oswc_formatter', 99);
add_filter('widget_text', 'oswc_formatter', 99);
```
|
Try using this:
```
$args = array(
'post_type' => YOUR_POST_TYPE,
'meta_query' => array(
array(
'key' => '_wpcf_belongs_marque-type_id',
'value' => $parent_id
)
)
);
```
In your loop set an `else` statement just to sure that you query isn't returning zero results:
```
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$output .= '<li class="active-results">' . the_title() . '</li>';
endwhile;
else:
$output = 'No items here :(';
endif;
```
Hope it helps.
|
178,135 |
<p>I have a WordPress site which has the built-in login form with the url <code>http://domain.com/wp-login.php</code> and register page <code>http://domain.com/wp-login.php?action=register</code></p>
<p>I want to display these forms on a page I created from the backend.</p>
<p>login </p>
<pre><code>http://domain.com/profile/login
</code></pre>
<p>register </p>
<pre><code>http://domain.com/profile/register
</code></pre>
<p>Is it possible and how can I do this?</p>
|
[
{
"answer_id": 178136,
"author": "Bruno Rodrigues",
"author_id": 42886,
"author_profile": "https://wordpress.stackexchange.com/users/42886",
"pm_score": 1,
"selected": false,
"text": "<p>You could try to add this to your <code>.htaccess</code> file:</p>\n\n<pre><code>Redirect 301 http://domain.com/wp-login.php http://domain.com/profile/login\nRedirect 301 http://domain.com/wp-login.php?action=register http://domain.com/profile/register\n</code></pre>\n\n<p>Hope it helps.</p>\n"
},
{
"answer_id": 211946,
"author": "David Ryal 'Pug' Anderson",
"author_id": 2786,
"author_profile": "https://wordpress.stackexchange.com/users/2786",
"pm_score": 0,
"selected": false,
"text": "<p>Use the Theme My Login plugin: <a href=\"https://wordpress.org/plugins/theme-my-login/\" rel=\"nofollow\">https://wordpress.org/plugins/theme-my-login/</a></p>\n"
}
] |
2015/02/14
|
[
"https://wordpress.stackexchange.com/questions/178135",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67551/"
] |
I have a WordPress site which has the built-in login form with the url `http://domain.com/wp-login.php` and register page `http://domain.com/wp-login.php?action=register`
I want to display these forms on a page I created from the backend.
login
```
http://domain.com/profile/login
```
register
```
http://domain.com/profile/register
```
Is it possible and how can I do this?
|
You could try to add this to your `.htaccess` file:
```
Redirect 301 http://domain.com/wp-login.php http://domain.com/profile/login
Redirect 301 http://domain.com/wp-login.php?action=register http://domain.com/profile/register
```
Hope it helps.
|
178,139 |
<p>The posts in the website I'm currently working on have multiple hierarchical categories applied to each of them. For instance:</p>
<pre><code>Source
- Books
-- Moby Dick
-- Sherlock Holmes
</code></pre>
<p>The permalinks are set as <code>/%category%/%postname%/</code>. However, the URL of a post does not include all subcategories - all I get is <code>site.com/source/books/*postname*</code>, even though the post in question has NOT been categories in Source, but only in Books + Moby Dick.</p>
<p>Could anyone help me figure out how to adjust this behaviour?</p>
<p>Thank you.</p>
|
[
{
"answer_id": 178169,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 3,
"selected": true,
"text": "<p>The permastruct <code>/%category%/%postname%/</code> will include the categories and subcategories in the URL <strong>from top to first assigned child</strong>. So, if you want the URL be <code>site.com/source/books/moby-dick/*postname*</code>, you have to assign the post only to \"Moby Dick\". Assigning the post only to \"Moby Dick\" category will still show the post under \"source\" and \"books\" category archives by default.</p>\n"
},
{
"answer_id": 267891,
"author": "Macarthurval",
"author_id": 120229,
"author_profile": "https://wordpress.stackexchange.com/users/120229",
"pm_score": 0,
"selected": false,
"text": "<p>Here you have a full solution, even you have multiple categories assigned to your post:</p>\n\n<pre><code>function permalink_full_categories( $cat, $cats, $post ) {\n\n $ordering = array();\n foreach( $cats as $index => $this_cat) {\n $ordering[$this_cat->parent] = $index;\n }\n\n $ordered = array();\n $i = 0;\n\n while( $ordering[$i] !== null ){\n array_push( $ordered, $cats[$ordering[$i]] );\n $i = $cats[$ordering[$i]]->term_id;\n }\n\n return end($cats);\n}\n\nadd_filter( 'post_link_category', 'permalink_full_categories', 20, 3 );\n</code></pre>\n\n<p>It filters the permalink category changing its default behavior, returning the last category of the hierarchy.</p>\n\n<p>By consequence, the Wordpress core write the full hierarchy category url.</p>\n"
}
] |
2015/02/14
|
[
"https://wordpress.stackexchange.com/questions/178139",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63683/"
] |
The posts in the website I'm currently working on have multiple hierarchical categories applied to each of them. For instance:
```
Source
- Books
-- Moby Dick
-- Sherlock Holmes
```
The permalinks are set as `/%category%/%postname%/`. However, the URL of a post does not include all subcategories - all I get is `site.com/source/books/*postname*`, even though the post in question has NOT been categories in Source, but only in Books + Moby Dick.
Could anyone help me figure out how to adjust this behaviour?
Thank you.
|
The permastruct `/%category%/%postname%/` will include the categories and subcategories in the URL **from top to first assigned child**. So, if you want the URL be `site.com/source/books/moby-dick/*postname*`, you have to assign the post only to "Moby Dick". Assigning the post only to "Moby Dick" category will still show the post under "source" and "books" category archives by default.
|
178,144 |
<p><code>shortcode_unautop()</code> in <code>/wp-includes/formatting.php</code> is supposed to find shortcodes in a block of text and remove wrapping paragraph tags from them.</p>
<p>I've been having issues with paragraph tags making it through this process. </p>
<p>Here's the output from <code>var_dump($pee)</code>, which I placed at the very beginning of the function, i.e., the string before being processed:</p>
<pre><code>string(353) "<p>[row wrap="true"]</p>
<p>[one_half]</p>
<p>[text_block]Fusce blandit adipiscing libero, nec bibendum diam volutpat tempor.[/text_block]</p>
<p>[/one_half]</p>
<p>[one_half last="true"]</p>
<p>[text_block]Donec fermentum diam leo, ut convallis nisl tristique ut. Ut rhoncus leo vitae tempus pulvinar.[/text_block]</p>
<p>[/one_half]</p>
<p>[/row]</p>
"
</code></pre>
<p>All wrapped in paragraph tags, as expected.</p>
<p>I then put <code>var_dump(preg_replace( $pattern, '$1', $pee ));</code> just before the end of the function, which gives:</p>
<pre><code>string(346) "[row wrap="true"]</p>
<p>[one_half]</p>
<p>[text_block]Fusce blandit adipiscing libero, nec bibendum diam volutpat tempor.[/text_block]</p>
<p>[/one_half]</p>
<p>[one_half last="true"]</p>
<p>[text_block]Donec fermentum diam leo, ut convallis nisl tristique ut. Ut rhoncus leo vitae tempus pulvinar.[/text_block]</p>
<p>[/one_half]</p>
<p>[/row]
"
</code></pre>
<p>All it has done is remove the opening and closing tags from the entire block, instead of each individual shortcode. I checked the value of <code>global $shortcode_tags;</code> and all the shortcodes in my example were in it.</p>
<p>Is the function broken, or am I expecting too much from it? I'm pretty sure I'm not and it is supposed to remove all the paragraph tags - but I can't help thinking something else is going on, like unexpected space characters or something.</p>
|
[
{
"answer_id": 178161,
"author": "mathieuhays",
"author_id": 67529,
"author_profile": "https://wordpress.stackexchange.com/users/67529",
"pm_score": 1,
"selected": false,
"text": "<p>I've been reading the WordPress documentation about this function and the behaviour you are having there, is the one expected to happen.</p>\n\n<p>This function clean outside of the shortcode and not inside. The regex is not checking the content of the shortcode.</p>\n\n<p>EDIT:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/shortcode_unautop/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/shortcode_unautop/</a></p>\n\n<blockquote>\n <p>Don’t auto-p wrap shortcodes that stand alone</p>\n \n <p>Ensures that shortcodes are not <strong>wrapped</strong> in <code><p>...</p></code>.</p>\n</blockquote>\n\n<p>Everything is said there. </p>\n"
},
{
"answer_id": 178179,
"author": "EpF",
"author_id": 34363,
"author_profile": "https://wordpress.stackexchange.com/users/34363",
"pm_score": 3,
"selected": true,
"text": "<p>It seems the function <em>is</em> broken. The issue is in trac: <a href=\"https://core.trac.wordpress.org/ticket/14050\" rel=\"nofollow\">https://core.trac.wordpress.org/ticket/14050</a></p>\n\n<p>I am using this to solve the problem temporarily: <a href=\"https://core.trac.wordpress.org/attachment/ticket/14050/plugin.php\" rel=\"nofollow\">https://core.trac.wordpress.org/attachment/ticket/14050/plugin.php</a> . This code still fails some of the tests used, but it completely resolves the issue I described, so I will use it unless I find something practical that it breaks.</p>\n"
}
] |
2015/02/14
|
[
"https://wordpress.stackexchange.com/questions/178144",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34363/"
] |
`shortcode_unautop()` in `/wp-includes/formatting.php` is supposed to find shortcodes in a block of text and remove wrapping paragraph tags from them.
I've been having issues with paragraph tags making it through this process.
Here's the output from `var_dump($pee)`, which I placed at the very beginning of the function, i.e., the string before being processed:
```
string(353) "<p>[row wrap="true"]</p>
<p>[one_half]</p>
<p>[text_block]Fusce blandit adipiscing libero, nec bibendum diam volutpat tempor.[/text_block]</p>
<p>[/one_half]</p>
<p>[one_half last="true"]</p>
<p>[text_block]Donec fermentum diam leo, ut convallis nisl tristique ut. Ut rhoncus leo vitae tempus pulvinar.[/text_block]</p>
<p>[/one_half]</p>
<p>[/row]</p>
"
```
All wrapped in paragraph tags, as expected.
I then put `var_dump(preg_replace( $pattern, '$1', $pee ));` just before the end of the function, which gives:
```
string(346) "[row wrap="true"]</p>
<p>[one_half]</p>
<p>[text_block]Fusce blandit adipiscing libero, nec bibendum diam volutpat tempor.[/text_block]</p>
<p>[/one_half]</p>
<p>[one_half last="true"]</p>
<p>[text_block]Donec fermentum diam leo, ut convallis nisl tristique ut. Ut rhoncus leo vitae tempus pulvinar.[/text_block]</p>
<p>[/one_half]</p>
<p>[/row]
"
```
All it has done is remove the opening and closing tags from the entire block, instead of each individual shortcode. I checked the value of `global $shortcode_tags;` and all the shortcodes in my example were in it.
Is the function broken, or am I expecting too much from it? I'm pretty sure I'm not and it is supposed to remove all the paragraph tags - but I can't help thinking something else is going on, like unexpected space characters or something.
|
It seems the function *is* broken. The issue is in trac: <https://core.trac.wordpress.org/ticket/14050>
I am using this to solve the problem temporarily: <https://core.trac.wordpress.org/attachment/ticket/14050/plugin.php> . This code still fails some of the tests used, but it completely resolves the issue I described, so I will use it unless I find something practical that it breaks.
|
178,145 |
<p>In the year archive page in the title tag i get</p>
<pre><code>Notice: Undefined index: 00 in wp-includes\locale.php on line 271
</code></pre>
<p>In the header.php i use:</p>
<pre><code><title><?php wp_title('|', true, 'right'); ?></title>
</code></pre>
<p>I even tried to use in functions.php </p>
<pre><code>add_theme_support( 'title-tag' );
</code></pre>
<p>My question: is WordPress fault or my theme fault?
I search on Google the notice and i found dozen of sites with this error on their titles.
My temporary fix is to check if is year archive page and set the title.
Any other ideas?</p>
|
[
{
"answer_id": 178161,
"author": "mathieuhays",
"author_id": 67529,
"author_profile": "https://wordpress.stackexchange.com/users/67529",
"pm_score": 1,
"selected": false,
"text": "<p>I've been reading the WordPress documentation about this function and the behaviour you are having there, is the one expected to happen.</p>\n\n<p>This function clean outside of the shortcode and not inside. The regex is not checking the content of the shortcode.</p>\n\n<p>EDIT:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/shortcode_unautop/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/shortcode_unautop/</a></p>\n\n<blockquote>\n <p>Don’t auto-p wrap shortcodes that stand alone</p>\n \n <p>Ensures that shortcodes are not <strong>wrapped</strong> in <code><p>...</p></code>.</p>\n</blockquote>\n\n<p>Everything is said there. </p>\n"
},
{
"answer_id": 178179,
"author": "EpF",
"author_id": 34363,
"author_profile": "https://wordpress.stackexchange.com/users/34363",
"pm_score": 3,
"selected": true,
"text": "<p>It seems the function <em>is</em> broken. The issue is in trac: <a href=\"https://core.trac.wordpress.org/ticket/14050\" rel=\"nofollow\">https://core.trac.wordpress.org/ticket/14050</a></p>\n\n<p>I am using this to solve the problem temporarily: <a href=\"https://core.trac.wordpress.org/attachment/ticket/14050/plugin.php\" rel=\"nofollow\">https://core.trac.wordpress.org/attachment/ticket/14050/plugin.php</a> . This code still fails some of the tests used, but it completely resolves the issue I described, so I will use it unless I find something practical that it breaks.</p>\n"
}
] |
2015/02/14
|
[
"https://wordpress.stackexchange.com/questions/178145",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47813/"
] |
In the year archive page in the title tag i get
```
Notice: Undefined index: 00 in wp-includes\locale.php on line 271
```
In the header.php i use:
```
<title><?php wp_title('|', true, 'right'); ?></title>
```
I even tried to use in functions.php
```
add_theme_support( 'title-tag' );
```
My question: is WordPress fault or my theme fault?
I search on Google the notice and i found dozen of sites with this error on their titles.
My temporary fix is to check if is year archive page and set the title.
Any other ideas?
|
It seems the function *is* broken. The issue is in trac: <https://core.trac.wordpress.org/ticket/14050>
I am using this to solve the problem temporarily: <https://core.trac.wordpress.org/attachment/ticket/14050/plugin.php> . This code still fails some of the tests used, but it completely resolves the issue I described, so I will use it unless I find something practical that it breaks.
|
178,146 |
<p>If I have developed a separate HTML page that I wish to include inside my Wordpress site what is the best way of including it?
In this case it requires a javascript library or stylesheet that is not by default in my Wordpress theme that would need to be inserted in the tag.</p>
<p>I am aware of the following solutions:</p>
<p>iFrames:</p>
<ul>
<li>To match the site styling I would need to include every css from the theme in the iframe header.</li>
<li>If the theme is updated with another script style sheet, this would not be updated in the iframe, maintenance could be arduous.</li>
</ul>
<p>Editing the theme:</p>
<p>I could add into the various theme files along the lines:</p>
<pre><code>is_single( 'page1' )
add_action( 'wp_head', 'extra_stuff' )
</code></pre>
<p>For each post/page I create or change I would have to change the theme files accordingly.</p>
<p>Ideally I would like to be able to do this from within the post editor</p>
<p>Are there any plugins that accomplish this?</p>
|
[
{
"answer_id": 178150,
"author": "stanton119",
"author_id": 67552,
"author_profile": "https://wordpress.stackexchange.com/users/67552",
"pm_score": 3,
"selected": true,
"text": "<p>I found the best solution was to add a custom field, <code>head</code>, and then build a short plugin to add the contents to the head tag:</p>\n\n<pre><code>add_action('wp_head', 'add_HTML_head');\nfunction add_HTML_head(){\n global $post;\n if(!empty($post)){\n // get custom field for 'head'\n $headHTML = get_post_meta($post->ID, 'head', true);\n if(!empty($headHTML)){\n echo $headHTML;\n }\n }\n}\n</code></pre>\n\n<p>I've packaged it up into a simple <a href=\"http://www.richard-stanton.com/wordpress/wordpress-html/\" rel=\"nofollow noreferrer\">plugin</a>.</p>\n"
},
{
"answer_id": 178176,
"author": "mike23",
"author_id": 1381,
"author_profile": "https://wordpress.stackexchange.com/users/1381",
"pm_score": 1,
"selected": false,
"text": "<p>For this kind of situation you can create a <a href=\"http://codex.wordpress.org/Page_Templates#Custom_Page_Template\" rel=\"nofollow\">custom template</a> for your page, as well as a specific header, for example : </p>\n\n<ul>\n<li><em>template-custompage.php</em> (your page template)</li>\n<li><em>header-custompage.php</em> (your custom header, where you call your custom CSS and scripts)</li>\n</ul>\n\n<p>In <em>template-custompage.php</em>, you call your custom header with : </p>\n\n<pre><code>get_header( 'custompage' );\n</code></pre>\n\n<p>Then create your page as you would normally in the Wordpress editor, and choose your custom page template in the pages attributes block.</p>\n"
}
] |
2015/02/14
|
[
"https://wordpress.stackexchange.com/questions/178146",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67552/"
] |
If I have developed a separate HTML page that I wish to include inside my Wordpress site what is the best way of including it?
In this case it requires a javascript library or stylesheet that is not by default in my Wordpress theme that would need to be inserted in the tag.
I am aware of the following solutions:
iFrames:
* To match the site styling I would need to include every css from the theme in the iframe header.
* If the theme is updated with another script style sheet, this would not be updated in the iframe, maintenance could be arduous.
Editing the theme:
I could add into the various theme files along the lines:
```
is_single( 'page1' )
add_action( 'wp_head', 'extra_stuff' )
```
For each post/page I create or change I would have to change the theme files accordingly.
Ideally I would like to be able to do this from within the post editor
Are there any plugins that accomplish this?
|
I found the best solution was to add a custom field, `head`, and then build a short plugin to add the contents to the head tag:
```
add_action('wp_head', 'add_HTML_head');
function add_HTML_head(){
global $post;
if(!empty($post)){
// get custom field for 'head'
$headHTML = get_post_meta($post->ID, 'head', true);
if(!empty($headHTML)){
echo $headHTML;
}
}
}
```
I've packaged it up into a simple [plugin](http://www.richard-stanton.com/wordpress/wordpress-html/).
|
178,148 |
<p>If the custom post type is known (e.g., 'reference') then the add_action is </p>
<pre><code>add_action( 'publish_reference' , 'run_new_post_code' );
</code></pre>
<p>Great. But what is the proper code for an unknown custom post type? I tried to add a text box so the custom_post_type could be added by the end-user. This is then called in <code>$custom_post_type =</code>. A wp_die shows the $custom_post_type is returned correctly. But the <code>publish_{$custom_post_type}</code> must be the wrong way to fire the add_action because this fails.</p>
<pre><code>$custom_post_type = $options['custom_post_type'];
add_action( 'publish_{$custom_post_type}' , 'run_new_post_code' );
</code></pre>
<p>What is a good way to get an add_action written so it'll work for any customer's custom_post_type?</p>
<p>Update: This works but is still only for one custom post type. What about multiple custom post types?</p>
<pre><code>$custom_post_type = $options['custom_post_type'];
add_action( 'publish_' . $custom_post_type , 'run_new_post_code' );
</code></pre>
|
[
{
"answer_id": 178150,
"author": "stanton119",
"author_id": 67552,
"author_profile": "https://wordpress.stackexchange.com/users/67552",
"pm_score": 3,
"selected": true,
"text": "<p>I found the best solution was to add a custom field, <code>head</code>, and then build a short plugin to add the contents to the head tag:</p>\n\n<pre><code>add_action('wp_head', 'add_HTML_head');\nfunction add_HTML_head(){\n global $post;\n if(!empty($post)){\n // get custom field for 'head'\n $headHTML = get_post_meta($post->ID, 'head', true);\n if(!empty($headHTML)){\n echo $headHTML;\n }\n }\n}\n</code></pre>\n\n<p>I've packaged it up into a simple <a href=\"http://www.richard-stanton.com/wordpress/wordpress-html/\" rel=\"nofollow noreferrer\">plugin</a>.</p>\n"
},
{
"answer_id": 178176,
"author": "mike23",
"author_id": 1381,
"author_profile": "https://wordpress.stackexchange.com/users/1381",
"pm_score": 1,
"selected": false,
"text": "<p>For this kind of situation you can create a <a href=\"http://codex.wordpress.org/Page_Templates#Custom_Page_Template\" rel=\"nofollow\">custom template</a> for your page, as well as a specific header, for example : </p>\n\n<ul>\n<li><em>template-custompage.php</em> (your page template)</li>\n<li><em>header-custompage.php</em> (your custom header, where you call your custom CSS and scripts)</li>\n</ul>\n\n<p>In <em>template-custompage.php</em>, you call your custom header with : </p>\n\n<pre><code>get_header( 'custompage' );\n</code></pre>\n\n<p>Then create your page as you would normally in the Wordpress editor, and choose your custom page template in the pages attributes block.</p>\n"
}
] |
2015/02/14
|
[
"https://wordpress.stackexchange.com/questions/178148",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47326/"
] |
If the custom post type is known (e.g., 'reference') then the add\_action is
```
add_action( 'publish_reference' , 'run_new_post_code' );
```
Great. But what is the proper code for an unknown custom post type? I tried to add a text box so the custom\_post\_type could be added by the end-user. This is then called in `$custom_post_type =`. A wp\_die shows the $custom\_post\_type is returned correctly. But the `publish_{$custom_post_type}` must be the wrong way to fire the add\_action because this fails.
```
$custom_post_type = $options['custom_post_type'];
add_action( 'publish_{$custom_post_type}' , 'run_new_post_code' );
```
What is a good way to get an add\_action written so it'll work for any customer's custom\_post\_type?
Update: This works but is still only for one custom post type. What about multiple custom post types?
```
$custom_post_type = $options['custom_post_type'];
add_action( 'publish_' . $custom_post_type , 'run_new_post_code' );
```
|
I found the best solution was to add a custom field, `head`, and then build a short plugin to add the contents to the head tag:
```
add_action('wp_head', 'add_HTML_head');
function add_HTML_head(){
global $post;
if(!empty($post)){
// get custom field for 'head'
$headHTML = get_post_meta($post->ID, 'head', true);
if(!empty($headHTML)){
echo $headHTML;
}
}
}
```
I've packaged it up into a simple [plugin](http://www.richard-stanton.com/wordpress/wordpress-html/).
|
178,155 |
<p>Normally, in WordPress, the page title appears in the content area. I'd like to have the page title appear in the header area. It looks like to do that, I'd have to remove it from its current location in the content-page.php and place it in header.php. But content-page.php is called from page.php, which calls the content-page from within a while loop (<code>while ( have_posts() ) : the_post(); ...</code> ) -- so I'd have to move or copy this into the header as well, I think. Seems like a lot of trouble. </p>
<p>Would it make more sense to move part of the header html into the page content, so I don't have to run the while loop more than once?</p>
<p>(As a learning tool, I'm re-creating an existing html site with WordPress, using the _s starter theme.)</p>
<p>--- EDIT ---</p>
<p>Thanks for answers. Very helpful. Here are results of some testing, based on your answers. Given the following code, in header (outside Loop):</p>
<pre><code>wp_title(): <?php wp_title('', true,''); ?><br>
the_title(): <?php the_title(); ?><br>
single_post_title(): <?php single_post_title(); ?><br>
$post->post_name: <?php echo 'page name: ' . $post->post_name; ?><br>
ispage? : <?php echo (is_page() ? 'yes' : 'no'); ?><br>
ispage(about-us) : <?php echo (is_page('about-us') ? 'yes' : 'no'); ?><br>
ispage(About Us) : <?php echo (is_page('About Us') ? 'yes' : 'no'); ?>
</code></pre>
<p>When viewed from my About Us page, I get:</p>
<pre><code>wp_title() About UsAt The Tabernacle
the_title(): About Us
single_post_title(): About Us
$post->post_name: page name: about-us
ispage? : yes
ispage(about-us) : yes
ispage(About Us) : yes
</code></pre>
<p>When viewed from my Home page, I get:</p>
<pre><code>wp_title(): At The Tabernacle My site motto here
the_title(): Home
single_post_title(): Home
$post->post_name: page name: home
ispage? : yes
ispage(about-us) : no
ispage(About Us) : no
</code></pre>
<p>And when viewed from a "Hello World" post, I get:</p>
<pre><code>wp_title(): Hello world!At The Tabernacle
the_title(): Hello world!
single_post_title(): Hello world!
$post->post_name: page name: hello-world
ispage? : no
ispage(about-us) : no
ispage(About Us) : no
</code></pre>
<p>Conclusion: I can use the_title() or single_post_title() (wp_title returns more text than I want). And I can test is_page(...) in order to display a specific page name when I'm viewing a post.</p>
<p>Thank you!</p>
|
[
{
"answer_id": 178158,
"author": "mathieuhays",
"author_id": 67529,
"author_profile": "https://wordpress.stackexchange.com/users/67529",
"pm_score": 4,
"selected": true,
"text": "<p>If you only need the title you can request it outside the loop easily.</p>\n\n<p><em>Try and call <code>the_title()</code> in your header. It should work</em></p>\n\n<p>But you have to be aware that if you don't put a condition, each page of your website will display its title in the header section.</p>\n\n<p>EDIT: the function to call is <code>get_the_title($post->ID)</code> since <code>the_title()</code> doesn't allow you to specify the post id as an argument. You can check on the <a href=\"http://codex.wordpress.org/\" rel=\"noreferrer\">Wordpress Codex</a> for function allowing you to query information from your post outside the loop.</p>\n"
},
{
"answer_id": 178160,
"author": "user3325126",
"author_id": 56674,
"author_profile": "https://wordpress.stackexchange.com/users/56674",
"pm_score": 2,
"selected": false,
"text": "<p>You need to use wp_title();</p>\n\n<p>If you're trying to use the post title like so:</p>\n\n<pre><code><head> \n <title> post title here </title> \n</head>\n</code></pre>\n\n<p>You would need to add the wp_title(' ', true , ' ');</p>\n\n<pre><code><head>\n <title> <?php wp_title('', true,''); ?> </title>\n</head>\n</code></pre>\n\n<p>For example: If your post name was Hello World, Hello World would now show up in the tab.</p>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/wp_title\" rel=\"nofollow\">http://codex.wordpress.org/Function_Reference/wp_title</a></p>\n"
},
{
"answer_id": 319273,
"author": "Vishwa",
"author_id": 120712,
"author_profile": "https://wordpress.stackexchange.com/users/120712",
"pm_score": 2,
"selected": false,
"text": "<p>While above mentioned methods are working for the moment, WordPress core developers <a href=\"https://make.wordpress.org/core/2014/10/29/title-tags-in-4-1/\" rel=\"nofollow noreferrer\">recommends</a> as follows:</p>\n\n<blockquote>\n <p>Starting with 4.1 and Twenty Fifteen, the recommended way for themes\n to display titles is by adding theme support like this:\n -<a href=\"https://profiles.wordpress.org/obenland\" rel=\"nofollow noreferrer\">Konstantin Obenland</a> </p>\n</blockquote>\n\n<p>You can either add this line in your theme's functions.php file after the <strong>after_setup_theme</strong>.\n \nor</p>\n\n<p>from same page, </p>\n\n<blockquote>\n <p>Starting with 4.1 and Twenty Fifteen, the recommended way for themes\n to display titles is by adding theme support like this:</p>\n\n<pre><code>function theme_slug_setup() {\n add_theme_support( 'title-tag' );\n}\nadd_action( 'after_setup_theme', 'theme_slug_setup' );\n</code></pre>\n \n <p>Support should be added on the after_setup_theme or init action, but\n no later than that. It does not accept any further arguments.</p>\n</blockquote>\n\n<p>What this do is, let WordPress choose the page title in header, without using hardcoded tags in header.php file.</p>\n\n<p>your title will be displays as following format.</p>\n\n<p><strong><code>Page Title - Site Title</code></strong></p>\n"
}
] |
2015/02/14
|
[
"https://wordpress.stackexchange.com/questions/178155",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67531/"
] |
Normally, in WordPress, the page title appears in the content area. I'd like to have the page title appear in the header area. It looks like to do that, I'd have to remove it from its current location in the content-page.php and place it in header.php. But content-page.php is called from page.php, which calls the content-page from within a while loop (`while ( have_posts() ) : the_post(); ...` ) -- so I'd have to move or copy this into the header as well, I think. Seems like a lot of trouble.
Would it make more sense to move part of the header html into the page content, so I don't have to run the while loop more than once?
(As a learning tool, I'm re-creating an existing html site with WordPress, using the \_s starter theme.)
--- EDIT ---
Thanks for answers. Very helpful. Here are results of some testing, based on your answers. Given the following code, in header (outside Loop):
```
wp_title(): <?php wp_title('', true,''); ?><br>
the_title(): <?php the_title(); ?><br>
single_post_title(): <?php single_post_title(); ?><br>
$post->post_name: <?php echo 'page name: ' . $post->post_name; ?><br>
ispage? : <?php echo (is_page() ? 'yes' : 'no'); ?><br>
ispage(about-us) : <?php echo (is_page('about-us') ? 'yes' : 'no'); ?><br>
ispage(About Us) : <?php echo (is_page('About Us') ? 'yes' : 'no'); ?>
```
When viewed from my About Us page, I get:
```
wp_title() About UsAt The Tabernacle
the_title(): About Us
single_post_title(): About Us
$post->post_name: page name: about-us
ispage? : yes
ispage(about-us) : yes
ispage(About Us) : yes
```
When viewed from my Home page, I get:
```
wp_title(): At The Tabernacle My site motto here
the_title(): Home
single_post_title(): Home
$post->post_name: page name: home
ispage? : yes
ispage(about-us) : no
ispage(About Us) : no
```
And when viewed from a "Hello World" post, I get:
```
wp_title(): Hello world!At The Tabernacle
the_title(): Hello world!
single_post_title(): Hello world!
$post->post_name: page name: hello-world
ispage? : no
ispage(about-us) : no
ispage(About Us) : no
```
Conclusion: I can use the\_title() or single\_post\_title() (wp\_title returns more text than I want). And I can test is\_page(...) in order to display a specific page name when I'm viewing a post.
Thank you!
|
If you only need the title you can request it outside the loop easily.
*Try and call `the_title()` in your header. It should work*
But you have to be aware that if you don't put a condition, each page of your website will display its title in the header section.
EDIT: the function to call is `get_the_title($post->ID)` since `the_title()` doesn't allow you to specify the post id as an argument. You can check on the [Wordpress Codex](http://codex.wordpress.org/) for function allowing you to query information from your post outside the loop.
|
178,199 |
<p>I'm in the process of setting up WordPress over HTTPS, which is hosted on a Digital Ocean VPS, managed by Serverpilot (though the HTTPS is set up manually, rather than through Serverpilot). The server has a number of WordPress installations, but there is one in particular I wanted to run securely. WordPress in itself is running in a subfolder (so it's located in domain.com/subfolder/).</p>
<p>I've managed to get SSL certificate up and running, as going to the main URL of the site domain.com and sticking a plain HTML on it works over SSL and the padlock's show.</p>
<p>However the WordPress installation enters a redirect loop.</p>
<p>I've done the following:-</p>
<ul>
<li><p>Switched all plugins off</p></li>
<li><p>Switched to a default theme (Twenty Thirteen)</p></li>
<li><p>Updated everything to their latest versions</p></li>
<li><p>Changed to default permalinks</p></li>
</ul>
<p>I've then changed the siteurl and WordPress URL to https, and then the site gets caught in a Redirect Loop. I use a Redirect Path plugin for Chrome, and it's effectively getting redirected to itself (so <a href="https://domain.com/subfolder/" rel="nofollow">https://domain.com/subfolder/</a> goes through to <a href="https://domain.com/subfolder/" rel="nofollow">https://domain.com/subfolder/</a>). Oddly this redirect appears to switch between a 301 and 302 redirect, without any rhyme or reason.</p>
<p>I also had a bit of a play around with WordPress HTTPS, but that wasn't successful either.</p>
<p>Any ideas? Not entirely sure where to go here...</p>
|
[
{
"answer_id": 298591,
"author": "robyoder",
"author_id": 140175,
"author_profile": "https://wordpress.stackexchange.com/users/140175",
"pm_score": 3,
"selected": false,
"text": "<p>The answer to this came in part from <a href=\"/a/179420\">this answer</a>, which linked to <a href=\"https://codex.wordpress.org/Administration_Over_SSL#Using_a_Reverse_Proxy\" rel=\"noreferrer\">the Codex</a>, advising the following snippet to be placed at the top of the wp-config file:</p>\n\n<pre><code>if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)\n $_SERVER['HTTPS']='on';\n</code></pre>\n\n<p>Unfortunately, this didn't quite solve it for me, but I noticed it worked if I removed the <code>if</code> and just always set <code>$_SERVER['HTTPS']='on';</code>. If you want to always force SSL on your site, then that should do the trick.</p>\n\n<p>If you want to allow both http and https, however, you'll need to adjust your nginx config. Add the following line:</p>\n\n<pre><code>proxy_set_header X-Forwarded-Proto $scheme;\n</code></pre>\n\n<p>That's the header the <code>if</code> condition above is looking for. By setting nginx to pass the requested scheme (either http or https) along as the <code>X-Forwarded-Proto</code>, you're letting WordPress see what that original scheme was so that it knows how to behave.</p>\n\n<p>Once you've done that, your WP site should work properly over both http and https.</p>\n"
},
{
"answer_id": 390769,
"author": "TGA",
"author_id": 207982,
"author_profile": "https://wordpress.stackexchange.com/users/207982",
"pm_score": 0,
"selected": false,
"text": "<p>I had to put <code>$_SERVER['REQUEST_SCHEME']='https';</code>\nalong side <code>$_SERVER['HTTPS']='on';</code> to do the trick. Thanks.</p>\n"
}
] |
2015/02/15
|
[
"https://wordpress.stackexchange.com/questions/178199",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9918/"
] |
I'm in the process of setting up WordPress over HTTPS, which is hosted on a Digital Ocean VPS, managed by Serverpilot (though the HTTPS is set up manually, rather than through Serverpilot). The server has a number of WordPress installations, but there is one in particular I wanted to run securely. WordPress in itself is running in a subfolder (so it's located in domain.com/subfolder/).
I've managed to get SSL certificate up and running, as going to the main URL of the site domain.com and sticking a plain HTML on it works over SSL and the padlock's show.
However the WordPress installation enters a redirect loop.
I've done the following:-
* Switched all plugins off
* Switched to a default theme (Twenty Thirteen)
* Updated everything to their latest versions
* Changed to default permalinks
I've then changed the siteurl and WordPress URL to https, and then the site gets caught in a Redirect Loop. I use a Redirect Path plugin for Chrome, and it's effectively getting redirected to itself (so <https://domain.com/subfolder/> goes through to <https://domain.com/subfolder/>). Oddly this redirect appears to switch between a 301 and 302 redirect, without any rhyme or reason.
I also had a bit of a play around with WordPress HTTPS, but that wasn't successful either.
Any ideas? Not entirely sure where to go here...
|
The answer to this came in part from [this answer](/a/179420), which linked to [the Codex](https://codex.wordpress.org/Administration_Over_SSL#Using_a_Reverse_Proxy), advising the following snippet to be placed at the top of the wp-config file:
```
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
$_SERVER['HTTPS']='on';
```
Unfortunately, this didn't quite solve it for me, but I noticed it worked if I removed the `if` and just always set `$_SERVER['HTTPS']='on';`. If you want to always force SSL on your site, then that should do the trick.
If you want to allow both http and https, however, you'll need to adjust your nginx config. Add the following line:
```
proxy_set_header X-Forwarded-Proto $scheme;
```
That's the header the `if` condition above is looking for. By setting nginx to pass the requested scheme (either http or https) along as the `X-Forwarded-Proto`, you're letting WordPress see what that original scheme was so that it knows how to behave.
Once you've done that, your WP site should work properly over both http and https.
|
178,222 |
<p>I'm working on looping through some books for a custom post type with advanced custom fields. One of the ACF's is a checkbox, and I'm wanting to only show the values with this one checked. The current loop I'm using is:</p>
<pre><code><?php
$args = array (
'post_type' => 'book',
'posts_per_page' => '2'
);
$thequery = new WP_Query( $args );
?>
<?php if (have_posts()) : while ( $thequery->have_posts() ) : $thequery->the_post(); ?>
<?php if( get_field('book_featured') ): ?>
<div class="sidebar-book-header">
<img src="<?php the_field( 'book_cover' ); ?>" alt="">
<a href="<?php the_field( 'buy_now_amazon' ); ?>" class="sidebar-button book-button" style="background-color: <?php the_field( 'book_color_highlight' ); ?>" target="_blank"><span>Buy<br>Now</span></a>
</div>
<p class="sidebar-book-info"><?php the_field( 'book_excerpt' ); ?> <a href="<?php the_permalink(); ?>" style="color: <?php the_field( 'book_color_highlight' ); ?>">Read More.</a></p>
<?php endif; ?>
<?php endwhile; endif; ?>
</code></pre>
<p>This displays the first value, but doesn't include a second one (there are two that I have checked). What am I doing wrong that causes the loop to only show one?</p>
|
[
{
"answer_id": 178341,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 1,
"selected": false,
"text": "<p>If you go to <a href=\"http://gravatar.com/d6b10d5767d1e29006c11e1a2c590f3c\" rel=\"nofollow\">http://gravatar.com/d6b10d5767d1e29006c11e1a2c590f3c</a> (omit the /avatar/ from path) you get <a href=\"http://gravatar.com/clojita\" rel=\"nofollow\">http://gravatar.com/clojita</a> which seems to be your gravatar account, correct?</p>\n\n<p>MD5 collision is unlikely (but maybe it's time to buy a lottery ticket :)</p>\n\n<p>Look at source fetches interesting detail — the comment in question has <code>comment-author-clark</code> class. So it's not only the gravatar that is confused.</p>\n\n<p>That class is generated in <a href=\"http://queryposts.com/function/get_comment_class/\" rel=\"nofollow\"><code>get_comment_class()</code></a> function and is coming from user retrieved via <code>$comment->user_id</code>. It's hard to guess more without hands on dumping of data, but my educated guess is that something is screwed up exotically in or around comment template.</p>\n\n<p>First thing I'd try (dumping everything aside) is switching to native theme and/or looking into differences between theme's comments implementation from original Underscores.</p>\n"
},
{
"answer_id": 353933,
"author": "nielsvdv",
"author_id": 179329,
"author_profile": "https://wordpress.stackexchange.com/users/179329",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is old post but had same issue and figured it out: user ID is of the author of the original post (article) against which the comment was written ... best to repress comment gravatars altogether, or put in a filter to lookup by email io users ....</p>\n"
}
] |
2015/02/16
|
[
"https://wordpress.stackexchange.com/questions/178222",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67589/"
] |
I'm working on looping through some books for a custom post type with advanced custom fields. One of the ACF's is a checkbox, and I'm wanting to only show the values with this one checked. The current loop I'm using is:
```
<?php
$args = array (
'post_type' => 'book',
'posts_per_page' => '2'
);
$thequery = new WP_Query( $args );
?>
<?php if (have_posts()) : while ( $thequery->have_posts() ) : $thequery->the_post(); ?>
<?php if( get_field('book_featured') ): ?>
<div class="sidebar-book-header">
<img src="<?php the_field( 'book_cover' ); ?>" alt="">
<a href="<?php the_field( 'buy_now_amazon' ); ?>" class="sidebar-button book-button" style="background-color: <?php the_field( 'book_color_highlight' ); ?>" target="_blank"><span>Buy<br>Now</span></a>
</div>
<p class="sidebar-book-info"><?php the_field( 'book_excerpt' ); ?> <a href="<?php the_permalink(); ?>" style="color: <?php the_field( 'book_color_highlight' ); ?>">Read More.</a></p>
<?php endif; ?>
<?php endwhile; endif; ?>
```
This displays the first value, but doesn't include a second one (there are two that I have checked). What am I doing wrong that causes the loop to only show one?
|
If you go to <http://gravatar.com/d6b10d5767d1e29006c11e1a2c590f3c> (omit the /avatar/ from path) you get <http://gravatar.com/clojita> which seems to be your gravatar account, correct?
MD5 collision is unlikely (but maybe it's time to buy a lottery ticket :)
Look at source fetches interesting detail — the comment in question has `comment-author-clark` class. So it's not only the gravatar that is confused.
That class is generated in [`get_comment_class()`](http://queryposts.com/function/get_comment_class/) function and is coming from user retrieved via `$comment->user_id`. It's hard to guess more without hands on dumping of data, but my educated guess is that something is screwed up exotically in or around comment template.
First thing I'd try (dumping everything aside) is switching to native theme and/or looking into differences between theme's comments implementation from original Underscores.
|
178,237 |
<p>I have a multisite WordPress project with a main site using <strong>Theme A</strong> and all 'sub'-sites using <strong>Theme B</strong>.</p>
<p>Both <strong>Theme A</strong> and <strong>Theme B</strong> are Child Themes.</p>
<p>I want to import the header file from Theme A into Theme B, so I can show that header before Theme B's header - how would I implement this header properly?</p>
<p>I need a way that ensures the styling and functions (<code>bloginfo()</code> etc) of Theme A are maintained.</p>
|
[
{
"answer_id": 178239,
"author": "David Gard",
"author_id": 10097,
"author_profile": "https://wordpress.stackexchange.com/users/10097",
"pm_score": 0,
"selected": false,
"text": "<p>You could make Theme B a <a href=\"http://codex.wordpress.org/Child_Themes\" rel=\"nofollow\"><strong>Child Theme</strong></a> of Theme A, and then create <strong>header-b.php</strong> in Theme B (as opposed to header.php), then just include that after your call to</p>\n\n<pre><code>get_header();\nrequire_once(\"header-b.php\")\n</code></pre>\n\n<p>To ensure that all of your styling is carried over from the parent, include this in your <strong>functions.php</strong> file of Theme B -</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'my_front_scripts');\nfunction my_front_scripts(){\n\n wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css');\n\n}\n</code></pre>\n\n<p>If it really is only your header style that you wish to use, it may even be worth creating that in it's own CSS file (<strong>header.css</strong>) and enqueuing that - obviously you'd need to also enqueue that in Theme A.</p>\n"
},
{
"answer_id": 178245,
"author": "David Gard",
"author_id": 10097,
"author_profile": "https://wordpress.stackexchange.com/users/10097",
"pm_score": 2,
"selected": true,
"text": "<p>As you have now stated that both Theme A and Theme B are already Child Themes, perhaps you could try adding this to your <strong>funcions.php</strong> file in Theme B -</p>\n<pre><code>add_action('wp_enqueue_scripts', 'enqueue_front_scripts');\nfunction enqueue_front_scripts(){\n\n /** Switch to the parent blog */\n switch_to_blog(1); // You may need to change the ID, I don't know what ID you main site has\n \n /** Grab the path of the parents 'header.php' file */\n $main_header_style_path = get_stylesheet_directory_uri() . '/header.css';\n\n /** Restore the current blog */\n restore_current_blog();\n \n /** Enqueue the main header styling */\n wp_enqueue_style('main-header', $main_header_style_path);\n \n}\n\nfunction get_main_header(){\n\n /** Switch to the parent blog */\n switch_to_blog(1); // You may need to change the ID, I don't know what ID you main site has\n\n /** Grab the path of the parents 'header.php' file */\n $main_header_path = get_stylesheet_directory_uri() . '/header.php';\n\n /** Output the main header */\n require_once($main_header_path);\n\n /** Restore the current blog */\n restore_current_blog(); // Don't restore until after you have included the header, otherwise you 'get_blogino()', etc. calls will reference Theme B\n \n}\n</code></pre>\n<p>And then to include both headers you'd do this (note that the header file in both themes would simply be called <strong>header.php</strong>) -</p>\n<pre><code>get_main_header();\nget_header();\n</code></pre>\n<p>I suggest that you have a read of the <a href=\"http://codex.wordpress.org/Function_Reference/switch_to_blog\" rel=\"nofollow noreferrer\">Function Reference for <code>switch_to_blog()</code></a> for more information.</p>\n<h1>Update</h1>\n<p>I forgot to mention that you would also still need to seperate your header styling in to it's own <code>header.css</code> file in Theme A, and then enqueue this in both Theme A and Theme B.</p>\n<p>I have update my code example about to reflect this.</p>\n"
}
] |
2015/02/16
|
[
"https://wordpress.stackexchange.com/questions/178237",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67338/"
] |
I have a multisite WordPress project with a main site using **Theme A** and all 'sub'-sites using **Theme B**.
Both **Theme A** and **Theme B** are Child Themes.
I want to import the header file from Theme A into Theme B, so I can show that header before Theme B's header - how would I implement this header properly?
I need a way that ensures the styling and functions (`bloginfo()` etc) of Theme A are maintained.
|
As you have now stated that both Theme A and Theme B are already Child Themes, perhaps you could try adding this to your **funcions.php** file in Theme B -
```
add_action('wp_enqueue_scripts', 'enqueue_front_scripts');
function enqueue_front_scripts(){
/** Switch to the parent blog */
switch_to_blog(1); // You may need to change the ID, I don't know what ID you main site has
/** Grab the path of the parents 'header.php' file */
$main_header_style_path = get_stylesheet_directory_uri() . '/header.css';
/** Restore the current blog */
restore_current_blog();
/** Enqueue the main header styling */
wp_enqueue_style('main-header', $main_header_style_path);
}
function get_main_header(){
/** Switch to the parent blog */
switch_to_blog(1); // You may need to change the ID, I don't know what ID you main site has
/** Grab the path of the parents 'header.php' file */
$main_header_path = get_stylesheet_directory_uri() . '/header.php';
/** Output the main header */
require_once($main_header_path);
/** Restore the current blog */
restore_current_blog(); // Don't restore until after you have included the header, otherwise you 'get_blogino()', etc. calls will reference Theme B
}
```
And then to include both headers you'd do this (note that the header file in both themes would simply be called **header.php**) -
```
get_main_header();
get_header();
```
I suggest that you have a read of the [Function Reference for `switch_to_blog()`](http://codex.wordpress.org/Function_Reference/switch_to_blog) for more information.
Update
======
I forgot to mention that you would also still need to seperate your header styling in to it's own `header.css` file in Theme A, and then enqueue this in both Theme A and Theme B.
I have update my code example about to reflect this.
|
178,243 |
<p>I am looking for a way to quickly and repeatedly set up <strong>testing / debugging environment</strong> for our plugin, most probably using <strong>Vagrant</strong>. Projects like <a href="https://github.com/Varying-Vagrant-Vagrants/VVV">VVV</a> focus on a single-environment setup (or, a couple of environments like stable / trunk) while what I'm looking for is a script that would setup environments like:</p>
<ul>
<li>wp39-php52.local</li>
<li>wp40-php52.local</li>
<li>wp41-php52.local</li>
<li>wp39-php53.local</li>
<li>wp40-php53.local</li>
<li>etc. (you get the idea)</li>
</ul>
<p>Is there such thing? The closest I found is <a href="https://github.com/tierra/wp-vagrant">WordPress Vagrant Boxes</a> which at least does PHP versions but maybe there is something more complete that also adds WordPress versions to the mix. Thanks.</p>
|
[
{
"answer_id": 183846,
"author": "GastroGeek",
"author_id": 70445,
"author_profile": "https://wordpress.stackexchange.com/users/70445",
"pm_score": 0,
"selected": false,
"text": "<p>Have you looked at this?</p>\n\n<p><a href=\"https://puphpet.com\" rel=\"nofollow\">puphpet</a></p>\n\n<p>If appears to help you create config files. Looks like you can set up multiple vhosts and have it execute custom commands post-init. So you could have it set up all the folders, hosts and databases and then copy your desired versions over with associated wp-config files? A little bit of set up initially, but might work.</p>\n\n<p>I use a shell script, myself. wp-install www.domain.com</p>\n\n<p>Currently only works for one install but would not be impossible to configure it take some arguments or an additional 'config' file so set up multiple vhosts. As you mentioned Vagrant, I shall assume the above is closer to meeting your needs.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 207152,
"author": "Bryan Willis",
"author_id": 38123,
"author_profile": "https://wordpress.stackexchange.com/users/38123",
"pm_score": 0,
"selected": false,
"text": "<p>It all depends on what you're wanting to use and what type of OS you will be developing with...</p>\n\n<p>For vagrant, here's automation for setting up with VVV:\n<a href=\"https://github.com/bradp/vv\" rel=\"nofollow\">https://github.com/bradp/vv</a></p>\n\n<p>And a couple of others built on vagrant: <br>\n<a href=\"https://github.com/vagrantpress/vagrantpress\" rel=\"nofollow\">https://github.com/vagrantpress/vagrantpress</a> <br>\n<a href=\"https://github.com/tierra/wp-vagrant\" rel=\"nofollow\">https://github.com/tierra/wp-vagrant</a></p>\n\n<p>However, I suggest trying out <a href=\"https://pantheon.io/\" rel=\"nofollow\">pantheon</a>. It lets you do all of this for free and has integration with wp-cli, git, behat, etc. There are other hosted platforms that have these features such as <a href=\"https://www.appfog.com/\" rel=\"nofollow\">https://www.appfog.com/</a> and even wpengine I believe.</p>\n\n<p>It also depends though on how much you want set up from the start. If you're only looking for a quick way to set up wordpress there are tons of scripts on github like <a href=\"https://github.com/GeekPress/WP-Quick-Install\" rel=\"nofollow\">this</a> or just use wp-cli.</p>\n"
},
{
"answer_id": 209786,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 1,
"selected": false,
"text": "<p>On the WordPress side of things, <a href=\"https://github.com/ideasonpurpose/basic-wordpress-vagrant\" rel=\"nofollow\">Basic WordPress Vagrant Environment</a> is ready to work with any WordPress version (with a little help). You would still need to find a way to configure the PHP but there is a hint in <a href=\"https://github.com/ideasonpurpose/basic-wordpress-box/blob/master/ansible/roles/php/tasks/php.yml\" rel=\"nofollow\"><code>https://github.com/ideasonpurpose/basic-wordpress-box/blob/master/ansible/roles/php/tasks/php.yml</code></a>.</p>\n\n<p>To use it out of the box; Download or clone the project to <code>wplatest-php55.dev/</code> and run <code>vagrant up</code></p>\n\n<p>Installing <a href=\"https://github.com/smdahlen/vagrant-hostmanager\" rel=\"nofollow\">Vagrant Host Manager</a> will automatically link the IP to your folder <code>http://wplatest-php55.dev/</code></p>\n\n<p><strong>Generate multiple environments from WP versions via install-wp.sh</strong></p>\n\n<p>Check the archive for possible WordPress versions <a href=\"https://wordpress.org/download/release-archive/\" rel=\"nofollow\"><code>https://wordpress.org/download/release-archive/</code></a></p>\n\n<pre><code># PWD (script directory)\n# ├── common_folder\n# ├── wp39-php55.dev\n# │ └── site/common_folder\n# ├── wp42-php55.dev\n# │ └── site/common_folder\n# └── wp431-php55.dev\n# └── site/common_folder\n</code></pre>\n\n<p>Here is a script that pulls the Vagrant environment master to the bash script's directory, clones a site for each version in the array, configures the install task to use that WP version and allows you to specify a file/folder to copy to all sites before you <code>vagrant up</code>.</p>\n\n<p>Put this in a file <code>install-wp.sh</code> then run <code>chmod +x install-wp.sh</code> to make it executable. Find a folder where you want to create all these boxes and run <code>./install-wp.sh</code>. It'll generate the structure above.</p>\n\n<p>Since you want to test your plugin in all versions make a folder in the same directory as the script <code>wp-content/plugins/your-plugin</code> then run <code>install-wp.sh wp-content</code>. The file/folder is copied to each site's root which is why I suggest <code>wp-content</code>.</p>\n\n<p><strong>install-wp.sh</strong></p>\n\n<pre><code>#!/bin/bash\n#\n# Author: Jesse Graupmann @jgraup - http://www.justgooddesign.com - 2015\n#\n# Create multiple WordPress sites based on version numbers in array.\n#\n# ( OPTIONAL )\n# Copy common file/folder to all sites - Pass as parameter $1\n#\n# Each site runs in a Vagrant Environment:\n# https://github.com/ideasonpurpose/basic-wordpress-vagrant\n#\n# Best if used with:\n# https://github.com/smdahlen/vagrant-hostmanager\n#\n# PWD (script directory)\n# ├── common_folder\n# ├── wp39-php55.dev\n# │ └── site/common_folder\n# ├── wp42-php55.dev\n# │ └── site/common_folder\n# └── wp431-php55.dev\n# └── site/common_folder\n\n# WordPress Versions\nversions=( 3.9 4.2 4.3.1 )\n\n# Move to the current directory\nbase=$(pwd); cd $base\n\n# Vagrant Environment\nremote_master=\"https://github.com/ideasonpurpose/basic-wordpress-vagrant/archive/master.zip\"\nvagrant_master_zip=$base/basic-wordpress-vagrant.zip\n\n# Download Latest Environment - overwrite file for latest\nwget -v -O $vagrant_master_zip $remote_master\n\n# Loop through version #s\nfor VERSION in \"${versions[@]}\" ; do\n\nflatv=\"${VERSION//.}\"\ndirname=wp$flatv-php55.dev\n\n# Clone Environment\necho -e \"\\nCloning to: $base/$dirname\\n\"\nmkdir -p $base/$dirname\ntar -zxvf $vagrant_master_zip -C $base/$dirname --strip-components=1\n\n# WordPress Versions\n# Archives: https://wordpress.org/download/release-archive/\n# Version: https://wordpress.org/wordpress-{{ wp-version }}.tar.gz\n# Latest: https://wordpress.org/latest.tar.gz\n\n# Path to Ansible task\nyml=$(cat $base/$dirname/ansible/roles/wordpress/tasks/install.yml)\n\n### REPLACE THE ANSIBLE WP VERSION w/OUR VERSION\nwp_url_latest=\"https:\\/\\/wordpress.org\\/latest.tar.gz\"\nwp_url_version=\"https://wordpress.org/wordpress-$VERSION.tar.gz\"\n\necho \"${yml/$wp_url_latest/$wp_url_version}\" > $base/$dirname/ansible/roles/wordpress/tasks/install.yml\n\n# (OPTIONAL) Copy common file/folder to all sites!\n# pass as argument to .sh\n#\n# Example Folder:\n# Make a common wp-content folder, then run install with\n#\n# ./install-wp.sh wp-content\n#\n# Example File:\n# Make a text file, then run install with\n#\n# ./install-wp.sh my_file.txt\n#\ncommon_dest=$base/$dirname/site/\n\n# Copy Folder\nif [ -d \"$1\" ]; then\n echo \"Copying $1 --> $common\"\n # Directory must exist\n if [ -d \"$1\" ]; then\n folder_name=$(basename $1)\n mkdir -p $common_dest/$folder_name;\n fi\n cp -r $1 $common_dest\n\n# or File\nelif [ -f \"$1\" ]; then\n echo \"Copying $1 --> $common_dest\"\n file_name=$(basename $1)\n cp $1 $common_dest/$file_name\nfi\n\n## Create doc for quick glance at version number\ndest=\"$base/$dirname\"\nremotewpzip=\"https://wordpress.org/wordpress-$VERSION.tar.gz\"\ntxt=$dest/download-wp-$VERSION.txt\ntouch $txt\nprintf \"WordPress Version: $VERSION - https://wordpress.org/download/release-archive/\\n\\nDownload Zip: $remotewpzip\\n\" > $txt\n\ndone\n\n# The rest is just for show\n\necho -e \"\\nDone!\\n\\nNow just run 'vagrant up' in any of these:\\n\"\n\nfor VERSION in \"${versions[@]}\" ; do\n flatv=\"${VERSION//.}\"\n dirname=wp$flatv-php55.dev\n echo -e \"\\t\"$base/$dirname \"\\thttp://\"$dirname\ndone\n\necho -e \"\\nMore Vagrant env info @ https://github.com/ideasonpurpose/basic-wordpress-vagrant\"\necho -e \"Best if used with https://github.com/smdahlen/vagrant-hostmanager\\n\\nENJOY!\"\n</code></pre>\n\n<p><strong>Update:</strong></p>\n\n<p>It turns out the <a href=\"https://github.com/ideasonpurpose/basic-wordpress-vagrant\" rel=\"nofollow\">Basic WordPress Vagrant Environment</a> isn't really setup to handle multiple php versions but the <a href=\"https://github.com/ideasonpurpose/basic-wordpress-box\" rel=\"nofollow\">Basic Wordpress Box</a> might be if you adjust the <a href=\"https://github.com/ideasonpurpose/basic-wordpress-box/blob/master/ansible/roles/php/tasks/php.yml#L3-L21\" rel=\"nofollow\">PHP task</a>. I figured I'd leave a shell of a script that would have handled multiple php versions. </p>\n\n<pre><code>#!/bin/bash\n############################################\n#\n# PWD (script directory)\n# ├── wp39-php55.dev\n# ├── wp42-php55.dev\n# └── wp431-php55.dev\n#\n############################################\n\n# WordPress Versions\n\nversions=( 3.9 4.2 4.3.1 )\n\n# PHP Versions\n\npversions=( 5.4 5.5 5.6 )\n\n############################################\n\n# Move to the current directory\n\nbase=$(pwd); cd $base\n\n############################################\n\n# PHP Loop\nfor PVERSION in \"${pversions[@]}\" ; do\n pflatv=\"${PVERSION//.}\"\n\n echo -e \"==> PHP: $PVERSION\\n\"\n\n # WordPress loop\n for VERSION in \"${versions[@]}\" ; do\n flatv=\"${VERSION//.}\"\n\n ############################################\n dirname=wp$flatv-php$pflatv.dev \n ############################################\n\n # Environment\n echo -e \"\\t\"$base/$dirname \"\\thttp://\"$dirname \n\n mkdir -p $base/$dirname\n\n ############################################\n\n # WordPress Versions\n # Archives: https://wordpress.org/download/release-archive/\n # Version: https://wordpress.org/wordpress-{{ wp-version }}.tar.gz\n # Latest: https://wordpress.org/latest.tar.gz\n\n ############################################\n\n wp_url_latest=\"https:\\/\\/wordpress.org\\/latest.tar.gz\"\n wp_url_version=\"https://wordpress.org/wordpress-$VERSION.tar.gz\"\n\n # Download WP\n\n echo -e \"\\tDownload WP: $wp_url_version\"\n\n ############################################\n\n # PHP Packages at https://launchpad.net/~ondrej\n # You can get more information about the packages at https://deb.sury.org\n # For PHP 5.6 use: ppa:ondrej/php5-5.6\n # For PHP 5.5 use: ppa:ondrej/php5\n # For PHP 5.4 use: ppa:ondrej/php5-oldstable\n\n ############################################\n\n # Config PHP\n\n echo -e \"\\tConfigure PHP: $PVERSION\\n\"\n\n done # WordPress version\ndone # PHP version\n\nexit 1\n</code></pre>\n"
}
] |
2015/02/16
|
[
"https://wordpress.stackexchange.com/questions/178243",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12248/"
] |
I am looking for a way to quickly and repeatedly set up **testing / debugging environment** for our plugin, most probably using **Vagrant**. Projects like [VVV](https://github.com/Varying-Vagrant-Vagrants/VVV) focus on a single-environment setup (or, a couple of environments like stable / trunk) while what I'm looking for is a script that would setup environments like:
* wp39-php52.local
* wp40-php52.local
* wp41-php52.local
* wp39-php53.local
* wp40-php53.local
* etc. (you get the idea)
Is there such thing? The closest I found is [WordPress Vagrant Boxes](https://github.com/tierra/wp-vagrant) which at least does PHP versions but maybe there is something more complete that also adds WordPress versions to the mix. Thanks.
|
On the WordPress side of things, [Basic WordPress Vagrant Environment](https://github.com/ideasonpurpose/basic-wordpress-vagrant) is ready to work with any WordPress version (with a little help). You would still need to find a way to configure the PHP but there is a hint in [`https://github.com/ideasonpurpose/basic-wordpress-box/blob/master/ansible/roles/php/tasks/php.yml`](https://github.com/ideasonpurpose/basic-wordpress-box/blob/master/ansible/roles/php/tasks/php.yml).
To use it out of the box; Download or clone the project to `wplatest-php55.dev/` and run `vagrant up`
Installing [Vagrant Host Manager](https://github.com/smdahlen/vagrant-hostmanager) will automatically link the IP to your folder `http://wplatest-php55.dev/`
**Generate multiple environments from WP versions via install-wp.sh**
Check the archive for possible WordPress versions [`https://wordpress.org/download/release-archive/`](https://wordpress.org/download/release-archive/)
```
# PWD (script directory)
# ├── common_folder
# ├── wp39-php55.dev
# │ └── site/common_folder
# ├── wp42-php55.dev
# │ └── site/common_folder
# └── wp431-php55.dev
# └── site/common_folder
```
Here is a script that pulls the Vagrant environment master to the bash script's directory, clones a site for each version in the array, configures the install task to use that WP version and allows you to specify a file/folder to copy to all sites before you `vagrant up`.
Put this in a file `install-wp.sh` then run `chmod +x install-wp.sh` to make it executable. Find a folder where you want to create all these boxes and run `./install-wp.sh`. It'll generate the structure above.
Since you want to test your plugin in all versions make a folder in the same directory as the script `wp-content/plugins/your-plugin` then run `install-wp.sh wp-content`. The file/folder is copied to each site's root which is why I suggest `wp-content`.
**install-wp.sh**
```
#!/bin/bash
#
# Author: Jesse Graupmann @jgraup - http://www.justgooddesign.com - 2015
#
# Create multiple WordPress sites based on version numbers in array.
#
# ( OPTIONAL )
# Copy common file/folder to all sites - Pass as parameter $1
#
# Each site runs in a Vagrant Environment:
# https://github.com/ideasonpurpose/basic-wordpress-vagrant
#
# Best if used with:
# https://github.com/smdahlen/vagrant-hostmanager
#
# PWD (script directory)
# ├── common_folder
# ├── wp39-php55.dev
# │ └── site/common_folder
# ├── wp42-php55.dev
# │ └── site/common_folder
# └── wp431-php55.dev
# └── site/common_folder
# WordPress Versions
versions=( 3.9 4.2 4.3.1 )
# Move to the current directory
base=$(pwd); cd $base
# Vagrant Environment
remote_master="https://github.com/ideasonpurpose/basic-wordpress-vagrant/archive/master.zip"
vagrant_master_zip=$base/basic-wordpress-vagrant.zip
# Download Latest Environment - overwrite file for latest
wget -v -O $vagrant_master_zip $remote_master
# Loop through version #s
for VERSION in "${versions[@]}" ; do
flatv="${VERSION//.}"
dirname=wp$flatv-php55.dev
# Clone Environment
echo -e "\nCloning to: $base/$dirname\n"
mkdir -p $base/$dirname
tar -zxvf $vagrant_master_zip -C $base/$dirname --strip-components=1
# WordPress Versions
# Archives: https://wordpress.org/download/release-archive/
# Version: https://wordpress.org/wordpress-{{ wp-version }}.tar.gz
# Latest: https://wordpress.org/latest.tar.gz
# Path to Ansible task
yml=$(cat $base/$dirname/ansible/roles/wordpress/tasks/install.yml)
### REPLACE THE ANSIBLE WP VERSION w/OUR VERSION
wp_url_latest="https:\/\/wordpress.org\/latest.tar.gz"
wp_url_version="https://wordpress.org/wordpress-$VERSION.tar.gz"
echo "${yml/$wp_url_latest/$wp_url_version}" > $base/$dirname/ansible/roles/wordpress/tasks/install.yml
# (OPTIONAL) Copy common file/folder to all sites!
# pass as argument to .sh
#
# Example Folder:
# Make a common wp-content folder, then run install with
#
# ./install-wp.sh wp-content
#
# Example File:
# Make a text file, then run install with
#
# ./install-wp.sh my_file.txt
#
common_dest=$base/$dirname/site/
# Copy Folder
if [ -d "$1" ]; then
echo "Copying $1 --> $common"
# Directory must exist
if [ -d "$1" ]; then
folder_name=$(basename $1)
mkdir -p $common_dest/$folder_name;
fi
cp -r $1 $common_dest
# or File
elif [ -f "$1" ]; then
echo "Copying $1 --> $common_dest"
file_name=$(basename $1)
cp $1 $common_dest/$file_name
fi
## Create doc for quick glance at version number
dest="$base/$dirname"
remotewpzip="https://wordpress.org/wordpress-$VERSION.tar.gz"
txt=$dest/download-wp-$VERSION.txt
touch $txt
printf "WordPress Version: $VERSION - https://wordpress.org/download/release-archive/\n\nDownload Zip: $remotewpzip\n" > $txt
done
# The rest is just for show
echo -e "\nDone!\n\nNow just run 'vagrant up' in any of these:\n"
for VERSION in "${versions[@]}" ; do
flatv="${VERSION//.}"
dirname=wp$flatv-php55.dev
echo -e "\t"$base/$dirname "\thttp://"$dirname
done
echo -e "\nMore Vagrant env info @ https://github.com/ideasonpurpose/basic-wordpress-vagrant"
echo -e "Best if used with https://github.com/smdahlen/vagrant-hostmanager\n\nENJOY!"
```
**Update:**
It turns out the [Basic WordPress Vagrant Environment](https://github.com/ideasonpurpose/basic-wordpress-vagrant) isn't really setup to handle multiple php versions but the [Basic Wordpress Box](https://github.com/ideasonpurpose/basic-wordpress-box) might be if you adjust the [PHP task](https://github.com/ideasonpurpose/basic-wordpress-box/blob/master/ansible/roles/php/tasks/php.yml#L3-L21). I figured I'd leave a shell of a script that would have handled multiple php versions.
```
#!/bin/bash
############################################
#
# PWD (script directory)
# ├── wp39-php55.dev
# ├── wp42-php55.dev
# └── wp431-php55.dev
#
############################################
# WordPress Versions
versions=( 3.9 4.2 4.3.1 )
# PHP Versions
pversions=( 5.4 5.5 5.6 )
############################################
# Move to the current directory
base=$(pwd); cd $base
############################################
# PHP Loop
for PVERSION in "${pversions[@]}" ; do
pflatv="${PVERSION//.}"
echo -e "==> PHP: $PVERSION\n"
# WordPress loop
for VERSION in "${versions[@]}" ; do
flatv="${VERSION//.}"
############################################
dirname=wp$flatv-php$pflatv.dev
############################################
# Environment
echo -e "\t"$base/$dirname "\thttp://"$dirname
mkdir -p $base/$dirname
############################################
# WordPress Versions
# Archives: https://wordpress.org/download/release-archive/
# Version: https://wordpress.org/wordpress-{{ wp-version }}.tar.gz
# Latest: https://wordpress.org/latest.tar.gz
############################################
wp_url_latest="https:\/\/wordpress.org\/latest.tar.gz"
wp_url_version="https://wordpress.org/wordpress-$VERSION.tar.gz"
# Download WP
echo -e "\tDownload WP: $wp_url_version"
############################################
# PHP Packages at https://launchpad.net/~ondrej
# You can get more information about the packages at https://deb.sury.org
# For PHP 5.6 use: ppa:ondrej/php5-5.6
# For PHP 5.5 use: ppa:ondrej/php5
# For PHP 5.4 use: ppa:ondrej/php5-oldstable
############################################
# Config PHP
echo -e "\tConfigure PHP: $PVERSION\n"
done # WordPress version
done # PHP version
exit 1
```
|
178,256 |
<p>I am displaying results from a custom post type ("works") and want to optionally filter by a custom taxonomy ("genre") if that is set (i.e. if the loop is on the custom taxonomy archive template).</p>
<p>I am using a wp_query with arguments, but it is not filtering by the custom taxonomy slug- it's returning all results.</p>
<p>For your information, I am ordering by a custom post type and I am paginating results (not included the code for that in this example). I set the custom post type, custom fields and custom taxonomy using the Types plugin, but I am not sure if that makes a difference to this question. </p>
<p>Here is the code:</p>
<pre><code>if($wp_query->query->genre != "") {
$genre = $wp_query->query->genre;
}
if($genre != "") {
$taxArray = array(
'taxonomy' => 'genre',
'field' => 'slug',
'terms' => $genre,
);
$args = array(
'post_type' => 'works',
'posts_per_page' => 40,
'meta_key' => 'wpcf-composition-date',
'orderby' => 'wpcf-composition-date',
'order' => "DESC",
'offset' => $offset,
'tax_query' => $taxArray
);
$loop = new wp_query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
?>
<?php get_template_part('templates/content-works', get_post_format()); ?>
<?php endwhile; ?>
</code></pre>
<p>Just to clarify, here is the output of <code>$args</code> from the page that uses the above code:</p>
<pre><code>Array
(
[post_type] => works
[posts_per_page] => 40
[meta_key] => wpcf-composition-date
[orderby] => wpcf-composition-date
[order] => DESC
[offset] => 0
[tax_query] => Array
(
[taxonomy] => genre
[field] => slug
[terms] => Array
(
orchestral
)
)
)
</code></pre>
<p>As I said, the above code lists all results from all custom taxonomies.</p>
<p>Is there an error in my code? What am I doing wrong? How can I display results filtered by the custom taxonomy slug?</p>
<p><strong>Update...</strong>
Just looked at the request and it seems the tax_query isn't being added to the query:</p>
<pre><code>SELECT SQL_CALC_FOUND_ROWS testweb_posts.ID FROM testweb_posts INNER JOIN testweb_postmeta ON ( testweb_posts.ID = testweb_postmeta.post_id ) WHERE 1=1 AND testweb_posts.post_type = 'works' AND (testweb_posts.post_status = 'publish' OR testweb_posts.post_status = 'private') AND (
testweb_postmeta.meta_key = 'wpcf-composition-date'
) GROUP BY testweb_posts.ID ORDER BY testweb_posts.post_title ASC LIMIT 0, 40
</code></pre>
|
[
{
"answer_id": 178266,
"author": "cristian.raiber",
"author_id": 52524,
"author_profile": "https://wordpress.stackexchange.com/users/52524",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$args = array( \n 'post_type' => 'works', \n 'posts_per_page' => 40, \n 'meta_key' => 'wpcf-composition-date', \n 'orderby' => 'wpcf-composition-date', \n 'order' => \"DESC\",\n 'offset' => $offset,\n 'tax_query' => array(\n 'taxonomy' => 'genre',\n 'field' => 'slug',\n 'terms' => array('orchestral'),\n );\n);\n</code></pre>\n\n<p>Could you please try this code for the sake of testing purposes ? Let me know what this query returns.</p>\n"
},
{
"answer_id": 178299,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>As I stated in comments, use <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code></a> to alter the main query. Never replace the main query with a custom one. Again, from comments</p>\n\n<blockquote>\n <p>Just for starters, on each page load you are running the same query twice, it is slow, double the amount of db calls and pagination has to be tweaked to work almost 100 percent, this just to get the same posts :-)</p>\n</blockquote>\n\n<p>You can also check out <a href=\"https://wordpress.stackexchange.com/a/155976/31545\">this post</a> I have done on the subject</p>\n\n<p>To make the transition is quite easy, easier than you think. Here is how</p>\n\n<ul>\n<li><p>Create a <code>taxonomy.php</code> template</p></li>\n<li><p>Add the following in there (I have added php tags to make space for your HTML mark up)</p>\n\n<pre><code><?php\n while ( have_posts() ) { \n the_post();\n?>\n <?php get_template_part('templates/content-works', get_post_format()); ?>\n<?php\n }\n?>\n</code></pre></li>\n<li><p>Now, you have to move your conditions to <code>functions.php</code> inside <code>pre_get_posts</code> (<em>Requires PHP 5.3+</em>)</p>\n\n<pre><code>add_action('pre_get_posts', function ($q) \n{\n if(!is_admin() && $q->is_main_query() && $q->is_tax()) {\n\n $q->set('post_type', 'works'); \n $q->set('posts_per_page', 40); \n $q->set('meta_key', 'wpcf-composition-date'); \n $q->set('orderby', 'wpcf-composition-date'); \n $q->set('order', 'DESC'); \n\n }\n\n return $q;\n}\n</code></pre></li>\n</ul>\n\n<p>This should be enough to make things work</p>\n"
}
] |
2015/02/16
|
[
"https://wordpress.stackexchange.com/questions/178256",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/5864/"
] |
I am displaying results from a custom post type ("works") and want to optionally filter by a custom taxonomy ("genre") if that is set (i.e. if the loop is on the custom taxonomy archive template).
I am using a wp\_query with arguments, but it is not filtering by the custom taxonomy slug- it's returning all results.
For your information, I am ordering by a custom post type and I am paginating results (not included the code for that in this example). I set the custom post type, custom fields and custom taxonomy using the Types plugin, but I am not sure if that makes a difference to this question.
Here is the code:
```
if($wp_query->query->genre != "") {
$genre = $wp_query->query->genre;
}
if($genre != "") {
$taxArray = array(
'taxonomy' => 'genre',
'field' => 'slug',
'terms' => $genre,
);
$args = array(
'post_type' => 'works',
'posts_per_page' => 40,
'meta_key' => 'wpcf-composition-date',
'orderby' => 'wpcf-composition-date',
'order' => "DESC",
'offset' => $offset,
'tax_query' => $taxArray
);
$loop = new wp_query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
?>
<?php get_template_part('templates/content-works', get_post_format()); ?>
<?php endwhile; ?>
```
Just to clarify, here is the output of `$args` from the page that uses the above code:
```
Array
(
[post_type] => works
[posts_per_page] => 40
[meta_key] => wpcf-composition-date
[orderby] => wpcf-composition-date
[order] => DESC
[offset] => 0
[tax_query] => Array
(
[taxonomy] => genre
[field] => slug
[terms] => Array
(
orchestral
)
)
)
```
As I said, the above code lists all results from all custom taxonomies.
Is there an error in my code? What am I doing wrong? How can I display results filtered by the custom taxonomy slug?
**Update...**
Just looked at the request and it seems the tax\_query isn't being added to the query:
```
SELECT SQL_CALC_FOUND_ROWS testweb_posts.ID FROM testweb_posts INNER JOIN testweb_postmeta ON ( testweb_posts.ID = testweb_postmeta.post_id ) WHERE 1=1 AND testweb_posts.post_type = 'works' AND (testweb_posts.post_status = 'publish' OR testweb_posts.post_status = 'private') AND (
testweb_postmeta.meta_key = 'wpcf-composition-date'
) GROUP BY testweb_posts.ID ORDER BY testweb_posts.post_title ASC LIMIT 0, 40
```
|
As I stated in comments, use [`pre_get_posts`](http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) to alter the main query. Never replace the main query with a custom one. Again, from comments
>
> Just for starters, on each page load you are running the same query twice, it is slow, double the amount of db calls and pagination has to be tweaked to work almost 100 percent, this just to get the same posts :-)
>
>
>
You can also check out [this post](https://wordpress.stackexchange.com/a/155976/31545) I have done on the subject
To make the transition is quite easy, easier than you think. Here is how
* Create a `taxonomy.php` template
* Add the following in there (I have added php tags to make space for your HTML mark up)
```
<?php
while ( have_posts() ) {
the_post();
?>
<?php get_template_part('templates/content-works', get_post_format()); ?>
<?php
}
?>
```
* Now, you have to move your conditions to `functions.php` inside `pre_get_posts` (*Requires PHP 5.3+*)
```
add_action('pre_get_posts', function ($q)
{
if(!is_admin() && $q->is_main_query() && $q->is_tax()) {
$q->set('post_type', 'works');
$q->set('posts_per_page', 40);
$q->set('meta_key', 'wpcf-composition-date');
$q->set('orderby', 'wpcf-composition-date');
$q->set('order', 'DESC');
}
return $q;
}
```
This should be enough to make things work
|
178,287 |
<p>In my <code>functions.php</code> I would like to enqueue a CSS file conditional on whether a custom field exists on the page or custom post type. How should I go about this?</p>
<pre><code> function flatsome_scripts()
{
wp_enqueue_style( 'flatsome-icons', get_template_directory_uri() .'/flatme/css/fonts.css', array(), '2.1', 'all' );
}
add_action( 'wp_enqueue_scripts', 'flatsome_scripts' );
</code></pre>
<p>Note that I don't want an answer which is part of the loop. The code should reside in <code>functions.php</code></p>
|
[
{
"answer_id": 178266,
"author": "cristian.raiber",
"author_id": 52524,
"author_profile": "https://wordpress.stackexchange.com/users/52524",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$args = array( \n 'post_type' => 'works', \n 'posts_per_page' => 40, \n 'meta_key' => 'wpcf-composition-date', \n 'orderby' => 'wpcf-composition-date', \n 'order' => \"DESC\",\n 'offset' => $offset,\n 'tax_query' => array(\n 'taxonomy' => 'genre',\n 'field' => 'slug',\n 'terms' => array('orchestral'),\n );\n);\n</code></pre>\n\n<p>Could you please try this code for the sake of testing purposes ? Let me know what this query returns.</p>\n"
},
{
"answer_id": 178299,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>As I stated in comments, use <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code></a> to alter the main query. Never replace the main query with a custom one. Again, from comments</p>\n\n<blockquote>\n <p>Just for starters, on each page load you are running the same query twice, it is slow, double the amount of db calls and pagination has to be tweaked to work almost 100 percent, this just to get the same posts :-)</p>\n</blockquote>\n\n<p>You can also check out <a href=\"https://wordpress.stackexchange.com/a/155976/31545\">this post</a> I have done on the subject</p>\n\n<p>To make the transition is quite easy, easier than you think. Here is how</p>\n\n<ul>\n<li><p>Create a <code>taxonomy.php</code> template</p></li>\n<li><p>Add the following in there (I have added php tags to make space for your HTML mark up)</p>\n\n<pre><code><?php\n while ( have_posts() ) { \n the_post();\n?>\n <?php get_template_part('templates/content-works', get_post_format()); ?>\n<?php\n }\n?>\n</code></pre></li>\n<li><p>Now, you have to move your conditions to <code>functions.php</code> inside <code>pre_get_posts</code> (<em>Requires PHP 5.3+</em>)</p>\n\n<pre><code>add_action('pre_get_posts', function ($q) \n{\n if(!is_admin() && $q->is_main_query() && $q->is_tax()) {\n\n $q->set('post_type', 'works'); \n $q->set('posts_per_page', 40); \n $q->set('meta_key', 'wpcf-composition-date'); \n $q->set('orderby', 'wpcf-composition-date'); \n $q->set('order', 'DESC'); \n\n }\n\n return $q;\n}\n</code></pre></li>\n</ul>\n\n<p>This should be enough to make things work</p>\n"
}
] |
2015/02/16
|
[
"https://wordpress.stackexchange.com/questions/178287",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40727/"
] |
In my `functions.php` I would like to enqueue a CSS file conditional on whether a custom field exists on the page or custom post type. How should I go about this?
```
function flatsome_scripts()
{
wp_enqueue_style( 'flatsome-icons', get_template_directory_uri() .'/flatme/css/fonts.css', array(), '2.1', 'all' );
}
add_action( 'wp_enqueue_scripts', 'flatsome_scripts' );
```
Note that I don't want an answer which is part of the loop. The code should reside in `functions.php`
|
As I stated in comments, use [`pre_get_posts`](http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) to alter the main query. Never replace the main query with a custom one. Again, from comments
>
> Just for starters, on each page load you are running the same query twice, it is slow, double the amount of db calls and pagination has to be tweaked to work almost 100 percent, this just to get the same posts :-)
>
>
>
You can also check out [this post](https://wordpress.stackexchange.com/a/155976/31545) I have done on the subject
To make the transition is quite easy, easier than you think. Here is how
* Create a `taxonomy.php` template
* Add the following in there (I have added php tags to make space for your HTML mark up)
```
<?php
while ( have_posts() ) {
the_post();
?>
<?php get_template_part('templates/content-works', get_post_format()); ?>
<?php
}
?>
```
* Now, you have to move your conditions to `functions.php` inside `pre_get_posts` (*Requires PHP 5.3+*)
```
add_action('pre_get_posts', function ($q)
{
if(!is_admin() && $q->is_main_query() && $q->is_tax()) {
$q->set('post_type', 'works');
$q->set('posts_per_page', 40);
$q->set('meta_key', 'wpcf-composition-date');
$q->set('orderby', 'wpcf-composition-date');
$q->set('order', 'DESC');
}
return $q;
}
```
This should be enough to make things work
|
178,294 |
<p>A few words in the WP Job Manager weren't translated yet. I edited most of them in de po file now but for the sentence "posted 5 hours ago" I can't find where to translate the "Hours" </p>
<p>It's declared as <code>%s</code> in the po file, Cant find the word hour in any of the plugin's files... </p>
<p>so where to change the "hours" term of this plugin.</p>
<pre><code>#: templates/content-job_listing.php (Line 18)
msgid "%s ago"
msgstr "%s geleden"
// Content-job_listing.php
<li class="date">
<date>
<?php printf(
__( '%s ago', 'wp-job-manager' ),
human_time_diff( get_post_time( 'U' ), current_time( 'timestamp' ) )
); ?>
</date>
</li>
</code></pre>
|
[
{
"answer_id": 178296,
"author": "cristian.raiber",
"author_id": 52524,
"author_profile": "https://wordpress.stackexchange.com/users/52524",
"pm_score": -1,
"selected": true,
"text": "<p>Since your problem resolves around the fact that the WP theme developers used a function that doesn't have any hooks so we could easily alter the output, you're going to have to copy & paste the following code in your functions.php file</p>\n\n<pre><code>function human_time_diff( $from, $to = '' ) {\n if ( empty( $to ) ) {\n $to = time();\n }\n\n $diff = (int) abs( $to - $from );\n\n if ( $diff < HOUR_IN_SECONDS ) {\n $mins = round( $diff / MINUTE_IN_SECONDS );\n if ( $mins <= 1 )\n $mins = 1;\n /* translators: min=minute */\n $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );\n } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {\n $hours = round( $diff / HOUR_IN_SECONDS );\n if ( $hours <= 1 )\n $hours = 1;\n $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );\n } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {\n $days = round( $diff / DAY_IN_SECONDS );\n if ( $days <= 1 )\n $days = 1;\n $since = sprintf( _n( '%s day', '%s days', $days ), $days );\n } elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {\n $weeks = round( $diff / WEEK_IN_SECONDS );\n if ( $weeks <= 1 )\n $weeks = 1;\n $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );\n } elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {\n $months = round( $diff / ( 30 * DAY_IN_SECONDS ) );\n if ( $months <= 1 )\n $months = 1;\n $since = sprintf( _n( '%s month', '%s months', $months ), $months );\n } elseif ( $diff >= YEAR_IN_SECONDS ) {\n $years = round( $diff / YEAR_IN_SECONDS );\n if ( $years <= 1 )\n $years = 1;\n $since = sprintf( _n( '%s year', '%s years', $years ), $years );\n }\n\n /**\n * Filter the human readable difference between two timestamps.\n *\n * @since 4.0.0\n *\n * @param string $since The difference in human readable text.\n * @param int $diff The difference in seconds.\n * @param int $from Unix timestamp from which the difference begins.\n * @param int $to Unix timestamp to end the time difference.\n */\n return apply_filters( 'human_time_diff', $since, $diff, $from, $to );\n}\n</code></pre>\n\n<blockquote>\n <p>'%s min', '%s mins'</p>\n \n <p>'%s hour', '%s hours' </p>\n \n <p>'%s day', '%s days'</p>\n \n <p>'%s week', '%s weeks'</p>\n \n <p>'%s month', '%s months'</p>\n</blockquote>\n\n<p>These are the formats you need to change with your own wording; be sure to only change the words (minute, hour, day, week, month) and not the <code>%s</code></p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 178307,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": false,
"text": "<p>I think you need to understand how the code you are using works. The code that output the string is:</p>\n\n<pre><code><?php printf( __( '%s ago', 'wp-job-manager' ), human_time_diff( get_post_time( 'U' ), current_time( 'timestamp' ) ) ); ?>\n</code></pre>\n\n<p>In the above code, <code>__( '%s ago', 'wp-job-manager' )</code> is translated by wp-job-manager language files and <code>%s</code> is replaced by the output of <code>human_time_diff()</code> function, which is in the format \"1 day\", \"2 months\", etc. The output of <code>human_time_diff()</code> is already translated by WordPress language files and, additionally, the output can be filtered. So, you have two options: 1) modify the output of <code>human_time_diff()</code> function using <code>human_time_diff</code> filter or 2) override the translations from core ussing <code>gettext</code> filter.</p>\n\n<p>1.- <strong>Using <code>human_time_diff</code> filter</strong>. Example:</p>\n\n<pre><code>add_filter( 'human_time_diff', function($since, $diff, $from, $to) {\n\n //Here you can build your own human time diff strings\n //For example\n if ( empty( $to ) ) {\n $to = time();\n }\n\n $diff = (int) abs( $to - $from );\n\n if ( $diff < HOUR_IN_SECONDS ) {\n $since = \"WOW, a lot of time ago!!!!\";\n }\n\n return $since;\n\n}, 10, 4 );\n</code></pre>\n\n<p>2.- <strong>Override the translations</strong> using <code>gettext</code> filter. For example:</p>\n\n<pre><code>add_filter( 'gettext', function($translated, $original, $domain) {\n\n if ( $original == \"%s hour\" ) {\n //fill $translated string with whatever you want\n $translated = \"Some other string you want instead of original translattion\";\n }\n return $translated;\n\n}, 10, 3 );\n</code></pre>\n"
}
] |
2015/02/16
|
[
"https://wordpress.stackexchange.com/questions/178294",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67623/"
] |
A few words in the WP Job Manager weren't translated yet. I edited most of them in de po file now but for the sentence "posted 5 hours ago" I can't find where to translate the "Hours"
It's declared as `%s` in the po file, Cant find the word hour in any of the plugin's files...
so where to change the "hours" term of this plugin.
```
#: templates/content-job_listing.php (Line 18)
msgid "%s ago"
msgstr "%s geleden"
// Content-job_listing.php
<li class="date">
<date>
<?php printf(
__( '%s ago', 'wp-job-manager' ),
human_time_diff( get_post_time( 'U' ), current_time( 'timestamp' ) )
); ?>
</date>
</li>
```
|
Since your problem resolves around the fact that the WP theme developers used a function that doesn't have any hooks so we could easily alter the output, you're going to have to copy & paste the following code in your functions.php file
```
function human_time_diff( $from, $to = '' ) {
if ( empty( $to ) ) {
$to = time();
}
$diff = (int) abs( $to - $from );
if ( $diff < HOUR_IN_SECONDS ) {
$mins = round( $diff / MINUTE_IN_SECONDS );
if ( $mins <= 1 )
$mins = 1;
/* translators: min=minute */
$since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
} elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
$hours = round( $diff / HOUR_IN_SECONDS );
if ( $hours <= 1 )
$hours = 1;
$since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
} elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
$days = round( $diff / DAY_IN_SECONDS );
if ( $days <= 1 )
$days = 1;
$since = sprintf( _n( '%s day', '%s days', $days ), $days );
} elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
$weeks = round( $diff / WEEK_IN_SECONDS );
if ( $weeks <= 1 )
$weeks = 1;
$since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
} elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {
$months = round( $diff / ( 30 * DAY_IN_SECONDS ) );
if ( $months <= 1 )
$months = 1;
$since = sprintf( _n( '%s month', '%s months', $months ), $months );
} elseif ( $diff >= YEAR_IN_SECONDS ) {
$years = round( $diff / YEAR_IN_SECONDS );
if ( $years <= 1 )
$years = 1;
$since = sprintf( _n( '%s year', '%s years', $years ), $years );
}
/**
* Filter the human readable difference between two timestamps.
*
* @since 4.0.0
*
* @param string $since The difference in human readable text.
* @param int $diff The difference in seconds.
* @param int $from Unix timestamp from which the difference begins.
* @param int $to Unix timestamp to end the time difference.
*/
return apply_filters( 'human_time_diff', $since, $diff, $from, $to );
}
```
>
> '%s min', '%s mins'
>
>
> '%s hour', '%s hours'
>
>
> '%s day', '%s days'
>
>
> '%s week', '%s weeks'
>
>
> '%s month', '%s months'
>
>
>
These are the formats you need to change with your own wording; be sure to only change the words (minute, hour, day, week, month) and not the `%s`
Hope this helps.
|
178,297 |
<p>My theme uses Magnific Popup as follows in <code>theme.js</code></p>
<pre><code> /* add lightbox for blog galleries */
$(".gallery a[href$='.jpg'],.gallery a[href$='.jpeg'],.featured-item a[href$='.jpeg'],.featured-item a[href$='.gif'],.featured-item a[href$='.jpg'], .page-featured-item .slider a[href$='.jpg'], .page-featured-item a[href$='.jpg'],.page-featured-item .slider a[href$='.jpeg'], .page-featured-item a[href$='.jpeg'], .gallery a[href$='.png'], .gallery a[href$='.jpeg'], .gallery a[href$='.gif']").parent().magnificPopup({
delegate: 'a',
type: 'image',
tLoading: '<div class="loading dark"><i></i><i></i><i></i><i></i></div>',
mainClass: 'my-mfp-zoom-in',
gallery: {
enabled: true,
navigateByImgClick: true,
preload: [0,1] // Will preload 0 - before current, and 1 after the current image
},
image: {
tError: '<a href="%url%">The image #%curr%</a> could not be loaded.',
verticalFit: false
}
});
</code></pre>
<p>I would like to modify this to add the caption of each image in the Wordpress Gallery. I know I should be using the selector.</p>
<pre><code>image: {
titleSrc:
}
</code></pre>
<p>Also I don't want to edit this code directly as it's part of a theme. Could I use a function or perhaps the footer to append my changes?</p>
|
[
{
"answer_id": 178296,
"author": "cristian.raiber",
"author_id": 52524,
"author_profile": "https://wordpress.stackexchange.com/users/52524",
"pm_score": -1,
"selected": true,
"text": "<p>Since your problem resolves around the fact that the WP theme developers used a function that doesn't have any hooks so we could easily alter the output, you're going to have to copy & paste the following code in your functions.php file</p>\n\n<pre><code>function human_time_diff( $from, $to = '' ) {\n if ( empty( $to ) ) {\n $to = time();\n }\n\n $diff = (int) abs( $to - $from );\n\n if ( $diff < HOUR_IN_SECONDS ) {\n $mins = round( $diff / MINUTE_IN_SECONDS );\n if ( $mins <= 1 )\n $mins = 1;\n /* translators: min=minute */\n $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );\n } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {\n $hours = round( $diff / HOUR_IN_SECONDS );\n if ( $hours <= 1 )\n $hours = 1;\n $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );\n } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {\n $days = round( $diff / DAY_IN_SECONDS );\n if ( $days <= 1 )\n $days = 1;\n $since = sprintf( _n( '%s day', '%s days', $days ), $days );\n } elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {\n $weeks = round( $diff / WEEK_IN_SECONDS );\n if ( $weeks <= 1 )\n $weeks = 1;\n $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );\n } elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {\n $months = round( $diff / ( 30 * DAY_IN_SECONDS ) );\n if ( $months <= 1 )\n $months = 1;\n $since = sprintf( _n( '%s month', '%s months', $months ), $months );\n } elseif ( $diff >= YEAR_IN_SECONDS ) {\n $years = round( $diff / YEAR_IN_SECONDS );\n if ( $years <= 1 )\n $years = 1;\n $since = sprintf( _n( '%s year', '%s years', $years ), $years );\n }\n\n /**\n * Filter the human readable difference between two timestamps.\n *\n * @since 4.0.0\n *\n * @param string $since The difference in human readable text.\n * @param int $diff The difference in seconds.\n * @param int $from Unix timestamp from which the difference begins.\n * @param int $to Unix timestamp to end the time difference.\n */\n return apply_filters( 'human_time_diff', $since, $diff, $from, $to );\n}\n</code></pre>\n\n<blockquote>\n <p>'%s min', '%s mins'</p>\n \n <p>'%s hour', '%s hours' </p>\n \n <p>'%s day', '%s days'</p>\n \n <p>'%s week', '%s weeks'</p>\n \n <p>'%s month', '%s months'</p>\n</blockquote>\n\n<p>These are the formats you need to change with your own wording; be sure to only change the words (minute, hour, day, week, month) and not the <code>%s</code></p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 178307,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": false,
"text": "<p>I think you need to understand how the code you are using works. The code that output the string is:</p>\n\n<pre><code><?php printf( __( '%s ago', 'wp-job-manager' ), human_time_diff( get_post_time( 'U' ), current_time( 'timestamp' ) ) ); ?>\n</code></pre>\n\n<p>In the above code, <code>__( '%s ago', 'wp-job-manager' )</code> is translated by wp-job-manager language files and <code>%s</code> is replaced by the output of <code>human_time_diff()</code> function, which is in the format \"1 day\", \"2 months\", etc. The output of <code>human_time_diff()</code> is already translated by WordPress language files and, additionally, the output can be filtered. So, you have two options: 1) modify the output of <code>human_time_diff()</code> function using <code>human_time_diff</code> filter or 2) override the translations from core ussing <code>gettext</code> filter.</p>\n\n<p>1.- <strong>Using <code>human_time_diff</code> filter</strong>. Example:</p>\n\n<pre><code>add_filter( 'human_time_diff', function($since, $diff, $from, $to) {\n\n //Here you can build your own human time diff strings\n //For example\n if ( empty( $to ) ) {\n $to = time();\n }\n\n $diff = (int) abs( $to - $from );\n\n if ( $diff < HOUR_IN_SECONDS ) {\n $since = \"WOW, a lot of time ago!!!!\";\n }\n\n return $since;\n\n}, 10, 4 );\n</code></pre>\n\n<p>2.- <strong>Override the translations</strong> using <code>gettext</code> filter. For example:</p>\n\n<pre><code>add_filter( 'gettext', function($translated, $original, $domain) {\n\n if ( $original == \"%s hour\" ) {\n //fill $translated string with whatever you want\n $translated = \"Some other string you want instead of original translattion\";\n }\n return $translated;\n\n}, 10, 3 );\n</code></pre>\n"
}
] |
2015/02/16
|
[
"https://wordpress.stackexchange.com/questions/178297",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40727/"
] |
My theme uses Magnific Popup as follows in `theme.js`
```
/* add lightbox for blog galleries */
$(".gallery a[href$='.jpg'],.gallery a[href$='.jpeg'],.featured-item a[href$='.jpeg'],.featured-item a[href$='.gif'],.featured-item a[href$='.jpg'], .page-featured-item .slider a[href$='.jpg'], .page-featured-item a[href$='.jpg'],.page-featured-item .slider a[href$='.jpeg'], .page-featured-item a[href$='.jpeg'], .gallery a[href$='.png'], .gallery a[href$='.jpeg'], .gallery a[href$='.gif']").parent().magnificPopup({
delegate: 'a',
type: 'image',
tLoading: '<div class="loading dark"><i></i><i></i><i></i><i></i></div>',
mainClass: 'my-mfp-zoom-in',
gallery: {
enabled: true,
navigateByImgClick: true,
preload: [0,1] // Will preload 0 - before current, and 1 after the current image
},
image: {
tError: '<a href="%url%">The image #%curr%</a> could not be loaded.',
verticalFit: false
}
});
```
I would like to modify this to add the caption of each image in the Wordpress Gallery. I know I should be using the selector.
```
image: {
titleSrc:
}
```
Also I don't want to edit this code directly as it's part of a theme. Could I use a function or perhaps the footer to append my changes?
|
Since your problem resolves around the fact that the WP theme developers used a function that doesn't have any hooks so we could easily alter the output, you're going to have to copy & paste the following code in your functions.php file
```
function human_time_diff( $from, $to = '' ) {
if ( empty( $to ) ) {
$to = time();
}
$diff = (int) abs( $to - $from );
if ( $diff < HOUR_IN_SECONDS ) {
$mins = round( $diff / MINUTE_IN_SECONDS );
if ( $mins <= 1 )
$mins = 1;
/* translators: min=minute */
$since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
} elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
$hours = round( $diff / HOUR_IN_SECONDS );
if ( $hours <= 1 )
$hours = 1;
$since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
} elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
$days = round( $diff / DAY_IN_SECONDS );
if ( $days <= 1 )
$days = 1;
$since = sprintf( _n( '%s day', '%s days', $days ), $days );
} elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
$weeks = round( $diff / WEEK_IN_SECONDS );
if ( $weeks <= 1 )
$weeks = 1;
$since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
} elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {
$months = round( $diff / ( 30 * DAY_IN_SECONDS ) );
if ( $months <= 1 )
$months = 1;
$since = sprintf( _n( '%s month', '%s months', $months ), $months );
} elseif ( $diff >= YEAR_IN_SECONDS ) {
$years = round( $diff / YEAR_IN_SECONDS );
if ( $years <= 1 )
$years = 1;
$since = sprintf( _n( '%s year', '%s years', $years ), $years );
}
/**
* Filter the human readable difference between two timestamps.
*
* @since 4.0.0
*
* @param string $since The difference in human readable text.
* @param int $diff The difference in seconds.
* @param int $from Unix timestamp from which the difference begins.
* @param int $to Unix timestamp to end the time difference.
*/
return apply_filters( 'human_time_diff', $since, $diff, $from, $to );
}
```
>
> '%s min', '%s mins'
>
>
> '%s hour', '%s hours'
>
>
> '%s day', '%s days'
>
>
> '%s week', '%s weeks'
>
>
> '%s month', '%s months'
>
>
>
These are the formats you need to change with your own wording; be sure to only change the words (minute, hour, day, week, month) and not the `%s`
Hope this helps.
|
178,302 |
<p>I need to find posts with a meta key that starts with the current year + the current month (i.e. 201502), but the actual value could also contain any day within that month (i.e. 20150214). </p>
<p>The really tricky part is that I'm trying to do this with ACF's Reapter and Date Picker fields. I've got it working to where it can return true if the I ask for posts containing a full date string (20150214), but I can't figure out how to do it for just the year and month.</p>
<p>Here's my current code:</p>
<pre><code>// custom filter to replace '=' with 'LIKE'
function my_posts_where($where) {
$where = str_replace("meta_key = 'show_times_%_date'", "meta_key LIKE 'show_times_%_date'", $where);
return $where;
}
add_filter("posts_where", "my_posts_where");
// get results
$this_month = date("Ym") . "14"; // this doesn't work if I remove the . "14"
$the_query = new WP_Query(array(
"numberposts" => -1,
"post_type" => "plays_events",
"meta_query" => array(
array(
"key" => "show_times_%_date",
"value" => $this_month,
)
),
));
</code></pre>
<p>I'm really confused by the <code>my_posts_where</code> but, I just copied and modified it from <a href="http://www.advancedcustomfields.com/resources/how-to-query-posts-filtered-by-custom-field-values/#example-5" rel="nofollow">this page</a>.</p>
<p>Essentially it's the "value" option that I need to figure out how to say <code>$this_month . $any_day</code>.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 178304,
"author": "David Gard",
"author_id": 10097,
"author_profile": "https://wordpress.stackexchange.com/users/10097",
"pm_score": 0,
"selected": false,
"text": "<p>I believe all you need to do here is remove the day from your <code>$this_month</code> parameter and use the <code>LIKE</code> comparison (with a trailing <code>%</code>) to query the value -</p>\n\n<pre><code>$this_month = date(\"Ym\");\n$the_query = new WP_Query(array(\n \"numberposts\" => -1,\n \"post_type\" => \"plays_events\",\n \"meta_query\" => array(\n array(\n \"key\" => \"show_times_%_date\",\n \"value\" => $this_month . \"%\",\n \"compare\" => \"LIKE\"\n )\n ),\n));\n</code></pre>\n\n<p>Check out the <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow\">Custom Field Parameters section in the Class Reference for <code>WP_Query</code></a></p>\n"
},
{
"answer_id": 178306,
"author": "JacobTheDev",
"author_id": 24566,
"author_profile": "https://wordpress.stackexchange.com/users/24566",
"pm_score": 2,
"selected": true,
"text": "<p>I figured it out:</p>\n\n<pre><code>$the_query = new WP_Query(array(\n \"numberposts\" => -1,\n \"post_type\" => \"plays_events\",\n \"meta_query\" => array(\n array(\n \"key\" => \"show_times_%_date\",\n \"value\" => $this_month . \"[0-9]{2}\",\n \"compare\" => \"REGEXP\"\n )\n ),\n));\n</code></pre>\n"
}
] |
2015/02/16
|
[
"https://wordpress.stackexchange.com/questions/178302",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24566/"
] |
I need to find posts with a meta key that starts with the current year + the current month (i.e. 201502), but the actual value could also contain any day within that month (i.e. 20150214).
The really tricky part is that I'm trying to do this with ACF's Reapter and Date Picker fields. I've got it working to where it can return true if the I ask for posts containing a full date string (20150214), but I can't figure out how to do it for just the year and month.
Here's my current code:
```
// custom filter to replace '=' with 'LIKE'
function my_posts_where($where) {
$where = str_replace("meta_key = 'show_times_%_date'", "meta_key LIKE 'show_times_%_date'", $where);
return $where;
}
add_filter("posts_where", "my_posts_where");
// get results
$this_month = date("Ym") . "14"; // this doesn't work if I remove the . "14"
$the_query = new WP_Query(array(
"numberposts" => -1,
"post_type" => "plays_events",
"meta_query" => array(
array(
"key" => "show_times_%_date",
"value" => $this_month,
)
),
));
```
I'm really confused by the `my_posts_where` but, I just copied and modified it from [this page](http://www.advancedcustomfields.com/resources/how-to-query-posts-filtered-by-custom-field-values/#example-5).
Essentially it's the "value" option that I need to figure out how to say `$this_month . $any_day`.
Thanks.
|
I figured it out:
```
$the_query = new WP_Query(array(
"numberposts" => -1,
"post_type" => "plays_events",
"meta_query" => array(
array(
"key" => "show_times_%_date",
"value" => $this_month . "[0-9]{2}",
"compare" => "REGEXP"
)
),
));
```
|
178,309 |
<p>I've created a custom post type <code>portfolio</code> and a <code>taxonomy</code> of course. </p>
<pre><code>function taxonomies_portfolio() {
$labels = array(
'name' => _x( 'Portfolio categories', 'taxonomy general name' ),
'singular_name' => _x( 'Portfolio categories', 'taxonomy singular name' ),
'search_items' => __( 'Query portfolio categories' ),
'all_items' => __( 'All portfolio categories' ),
'parent_item' => __( 'Parent category' ),
'parent_item_colon' => __( 'Parent category:' ),
'edit_item' => __( 'Edit portfolio category' ),
'update_item' => __( 'Update portfolio category' ),
'add_new_item' => __( 'Add Edit portfolio category' ),
'new_item_name' => __( 'New portfolio category' ),
'menu_name' => __( 'Categories' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'rewrite' => true
);
register_taxonomy( 'portfolio_category', 'portfolio', $args );
}
add_action( 'init', 'taxonomies_portfolio', 0 );
</code></pre>
<p>Is it possible to create <strong>1 template file to display all items of a single category?</strong> I've tried to create a <code>taxonomy.php</code> but without success. What is the correct template name to work with? </p>
|
[
{
"answer_id": 178311,
"author": "Manny Fleurmond",
"author_id": 2234,
"author_profile": "https://wordpress.stackexchange.com/users/2234",
"pm_score": 4,
"selected": true,
"text": "<p>According to the Wordpress Codex page on <a href=\"http://codex.wordpress.org/Template_Hierarchy#Custom_Taxonomies_display\" rel=\"noreferrer\">Template Hierarchy</a>, you create a template file with the name of <code>taxonomy-portfolio_category.php</code>. WordPress will use that to display the archive for that taxonomy. You can also use <code>taxonomy-portfolio_category-{term_name}.php</code> to create templates for specific terms in your taxonomy.</p>\n"
},
{
"answer_id": 291885,
"author": "bob-12345",
"author_id": 118041,
"author_profile": "https://wordpress.stackexchange.com/users/118041",
"pm_score": 0,
"selected": false,
"text": "<p>You do not have to use the WordPress standard tempates to manage the several taxonomies' templates for the same custom post type.</p>\n\n<p>Assume you have your: 1) <code>portfolio</code> CPT with the 1) <code>pcat</code> taxonomy and 3) 'sites', 'apps' and 'design' terms created in this taxonomy (here slugs are shown).</p>\n\n<p><strong>Case 1:</strong> You may want to show the same template for any of these <code>pcat</code> taxonomies. Just use the same single <code>portfolio-signle.php</code> template with the code that shows any single <code>portfolio</code> record in a uniform way.</p>\n\n<p><strong>Case 2:</strong> Now say you want to show different template for each <code>portfolio</code> CPT record depending on the <code>pcat</code> taxonomy term ('sites', 'apps', 'design', 'whatever') assigned to that record.</p>\n\n<p>You can do this still using the same <code>portfolio-signle.php</code> with additional partial template for each <code>pcat</code> term.</p>\n\n<p>Your <code>portfolio-signle.php</code> has to hold this code:</p>\n\n<pre><code><?php\nget_header();\n// Here you get the particular record of the `portfolio` CPT.\nglobal $post;\n// Get the array of 'pcat' taxonomy terms attached to the record\n// and take the slug of first term only (just for brevity)\n$txslug = get_the_terms($post, 'pcat')[0]->slug;\n// Dynamically prepare the file name\n$filename = get_template_directory() . '/partials/_portfolio-single-'.$txslug.'.php';\n// Check if the file exists & readable\nif (is_readable($filename)) {\n // The case when you created the sub-template partial for the particular `pcat` term.\n include get_template_directory() . '/partials/_portfolio-single-'.$txslug.'.php';\n} else {\n // The case for all other `pcat` taxonomy terms.\n include get_template_directory() . '/partials/_portfolio-single-other.php';\n}\nget_footer();\n</code></pre>\n\n<p>As you see from the code above you will have to create the respective partial sub-templates for each <code>pcat</code> taxonomy term you assign to your posts that will actually handle the look of the taxonomy term.</p>\n\n<p>Or / and create the <code>/partials/portfolio-single-other.php</code> to handle all the terms that you want to look uniform way.</p>\n\n<p>This will keep your theme files well-organized and for at no code cost allow you flexibly manage the look of the different taxonomy terms'.</p>\n\n<p>NB: Do not forget to re-declare <code>global $post;</code> at the top of your <code>'/partials/_portfolio-single-'.$txslug.'.php'</code> templates. You will get the access to the CPT object you want to show at no additional costs.</p>\n"
}
] |
2015/02/16
|
[
"https://wordpress.stackexchange.com/questions/178309",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58496/"
] |
I've created a custom post type `portfolio` and a `taxonomy` of course.
```
function taxonomies_portfolio() {
$labels = array(
'name' => _x( 'Portfolio categories', 'taxonomy general name' ),
'singular_name' => _x( 'Portfolio categories', 'taxonomy singular name' ),
'search_items' => __( 'Query portfolio categories' ),
'all_items' => __( 'All portfolio categories' ),
'parent_item' => __( 'Parent category' ),
'parent_item_colon' => __( 'Parent category:' ),
'edit_item' => __( 'Edit portfolio category' ),
'update_item' => __( 'Update portfolio category' ),
'add_new_item' => __( 'Add Edit portfolio category' ),
'new_item_name' => __( 'New portfolio category' ),
'menu_name' => __( 'Categories' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'rewrite' => true
);
register_taxonomy( 'portfolio_category', 'portfolio', $args );
}
add_action( 'init', 'taxonomies_portfolio', 0 );
```
Is it possible to create **1 template file to display all items of a single category?** I've tried to create a `taxonomy.php` but without success. What is the correct template name to work with?
|
According to the Wordpress Codex page on [Template Hierarchy](http://codex.wordpress.org/Template_Hierarchy#Custom_Taxonomies_display), you create a template file with the name of `taxonomy-portfolio_category.php`. WordPress will use that to display the archive for that taxonomy. You can also use `taxonomy-portfolio_category-{term_name}.php` to create templates for specific terms in your taxonomy.
|
178,321 |
<p>I'm trying to get the meta info by key <code>rw_related_link</code> for each post but my code is wrong since instead get the ones related to the current post I got the same in all post and that's wrong. This is what I have at <code>single.php</code>:</p>
<pre><code>if (have_posts()) {
while (have_posts()) {
the_post();
$normal_args = array(
'ignore_sticky_posts' => 1,
'order' => 'desc',
'meta_query' => array(
array(
'key' => 'rw_related_link'
)
),
'post_status' => 'publish',
'posts_per_page' => 6
);
$normal_query = new WP_Query( $normal_args );
if ($normal_query->have_posts()) { ?>
<section class="single_relations sih1">
<ul>
<?php while ($normal_query->have_posts()) {
$normal_query->the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
} ?>
</ul>
</section>
<?php }
wp_reset_postdata();
}
}
</code></pre>
<p>What is wrong in my code?</p>
|
[
{
"answer_id": 178329,
"author": "Bruno Rodrigues",
"author_id": 42886,
"author_profile": "https://wordpress.stackexchange.com/users/42886",
"pm_score": 3,
"selected": true,
"text": "<p>The way you did in your code you are querying posts with the key <code>rw_related_link</code>.</p>\n\n<p>If I understood you right, you must use get_post_meta inside the loop.</p>\n\n<pre><code><?php while ($normal_query->have_posts()) {\n $normal_query->the_post(); \n $related_link = get_post_meta(get_the_ID(), 'rw_related_link', true);\n // The value you want is in $related_link variable.\n?>\n <li><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></li>\n<?php } ?>\n</code></pre>\n\n<p>Hope it helps.</p>\n"
},
{
"answer_id": 178332,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 1,
"selected": false,
"text": "<p>The arguments passed to <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">the <code>WP_Query</code> class</a>'s constructor are used to describe the posts you are \"looking for\" in, and wish to retrieve from the database - <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow\">the <code>'meta_query'</code> argument</a> is used to retrieve posts that contain a particular meta key and/or value.</p>\n\n<p>In order to actually manipulate (i.e. create/retrieve/update/delete) post meta-data, you should be using the <a href=\"http://codex.wordpress.org/Metadata_API\" rel=\"nofollow\">Metadata API</a> - in this instance, <a href=\"http://codex.wordpress.org/Function_Reference/get_metadata\" rel=\"nofollow\">the <code>get_metadata()</code> function</a> in particular.</p>\n"
}
] |
2015/02/16
|
[
"https://wordpress.stackexchange.com/questions/178321",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16412/"
] |
I'm trying to get the meta info by key `rw_related_link` for each post but my code is wrong since instead get the ones related to the current post I got the same in all post and that's wrong. This is what I have at `single.php`:
```
if (have_posts()) {
while (have_posts()) {
the_post();
$normal_args = array(
'ignore_sticky_posts' => 1,
'order' => 'desc',
'meta_query' => array(
array(
'key' => 'rw_related_link'
)
),
'post_status' => 'publish',
'posts_per_page' => 6
);
$normal_query = new WP_Query( $normal_args );
if ($normal_query->have_posts()) { ?>
<section class="single_relations sih1">
<ul>
<?php while ($normal_query->have_posts()) {
$normal_query->the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
} ?>
</ul>
</section>
<?php }
wp_reset_postdata();
}
}
```
What is wrong in my code?
|
The way you did in your code you are querying posts with the key `rw_related_link`.
If I understood you right, you must use get\_post\_meta inside the loop.
```
<?php while ($normal_query->have_posts()) {
$normal_query->the_post();
$related_link = get_post_meta(get_the_ID(), 'rw_related_link', true);
// The value you want is in $related_link variable.
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php } ?>
```
Hope it helps.
|
178,327 |
<p>I am trying to create a Facebook JS-SDK based auto login feature. When user is "Connected" passing FbID and aother user data to an ajax function which creates the session cookie. Cookie is created (I can see <code>"wordpress_logged_in_.... cookie"</code> in the browser inspector) but when I reload the page the user is still logged out. </p>
<p>Do you have idea why?</p>
<p><strong>JavaScript</strong></p>
<pre><code>function ajaxloginFB(uid,email,first_name,last_name) {
data = "uid=" + uid + "&" + "name=" + last_name + " " + first_name + "&" + "email=" + email + "&" + $.param({ action: 'facebook_login', nonce: ajax_object.ajaxnonce });
$.ajax({
url : ajax_object.ajaxurl,
type: "post",
data : data,
success:function(response){
var response = $.parseJSON(response);
if (response.success == true){
window.location.reload();
}
}
});
}
</code></pre>
<p><strong>PHP</strong></p>
<pre><code>add_action( 'wp_ajax_facebook_login', 'facebook_ajax_login_or_register' );
add_action( 'wp_ajax_nopriv_facebook_login', 'facebook_ajax_login_or_register' );
function facebook_ajax_login_or_register(){
$uid = sanitize_text_field( $_POST['uid'] );
$args = array(
'meta_key' => 'fbuid',
'meta_value' => $uid,
'meta_compare' => '=',
);
$fb_user = get_users($args);
$current_user_id = $fb_user[0];
wp_set_auth_cookie( $current_user_id, true );
$response[success] = true;
echo json_encode($response);
die();
}
</code></pre>
|
[
{
"answer_id": 243845,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 2,
"selected": false,
"text": "<p>I add one function <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_current_user\" rel=\"nofollow\">wp_set_current_user</a> for setting up current user.</p>\n\n<pre><code>add_action( 'wp_ajax_facebook_login', 'facebook_ajax_login_or_register' );\nadd_action( 'wp_ajax_nopriv_facebook_login', 'facebook_ajax_login_or_register' );\n\nfunction facebook_ajax_login_or_register(){\n $uid = sanitize_text_field( $_POST['uid'] );\n $args = array(\n 'meta_key' => 'fbuid',\n 'meta_value' => $uid,\n 'meta_compare' => '=',\n );\n $fb_user = get_users($args);\n $current_user_id = $fb_user[0];\n wp_set_current_user($current_user_id);//Set current user\n wp_set_auth_cookie( $current_user_id, true );\n $response[success] = true;\n echo json_encode($response);\n die();\n}\n</code></pre>\n\n<p>I'm not tested this so let me know if still you facing same issue. </p>\n"
},
{
"answer_id": 306174,
"author": "Michał Mazur",
"author_id": 145362,
"author_profile": "https://wordpress.stackexchange.com/users/145362",
"pm_score": 0,
"selected": false,
"text": "<p>I use ajax with xhr authentication header for my custom wp login</p>\n\n<pre><code>$.ajax({\n url : ajax_object.ajaxurl,\n type: \"post\",\n data: data,\n contentType: 'application/x-www-form-urlencoded',\n xhrFields: {withCredentials: true}\n});\n</code></pre>\n"
}
] |
2015/02/16
|
[
"https://wordpress.stackexchange.com/questions/178327",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9909/"
] |
I am trying to create a Facebook JS-SDK based auto login feature. When user is "Connected" passing FbID and aother user data to an ajax function which creates the session cookie. Cookie is created (I can see `"wordpress_logged_in_.... cookie"` in the browser inspector) but when I reload the page the user is still logged out.
Do you have idea why?
**JavaScript**
```
function ajaxloginFB(uid,email,first_name,last_name) {
data = "uid=" + uid + "&" + "name=" + last_name + " " + first_name + "&" + "email=" + email + "&" + $.param({ action: 'facebook_login', nonce: ajax_object.ajaxnonce });
$.ajax({
url : ajax_object.ajaxurl,
type: "post",
data : data,
success:function(response){
var response = $.parseJSON(response);
if (response.success == true){
window.location.reload();
}
}
});
}
```
**PHP**
```
add_action( 'wp_ajax_facebook_login', 'facebook_ajax_login_or_register' );
add_action( 'wp_ajax_nopriv_facebook_login', 'facebook_ajax_login_or_register' );
function facebook_ajax_login_or_register(){
$uid = sanitize_text_field( $_POST['uid'] );
$args = array(
'meta_key' => 'fbuid',
'meta_value' => $uid,
'meta_compare' => '=',
);
$fb_user = get_users($args);
$current_user_id = $fb_user[0];
wp_set_auth_cookie( $current_user_id, true );
$response[success] = true;
echo json_encode($response);
die();
}
```
|
I add one function [wp\_set\_current\_user](https://codex.wordpress.org/Function_Reference/wp_set_current_user) for setting up current user.
```
add_action( 'wp_ajax_facebook_login', 'facebook_ajax_login_or_register' );
add_action( 'wp_ajax_nopriv_facebook_login', 'facebook_ajax_login_or_register' );
function facebook_ajax_login_or_register(){
$uid = sanitize_text_field( $_POST['uid'] );
$args = array(
'meta_key' => 'fbuid',
'meta_value' => $uid,
'meta_compare' => '=',
);
$fb_user = get_users($args);
$current_user_id = $fb_user[0];
wp_set_current_user($current_user_id);//Set current user
wp_set_auth_cookie( $current_user_id, true );
$response[success] = true;
echo json_encode($response);
die();
}
```
I'm not tested this so let me know if still you facing same issue.
|
178,331 |
<p>Is there a native function to display the correct responsive image size for post thumbnails or gallery images depending on the screen resolution?</p>
<p>Normally I'm using:</p>
<p>1.Custom image sizes:</p>
<pre><code>function customImageSetup () {
add_theme_support( 'post-thumbnails' );
add_image_size('grid_1 mini square', 60, 60, TRUE);
add_image_size('grid_2', 160);
add_image_size('grid_2 square', 160, 160, TRUE);
add_image_size('grid_4', 360);
add_image_size('grid_4 square', 360, 360, TRUE);
add_image_size('grid_6', 560);
add_image_size('grid_6 square', 560, 560, TRUE);
add_image_size('grid_8', 760);
add_image_size('grid_8 square', 760, 760, TRUE);
add_image_size('grid_10', 960);
add_image_size('grid_12', 1160, FALSE);
}
</code></pre>
<p>2.Display e.g. the thumbnail with <code>.img-max</code> class assigned:</p>
<pre><code><?php the_post_thumbnail('grid_4', array( 'class' => "img-max"));?>
</code></pre>
<p>3.And this simple css line to fit the image:</p>
<pre><code>.img-max { width:100%; height:auto; }
</code></pre>
<p>This works in most cases, but especially in terms of responsive web design it would be quite useful to make use of custom image sizes at different screen resolutions. </p>
<p>Is there a wordpress function to replace images server side and without javascript?</p>
|
[
{
"answer_id": 178333,
"author": "cristian.raiber",
"author_id": 52524,
"author_profile": "https://wordpress.stackexchange.com/users/52524",
"pm_score": 1,
"selected": false,
"text": "<p>No, there isn't such a thing at the moment. However, there is a solution you could try if you're really keen on this. </p>\n\n<p>This is something I've used in the past and it's worked out fine, although it has its limitations. </p>\n\n<p><strong>The solution:</strong></p>\n\n<p>You could write a small JS function that gets the user's current screen resolution and have it written to a cookie. You're also going to need a function that updates the value stored in the cookie if the user is resizing his browser window. </p>\n\n<p>You can read this cookie using PHP and have something along the lines of:</p>\n\n<pre><code>if($screen_resolution > 640 && $screen_resolution < 860) {\n\n the_post_thumbnail('your-custom-image-size-for-this-viewport-here');\n}\n</code></pre>\n\n<p>P.S: Please take into account that this solution doesn't work too good with caching systems.</p>\n"
},
{
"answer_id": 178392,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>To add to the answer from @cristian.raiber, there is no function in Wordpress or php to detect screen sizes, and there will in all probabilty never be such functionality. Php runs server side, which runs before clients side which is browser side. As for php, and for that matter Wordpress, I cannot see any future implementation of any kind of function to handle such detection in any form of predictable and reliable way. </p>\n\n<p>There is just no fool prove way to make this work, no matter how you look at it. Server side operations is predictable and something we can trust as it does not rely on end user input, and most importantly cannot be manipulated by the end user. Client side operations <strong>can</strong> be maniplulated. </p>\n\n<p>Look at the following client side variables and manipulations:</p>\n\n<ul>\n<li><p>Cookies -> Cookies can be deleted or blocked by the user, cookies can also be blocked by state or country laws</p></li>\n<li><p>jQuery -> End users can disable jquery anytime</p></li>\n<li><p>Browsers -> Sites behave differently in different browsers. End users can disable browser detection</p></li>\n</ul>\n\n<p>Client side solutions will work in some cases, in other cases not based on the above (there are other points not mentioned as well). </p>\n\n<p>You could use <code>wp_is_mobile()</code> to detect mobiles (it only works on mobiles, not tablets) and then dish up the correct image size accordingly, <strong>BUT</strong>, the following should be noted</p>\n\n<ul>\n<li><p>As the above points on client side operations, this is also an unreliable function as it also depends on client side operations. In my opinion, a mickey mouse function</p></li>\n<li><p>It does not detect screen sizes, and it only detects mobile phone devices. It does not work on tablets</p></li>\n</ul>\n\n<h2>CONCLUSION</h2>\n\n<p>The only proper solution to this is to optimize your images as best you can (this require proper planning and correct image sizes to be dished up according to content size. Don't load a 700px image when your content max width is 500px) then let the browser resize the images accordingly. I know this slows loading times as browsers use a lot of resources to resize images, but at least you can be able to serve content reliably to the the end user</p>\n"
},
{
"answer_id": 184196,
"author": "William Turrell",
"author_id": 42868,
"author_profile": "https://wordpress.stackexchange.com/users/42868",
"pm_score": 2,
"selected": false,
"text": "<p>There's no native function, but the <a href=\"https://wordpress.org/plugins/ricg-responsive-images/\" rel=\"nofollow\">RICG Responsive Images plugin</a> will add a <code>srcset</code> attribute with the available image sizes. Srcset (along with the <code><picture></code> element), is <a href=\"http://caniuse.com/#feat=srcset\" rel=\"nofollow\">steadily gaining browser support</a> - it doesn't need any javascript and it's up to the browser to decide which is the correct image to load.</p>\n\n<p>The attribute is added for posts where you've used the 'Add Media' button and <a href=\"https://github.com/ResponsiveImagesCG/wp-tevko-responsive-images/blob/master/readme.md\" rel=\"nofollow\">there are methods</a> to call it by hand within a theme template – you could modify your <code>customImageSetup</code> function to call <a href=\"https://github.com/ResponsiveImagesCG/wp-tevko-responsive-images/blob/master/readme.md#tevkori_get_srcset_string-id-size-\" rel=\"nofollow\">tevkori_get_srcset_string()</a>, for example.</p>\n\n<p>It's non-invasive, in that it won't make any changes to your media library or database and if you uninstall it your site will go back to normal.</p>\n"
}
] |
2015/02/16
|
[
"https://wordpress.stackexchange.com/questions/178331",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58496/"
] |
Is there a native function to display the correct responsive image size for post thumbnails or gallery images depending on the screen resolution?
Normally I'm using:
1.Custom image sizes:
```
function customImageSetup () {
add_theme_support( 'post-thumbnails' );
add_image_size('grid_1 mini square', 60, 60, TRUE);
add_image_size('grid_2', 160);
add_image_size('grid_2 square', 160, 160, TRUE);
add_image_size('grid_4', 360);
add_image_size('grid_4 square', 360, 360, TRUE);
add_image_size('grid_6', 560);
add_image_size('grid_6 square', 560, 560, TRUE);
add_image_size('grid_8', 760);
add_image_size('grid_8 square', 760, 760, TRUE);
add_image_size('grid_10', 960);
add_image_size('grid_12', 1160, FALSE);
}
```
2.Display e.g. the thumbnail with `.img-max` class assigned:
```
<?php the_post_thumbnail('grid_4', array( 'class' => "img-max"));?>
```
3.And this simple css line to fit the image:
```
.img-max { width:100%; height:auto; }
```
This works in most cases, but especially in terms of responsive web design it would be quite useful to make use of custom image sizes at different screen resolutions.
Is there a wordpress function to replace images server side and without javascript?
|
To add to the answer from @cristian.raiber, there is no function in Wordpress or php to detect screen sizes, and there will in all probabilty never be such functionality. Php runs server side, which runs before clients side which is browser side. As for php, and for that matter Wordpress, I cannot see any future implementation of any kind of function to handle such detection in any form of predictable and reliable way.
There is just no fool prove way to make this work, no matter how you look at it. Server side operations is predictable and something we can trust as it does not rely on end user input, and most importantly cannot be manipulated by the end user. Client side operations **can** be maniplulated.
Look at the following client side variables and manipulations:
* Cookies -> Cookies can be deleted or blocked by the user, cookies can also be blocked by state or country laws
* jQuery -> End users can disable jquery anytime
* Browsers -> Sites behave differently in different browsers. End users can disable browser detection
Client side solutions will work in some cases, in other cases not based on the above (there are other points not mentioned as well).
You could use `wp_is_mobile()` to detect mobiles (it only works on mobiles, not tablets) and then dish up the correct image size accordingly, **BUT**, the following should be noted
* As the above points on client side operations, this is also an unreliable function as it also depends on client side operations. In my opinion, a mickey mouse function
* It does not detect screen sizes, and it only detects mobile phone devices. It does not work on tablets
CONCLUSION
----------
The only proper solution to this is to optimize your images as best you can (this require proper planning and correct image sizes to be dished up according to content size. Don't load a 700px image when your content max width is 500px) then let the browser resize the images accordingly. I know this slows loading times as browsers use a lot of resources to resize images, but at least you can be able to serve content reliably to the the end user
|
178,356 |
<p>So, for the Plupload, I know there is a documentation to how to resize the image on the client side before uploading : <a href="http://www.plupload.com/docs/Image-Resizing-on-Client-Side" rel="nofollow">http://www.plupload.com/docs/Image-Resizing-on-Client-Side</a></p>
<p>However, I am not sure how to do it for Wordpress.</p>
<p>Could you guys give me a guidance to how to do this?</p>
<p>Thank you so much!</p>
<p>Regards</p>
|
[
{
"answer_id": 178473,
"author": "Leo Caseiro",
"author_id": 52791,
"author_profile": "https://wordpress.stackexchange.com/users/52791",
"pm_score": 2,
"selected": true,
"text": "<p>I've done a Plupload using the Front End. The WordPress Plupload is very customised, so I've implemented from the scratch as a Plugin. I'll show an example using <em>functions.php</em></p>\n\n<p>Download the Plupload from <a href=\"http://www.plupload.com/download/\" rel=\"nofollow\">http://www.plupload.com/download/</a> and put in your theme inside a js/thirdparty/plupload/{all_files}</p>\n\n<p><br></p>\n\n<p>Code to use on <em>functions.php</em></p>\n\n<pre><code> //Plupload File\n wp_enqueue_script( 'plupload', get_template_directory_uri() . '/js/thirdparty/plupload/js/plupload.full.min.js', array( 'jquery' ) );\n //Plupload Queue File (up to you using queue)\n wp_enqueue_script( 'plupload-queue', get_template_directory_uri() .'/js/thirdparty/plupload/js/jquery.plupload.queue.min.js', array( 'jquery' ) );\n //Your own JS (make sure you set the dependencies)\n wp_enqueue_script( 'my-functions', get_template_directory_uri() .'/js/functions.js', array( 'jquery' , 'plupload', 'plupload-queue' ) );\n\n //Send the wp-admin/wp-ajax.php to the Javascript:\n wp_localize_script( 'my-functions', 'customObj', array(\n 'ajax_url' => admin_url( 'admin-ajax.php' )\n ) );\n\n\n //AJAX Upload function\n add_action( 'wp_ajax_my_custom_plupload_ajax_method', 'process_ajax_my_custom_plupload_ajax_method' );\n add_action( 'wp_ajax_nopriv_my_custom_plupload_ajax_method', 'process_ajax_my_custom_plupload_ajax_method' );\n\n //Here you will code your upload depends on your needs:\n function process_ajax_my_custom_plupload_ajax_method() {\n $mimes = array(\n 'jpg' =>'image/jpg',\n 'jpeg' =>'image/jpeg',\n 'gif' => 'image/gif',\n 'png' => 'image/png'\n );\n\n\n $uploadedfile = $_FILES['file']; //Default from Plupload.\n\n //You could use media_handle_upload also, up to you.\n $upload_overrides = array( 'test_form' => false, 'mimes' => $mimes );\n $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );\n\n\n if ( is_wp_error( $movefile ) ) {\n return wp_send_json_error( $movefile );\n } else {\n return wp_send_json_success( $movefile );\n }\n }\n</code></pre>\n\n<p><br></p>\n\n<p>Than you can use JS like normally you'd use</p>\n\n<p>Code to use in <em>/js/functions.js:</em></p>\n\n<pre><code>var uploader = new plupload.Uploader({\n runtimes : 'html5, flash, silverlight, html4',\n url : customObj.ajax_url, //it comes with wp_localize_script\n drop_element: 'sortable', //up to you\n chunk_size : '1mb',\n unique_names : true,\n\n resize : {width : 320, height : 240, quality : 90}, //Here you go to resize images\n\n browse_button : 'pickfiles', // you can pass in id...\n container: 'container', // ... or DOM Element itself\n\n filters : {\n max_file_size : '2mb',\n\n // Specify what files to browse for\n mime_types: [\n {title : \"Image files\", extensions : \"jpeg,jpg,gif,png\"}\n ],\n prevent_duplicates: true\n },\n\n multipart_params: {\n 'action': 'my_custom_plupload_ajax_method' //Depends on the PHP method\n },\n\n //Flash settings\n flash_swf_url : '/plupload/js/Moxie.swf',\n\n // Silverlight settings\n silverlight_xap_url : '/plupload/js/Moxie.xap',\n\n init: {\n PostInit: function() {\n document.getElementById('filelist').innerHTML = '';\n\n document.getElementById('uploadfiles').onclick = function() {\n uploader.start();\n return false;\n };\n },\n\n FilesAdded: function(up, files) {\n plupload.each(files, function(file) {\n document.getElementById('filelist').innerHTML += '<div id=\"' + file.id + '\">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>';\n });\n },\n\n UploadProgress: function(up, file) {\n document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + \"%</span>\";\n },\n\n Error: function(up, err) {\n document.getElementById('console').innerHTML += \"\\nError #\" + err.code + \": \" + err.message;\n },\n FileUploaded: function(up, file, info) {\n var photo = JSON.parse(info.response);\n console.log(photo); //Here you'll use in your JS. That's the WP result.\n }\n});\n\nuploader.init();\n</code></pre>\n\n<p>The method to upload, you can use either <a href=\"http://codex.wordpress.org/Function_Reference/media_handle_upload\" rel=\"nofollow\">media_handle_upload</a> if you want it into your media or <a href=\"http://codex.wordpress.org/Function_Reference/wp_handle_upload\" rel=\"nofollow\">wp_handle_upload</a> for upload by itself (can be used for any file, you just need to change the mime_types).</p>\n\n<p>Hope works for you.</p>\n"
},
{
"answer_id": 214438,
"author": "Jörn Lund",
"author_id": 35723,
"author_profile": "https://wordpress.stackexchange.com/users/35723",
"pm_score": 2,
"selected": false,
"text": "<p>The following Code will enable client side image resize everywhere:</p>\n\n<ol>\n<li><p>Put a file named <code>client-side-image-resize.php</code> in your mu-plugins directory (<code>wp-content/mu-plugins/</code>)</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function client_side_resize_load() {\n wp_enqueue_script( 'client-resize' , plugins_url( 'client-side-image-resize.js' , __FILE__ ) , array('media-editor' ) , '0.0.1' );\n wp_localize_script( 'client-resize' , 'client_resize' , array( \n 'plupload' => array(\n 'resize' => array(\n 'enabled' => true,\n 'width' => 1920, // enter your width here\n 'height' => 1200, // enter your width here\n 'quality' => 90,\n ),\n )\n ) );\n}\nadd_action( 'wp_enqueue_media' , 'client_side_resize_load' );\n</code></pre>\n\n<p>The php will create a js object named <code>client_resize</code> and enqueue the following script.</p></li>\n<li><p>Save another file named <code>client-side-image-resize.js</code> in the same directory:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>(function(media){\n var oldReady = media.view.UploaderWindow.prototype.ready;\n media.view.UploaderWindow.prototype.ready = function() {\n if ( ! this.options.uploader.plupload )\n this.options.uploader.plupload = client_resize.plupload;\n // back to default behaviour\n oldReady.apply( this , arguments );\n };\n})(wp.media);\n</code></pre>\n\n<p>The JS is configuring Plupload to resize images on client side before uploading them.</p></li>\n</ol>\n\n<p>The next step would be to scan WPs image sizes for the largest possible size, in order to auto configure the <code>client_resize</code> js object.</p>\n"
}
] |
2015/02/16
|
[
"https://wordpress.stackexchange.com/questions/178356",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67604/"
] |
So, for the Plupload, I know there is a documentation to how to resize the image on the client side before uploading : <http://www.plupload.com/docs/Image-Resizing-on-Client-Side>
However, I am not sure how to do it for Wordpress.
Could you guys give me a guidance to how to do this?
Thank you so much!
Regards
|
I've done a Plupload using the Front End. The WordPress Plupload is very customised, so I've implemented from the scratch as a Plugin. I'll show an example using *functions.php*
Download the Plupload from <http://www.plupload.com/download/> and put in your theme inside a js/thirdparty/plupload/{all\_files}
Code to use on *functions.php*
```
//Plupload File
wp_enqueue_script( 'plupload', get_template_directory_uri() . '/js/thirdparty/plupload/js/plupload.full.min.js', array( 'jquery' ) );
//Plupload Queue File (up to you using queue)
wp_enqueue_script( 'plupload-queue', get_template_directory_uri() .'/js/thirdparty/plupload/js/jquery.plupload.queue.min.js', array( 'jquery' ) );
//Your own JS (make sure you set the dependencies)
wp_enqueue_script( 'my-functions', get_template_directory_uri() .'/js/functions.js', array( 'jquery' , 'plupload', 'plupload-queue' ) );
//Send the wp-admin/wp-ajax.php to the Javascript:
wp_localize_script( 'my-functions', 'customObj', array(
'ajax_url' => admin_url( 'admin-ajax.php' )
) );
//AJAX Upload function
add_action( 'wp_ajax_my_custom_plupload_ajax_method', 'process_ajax_my_custom_plupload_ajax_method' );
add_action( 'wp_ajax_nopriv_my_custom_plupload_ajax_method', 'process_ajax_my_custom_plupload_ajax_method' );
//Here you will code your upload depends on your needs:
function process_ajax_my_custom_plupload_ajax_method() {
$mimes = array(
'jpg' =>'image/jpg',
'jpeg' =>'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png'
);
$uploadedfile = $_FILES['file']; //Default from Plupload.
//You could use media_handle_upload also, up to you.
$upload_overrides = array( 'test_form' => false, 'mimes' => $mimes );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( is_wp_error( $movefile ) ) {
return wp_send_json_error( $movefile );
} else {
return wp_send_json_success( $movefile );
}
}
```
Than you can use JS like normally you'd use
Code to use in */js/functions.js:*
```
var uploader = new plupload.Uploader({
runtimes : 'html5, flash, silverlight, html4',
url : customObj.ajax_url, //it comes with wp_localize_script
drop_element: 'sortable', //up to you
chunk_size : '1mb',
unique_names : true,
resize : {width : 320, height : 240, quality : 90}, //Here you go to resize images
browse_button : 'pickfiles', // you can pass in id...
container: 'container', // ... or DOM Element itself
filters : {
max_file_size : '2mb',
// Specify what files to browse for
mime_types: [
{title : "Image files", extensions : "jpeg,jpg,gif,png"}
],
prevent_duplicates: true
},
multipart_params: {
'action': 'my_custom_plupload_ajax_method' //Depends on the PHP method
},
//Flash settings
flash_swf_url : '/plupload/js/Moxie.swf',
// Silverlight settings
silverlight_xap_url : '/plupload/js/Moxie.xap',
init: {
PostInit: function() {
document.getElementById('filelist').innerHTML = '';
document.getElementById('uploadfiles').onclick = function() {
uploader.start();
return false;
};
},
FilesAdded: function(up, files) {
plupload.each(files, function(file) {
document.getElementById('filelist').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>';
});
},
UploadProgress: function(up, file) {
document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
},
Error: function(up, err) {
document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
},
FileUploaded: function(up, file, info) {
var photo = JSON.parse(info.response);
console.log(photo); //Here you'll use in your JS. That's the WP result.
}
});
uploader.init();
```
The method to upload, you can use either [media\_handle\_upload](http://codex.wordpress.org/Function_Reference/media_handle_upload) if you want it into your media or [wp\_handle\_upload](http://codex.wordpress.org/Function_Reference/wp_handle_upload) for upload by itself (can be used for any file, you just need to change the mime\_types).
Hope works for you.
|
178,370 |
<p>I am having problems enqueuing javascript. When I use the script tag in the head section of my site, everything works just fine. If I take the scripts out and use enqueue, the site breaks but I don't get any errors in firebug. Viewing the source code, the entire page looks as if it is there but obviously some of the js scripts are not working and this causes my site to crash. Is there a way to find out why it's crashing? The console has nothing in it. </p>
<p>I would link to the site but I am going to continue working and since things will change, the link won't be much good. I am looking for tips to debugging js errors. Where can I look? </p>
<p>my method of enqueueing the script</p>
<pre><code> wp_register_script('isotope', get_template_directory_uri() . '/js/jquery.isotope.min.js',array('jquery'),'',true);
wp_enqueue_script('isotope');
function bliss_jsscripts(){
if( !is_admin()){
wp_register_script('supersized', get_template_directory_uri() . '/js/supersized.3.2.6.js',array('jquery'), false, true);
wp_enqueue_script('supersized','','',false,'');
}
}
add_action('wp_enqueue_scripts', 'bliss_jsscripts', 999);
</code></pre>
|
[
{
"answer_id": 178372,
"author": "Privateer",
"author_id": 66020,
"author_profile": "https://wordpress.stackexchange.com/users/66020",
"pm_score": 2,
"selected": false,
"text": "<p>What you might do is check the status of the scripts you are trying to enqueue after doing so.</p>\n\n<p>Also, be sure to enqueue things inside of an action.</p>\n\n<p>e.g.</p>\n\n<pre><code>function do_my_enqueue_scripts() {\n wp_register_script('isotope', get_template_directory_uri() . '/js/jquery.isotope.min.js',array('jquery'),'',true);\n\n wp_enqueue_script('isotope');\n}\nadd_action('wp_enqueue_scripts', 'do_my_enqueue_scripts');\n</code></pre>\n\n<p>You can use the <a href=\"http://codex.wordpress.org/Function_Reference/wp_script_is\" rel=\"nofollow\">wp_script_is</a> function to check if they actually get enqueued.</p>\n\n<p>e.g. after </p>\n\n<pre><code>wp_enqueue_script('isotope');\nif ( ! wp_script_is('isotope', 'enqueued') ) {\n echo '<p>Script failed to queue up!</p>';\n}\n</code></pre>\n"
},
{
"answer_id": 179129,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 1,
"selected": false,
"text": "<p>Your problem likely stems from using the WordPress functions incorrectly - there is probably no need to debug any Javascript to solve the issue. Carefully review <a href=\"http://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\">the Codex entry for <code>wp_enqueue_script()</code></a>. </p>\n\n<p>I assume this is what you are attempting to accomplish. In your theme's <strong>functions.php</strong> file:</p>\n\n<pre><code>function wpse178370_enqueue_scripts() {\n wp_enqueue_script( 'isotope', get_template_directory_uri() . '/js/jquery.isotope.min.js', array('jquery') );\n wp_enqueue_script( 'supersized', get_template_directory_uri() . '/js/supersized.3.2.6.js', array('jquery'), '3.2.6' );\n}\n\nadd_action( 'wp_enqueue_scripts', 'wpse178370_enqueue_scripts' );\n</code></pre>\n\n<p>Unless you're enquing a script at largely different points in your code, or swapping out script registrations on the fly, there's not too much of a reason to use <code>wp_register_script()</code> at all. Likewise, unless you explicitly need a script to be printed in the site footer (at <code>wp_footer()</code>) <em>instead of</em> within the <code><head></head></code> tags, you shouldn't be setting the <code>$in_footer</code> argument of <code>wp_enqueue_script()</code>/<code>wp_register_script()</code> to <code>true</code>.</p>\n\n<p>If you register a script using <code>wp_register_script()</code> and specify all those optional arguments, then call <code>wp_enqueue_script()</code> with the same script tag and again specify all those optional arguments, you will override the arguments that you specified in <code>wp_register_script()</code>.</p>\n\n<p>Additionally, the <code>is_admin()</code> conditional check is uneccessary as dashboard scripts are printed on the <code>'admin_enqueue_scripts'</code> action, not <code>'wp_enqueue_scripts'</code>.</p>\n"
}
] |
2015/02/17
|
[
"https://wordpress.stackexchange.com/questions/178370",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14761/"
] |
I am having problems enqueuing javascript. When I use the script tag in the head section of my site, everything works just fine. If I take the scripts out and use enqueue, the site breaks but I don't get any errors in firebug. Viewing the source code, the entire page looks as if it is there but obviously some of the js scripts are not working and this causes my site to crash. Is there a way to find out why it's crashing? The console has nothing in it.
I would link to the site but I am going to continue working and since things will change, the link won't be much good. I am looking for tips to debugging js errors. Where can I look?
my method of enqueueing the script
```
wp_register_script('isotope', get_template_directory_uri() . '/js/jquery.isotope.min.js',array('jquery'),'',true);
wp_enqueue_script('isotope');
function bliss_jsscripts(){
if( !is_admin()){
wp_register_script('supersized', get_template_directory_uri() . '/js/supersized.3.2.6.js',array('jquery'), false, true);
wp_enqueue_script('supersized','','',false,'');
}
}
add_action('wp_enqueue_scripts', 'bliss_jsscripts', 999);
```
|
What you might do is check the status of the scripts you are trying to enqueue after doing so.
Also, be sure to enqueue things inside of an action.
e.g.
```
function do_my_enqueue_scripts() {
wp_register_script('isotope', get_template_directory_uri() . '/js/jquery.isotope.min.js',array('jquery'),'',true);
wp_enqueue_script('isotope');
}
add_action('wp_enqueue_scripts', 'do_my_enqueue_scripts');
```
You can use the [wp\_script\_is](http://codex.wordpress.org/Function_Reference/wp_script_is) function to check if they actually get enqueued.
e.g. after
```
wp_enqueue_script('isotope');
if ( ! wp_script_is('isotope', 'enqueued') ) {
echo '<p>Script failed to queue up!</p>';
}
```
|
178,376 |
<p>In order to speedup my site load and prevent scripts from render the page I'm trying to move all the <strong>possible</strong> scripts (meaning JS files) from <code>head</code> to <code>footer</code>. After read and do some research I made this code:</p>
<pre><code>function footer_enqueue_scripts() {
remove_action('wp_head', 'wp_print_scripts');
remove_action('wp_head', 'wp_print_head_scripts', 9);
remove_action('wp_head', 'wp_enqueue_scripts', 1);
add_action('wp_footer', 'wp_print_scripts', 5);
add_action('wp_footer', 'wp_enqueue_scripts', 5);
add_action('wp_footer', 'wp_print_head_scripts', 5);
}
add_action('after_setup_theme', 'footer_enqueue_scripts');
</code></pre>
<p>But it's not working since some scripts still loaded at <code>head</code>, see the output below:</p>
<pre><code><head>
<link rel="stylesheet" type="text/css" href="http://elclarin.dev/wp-content/cache/minify/000000/d4587/default.include.993ea9.css" media="all" />
<script type="text/javascript" src="http://elclarin.dev/wp-content/cache/minify/000000/d4587/default.include.0fe0ac.js"></script>
....
<!-- Metas -->
<meta charset="utf-8">
<!-- JS Files -->
<script type="text/javascript" src="http://elclarin.dev/wp-content/themes/elclarin_v2/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="http://elclarin.dev/wp-content/themes/elclarin_v2/js/jquery.tools-1.2.7.min.js"></script>
<script type="text/javascript" src="http://elclarin.dev/wp-content/themes/elclarin_v2/js/prefixfree-1.0.6.min.js"></script>
<script type="text/javascript" src="http://elclarin.dev/wp-content/themes/elclarin_v2/js/modernizr.js"></script>
<!--[if lt IE 9]>
<script type="text/javascript" src="http://elclarin.dev/wp-content/themes/elclarin_v2/js/html5shiv.js"></script>
<![endif]-->
<!--[if (gte IE 6)&(lte IE 8)]>
<script type="text/javascript" src="http://elclarin.dev/wp-content/themes/elclarin_v2/js/selectivizr-1.0.2.min.js"></script>
<![endif]-->
<script type="text/javascript">
var TEMPLATEURL = 'http://elclarin.dev/wp-content/themes/elclarin_v2';
</script>
<!-- Generated by OpenX 2.8.9 -->
<script type='text/javascript' src='http://openx.elclarinweb.com/www/delivery/spcjs.php?id=2&amp;target=_blank'></script>
<!-- Analytics Files -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-29394358-3']);
_gaq.push(['_trackPageview']);
_gaq.push(['elclarin._setAccount', 'UA-36592785-1']);
_gaq.push(['elclarin._trackPageview']);
_gaq.push(['elclarin._setAccount', 'UA-49334701-1']);
_gaq.push(['elclarin._trackPageview']);
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
...
</footer>
<script type='text/javascript' src='http://elclarin.dev/wp-includes/js/admin-bar.min.js?ver=4.1'></script>
<script type='text/javascript' src='http://elclarin.dev/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.2.1'></script>
<script type='text/javascript' src='http://elclarin.dev/wp-includes/js/hoverIntent.min.js?ver=r7'></script>
...
</code></pre>
<p>Any workaround on this topic? Live site for testing purposes is <a href="http://elclarinweb.com" rel="nofollow">here</a></p>
<p><strong>Update</strong></p>
<p>After <strong>@Milo</strong> tip I found that scripts as he said are not enqueued properly at theme in <code>header.php</code> file since I can see this:</p>
<pre><code><!-- JS Files -->
<script type="text/javascript" src="<?php echo TEMPLATEURL ?>/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="<?php echo TEMPLATEURL ?>/js/jquery.tools-1.2.7.min.js"></script>
<script type="text/javascript" src="<?php echo TEMPLATEURL ?>/js/prefixfree-1.0.6.min.js"></script>
<script type="text/javascript" src="<?php echo TEMPLATEURL ?>/js/modernizr.js"></script>
<!--[if lt IE 9]>
<script type="text/javascript" src="<?php echo TEMPLATEURL ?>/js/html5shiv.js"></script>
<![endif]-->
<!--[if (gte IE 6)&(lte IE 8)]>
<script type="text/javascript" src="<?php echo TEMPLATEURL ?>/js/selectivizr-1.0.2.min.js"></script>
<![endif]-->
<script type="text/javascript">
var TEMPLATEURL = '<?php echo TEMPLATEURL; ?>';
</script>
<script type="text/javascript" src="<?php echo TEMPLATEURL ?>/js/acciones.js"></script>
<!-- Generated by OpenX 2.8.9 -->
<script type='text/javascript' src='http://openx.elclarinweb.com/www/delivery/spcjs.php?id=2&amp;target=_blank'></script>
<!-- Analytics Files -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-29394358-3']);
_gaq.push(['_trackPageview']);
_gaq.push(['elclarin._setAccount', 'UA-36592785-1']);
_gaq.push(['elclarin._trackPageview']);
_gaq.push(['elclarin._setAccount', 'UA-49334701-1']);
_gaq.push(['elclarin._trackPageview']);
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
<!-- WP Files -->
<?php wp_head(); ?>
</code></pre>
<p>My question regarding those includes (I'm not the developer of theme but I'm pretty sure this can be fixed): what's the right|proper way to load them without break the theme and keeping performance and page speedup in mind?</p>
|
[
{
"answer_id": 178379,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>IMHO, I still think that loading scripts and styles directly in the header is bad practice as it is always a problem removing them and loading them coditionally. </p>\n\n<p>The best way to work around this is to create a [child theme] and then copy <code>header.php</code> to your child theme. Wordpress will load your child theme's header instead of the parent theme's header.</p>\n\n<p>You can now delete all the scripts from your header and properly enqueue and register them through the <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"nofollow noreferrer\"><code>wp_enqueue_scripts</code></a> hook in your child theme <code>functions.php</code>. Just remember to set the <code>$in_footer</code> parameter in the <a href=\"http://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow noreferrer\"><code>wp_enqueue_script()</code></a> and <a href=\"http://codex.wordpress.org/Function_Reference/wp_register_script\" rel=\"nofollow noreferrer\"><code>wp_register_script()</code></a> functions to `true</p>\n\n<h2>EDIT</h2>\n\n<p>From your <a href=\"https://gist.github.com/paquitodev/ff96fe0cce53334a6e2f\" rel=\"nofollow noreferrer\">linked <code>header.php</code></a>, your scripts is added between lines 56 - 95. This you will need to delete. If you visit the site, you will not see any jquery being loaded.</p>\n\n<p>Thenbuild in jquery library is already being loaded, no need to worry about that. The rest you need to enqueue yourself. Here is an example (<em>Remember, each script should have a unique handle, so name them something that is unique that will not create conflict</em>)</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'enqueue_my_scripts');\n\nfunction enqueue_my_scripts() \n{\n wp_enqueue_script('jquery-tools', get_template_directory_uri() . '/js/jquery.tools.js-1.2.7.min.js', array('jquery'), false, true);\n //Do the same for the other scripts\n}\n</code></pre>\n\n<p>Notice I have used <code>get_template_directory_uri()</code> here as you will be leaving your js folder in your parent theme. You can, however, move your js folder to your child theme, but then you will need to use <code>get_stylesheet_directory_uri()</code></p>\n\n<h2>NOTES ON THE CONDITIONAL SCRIPTS</h2>\n\n<p>There is still, after four years after being raised, no build in way to load scripts conditionally according to IE browser like there is for styles. You can check out the trac ticket and another question raising this same issue <a href=\"https://wordpress.stackexchange.com/a/54331/31545\">here</a></p>\n\n<p>I have never tried loading scripts conditionally according to browser, so I cannot comment on this section or state whether any solution work which is mentioned in the linked answer or trac ticket. What I can tell you, if the solutions don't work, you will need to copy <code>footer.php</code> to your child theme and then move lines 61 -66 from your header to your footer</p>\n\n<h2>NOTES ON THE SCRIPT LINES 67 -69</h2>\n\n<p>This sections passes a php variable to jquery. The correct way to do this will be to use <a href=\"http://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow noreferrer\"><code>wp_localize_script()</code></a>. You will need to contact the developer here for assistance as this is frankly theme related, and I do really not know where this is actually used in your scripts. Check out the link also for usage and info</p>\n\n<h2>NOTES ON THE ANALYTICS SCRIPT LINES 75 - 94</h2>\n\n<p>You will need to create a js file for this section. If you haven't copied the js folder from the parent to your child theme, create a new js folder for your child theme. Open it up and create a new js file and call it what you like, something like <code>analytics.script.js</code>.</p>\n\n<p>Next you will move everything inside the script tags to this folder, this is lines 77 - 92. Be sure to use the no conflict wrapper to wrap this script in as described <a href=\"http://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_Wrappers\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>You can just enqueue this script as normal as described earlier, just remember to use <code>get_stylesheet_directory_uri()</code> and not <code>get_template_directory_uri()</code></p>\n\n<h2>EDIT 2</h2>\n\n<p>The patch from the linked answer under <em>NOTES ON THE CONDITIONAL SCRIPTS</em> does not work, it is not yet implemented and as I said in comments, it will most probably not be included in version 10 in a 100 years time :-). Unfortunately you will need to live with this, there is just no way to achieve this at present. This is really the draw back for supporting IE6 - 8. Well, to be honest, if you still support IE6 and 7, you are fighting a battle that was lost long ago. All major software developers has dropped IE6 (this includes Wordpress), IE7 was dropped by Microsoft themselves, so software developers will follow soon, and IE 8 will not live to see end 2016 IMHO</p>\n\n<p>To overcome this compatibility issue with jquery, it might be better to stick with what the theme itself offers</p>\n\n<p>You can try something like this</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'enqueue_my_scripts', PHP_INT_MAX);\n\nfunction enqueue_my_scripts() \n{\n\n /**\n * Make sure, get_template_directory_uri() if script stays in parent theme\n * Use get_stylesheet_directory_uri() if script is in child theme\n */ \n wp_enqueue_script('jquery-min', get_template_directory_uri() . '/js/jquery-1.7.2.min.js', array(), false, true);\n wp_enqueue_script('jquery-tools', get_template_directory_uri() . '/js/jquery.tools.js-1.2.7.min.js', array('jquery-min'), false, true);\n wp_enqueue_script('prefixfree', get_template_directory_uri() . '/js/prefixfree-1.0.6.min.js', array(), false, true);\n wp_enqueue_script('modernizr', get_template_directory_uri() . '/js/modernizr.js', array(), false, true);\n\n /**\n * The two conditional scripts which there is no work around for, load them or drop support\n */ \n wp_enqueue_script('html5shiv', get_template_directory_uri() . '/js/html5shiv.js', array(), false, true);\n wp_enqueue_script('selectivizr', get_template_directory_uri() . '/js/selectivizr-1.0.2.min.js', array(), false, true);\n\n wp_enqueue_script('acciones', get_template_directory_uri() . '/js/acciones.js', array(), false, true);\n wp_enqueue_script('openx', 'http://openx.elclarinweb.com/www/delivery/spcjs.php?id=2&amp;target=_blank', array(), false, true);\n wp_enqueue_script('analytics', get_stylesheet_directory_uri() . '/js/analytics.script.js', array(), false, true);\n\n}\n</code></pre>\n\n<p>As I said before, there is a php variable passed to a script which you should talk to the theme author about. Also, any compatibility issues should be further discussed with the them authors. This is the correct layout and should in theory work. For any other theme related and compatibility issues, feel free to contact the theme author for support</p>\n\n<h2>EDIT 3</h2>\n\n<p>This is how your child theme header.php should look like</p>\n\n<pre><code><!DOCTYPE html>\n<html itemscope itemtype=\"http://schema.org/Blog\">\n<head>\n <!-- Metas -->\n <meta charset=\"utf-8\">\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n <meta name=\"google-site-verification\" content=\"V022hygXU9AHEdTBX2BFnTBYeo4SsaTjC7aGdoIMPL4\"/>\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">\n <meta name=\"viewport\" content=\"width=device-width\">\n <meta name=\"description\" content=\"<?php bloginfo( 'description' ); ?>\">\n <?php if (is_single()) { ?>\n <meta property=\"og:title\" content=\"<?php the_title(); ?>\"/>\n <meta itemprop=\"name\" content=\"<?php the_title(); ?>\">\n <meta property=\"og:type\" content=\"article\"/>\n <meta property=\"og:url\" content=\"<?php the_permalink(); ?>\"/>\n <?php\n if (has_post_thumbnail()) {\n $src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), array( 490, 290 ), false );\n ?>\n <meta property=\"og:image\" content=\"<?php echo $src[0]; ?>\"/>\n <meta itemprop=\"image\" content=\"<?php echo $src[0]; ?>\">\n <?php } else { ?>\n <meta property=\"og:image\" content=\"<?php echo TEMPLATEURL; ?>/images/logo.png\"/>\n <meta itemprop=\"image\" content=\"<?php echo TEMPLATEURL; ?>/images/logo.png\">\n <?php } ?>\n <meta property=\"og:site_name\" content=\"<?php bloginfo( 'name' ); ?>\"/>\n <meta itemprop=\"description\" content=\"<?php the_excerpt(); ?>\">\n <?php } ?>\n\n <!-- Title -->\n <title>\n <?php\n if (isset($wp_query->query_vars['b'])) {\n echo str_replace( \"+\", \" \", $wp_query->query_vars['b'] ).\" | \";\n }\n wp_title( '|', true, 'right' );\n bloginfo( 'name' );\n if (isset($paged) && $paged >= 2 || isset($page) && $page >= 2 || isset($page_alt) && $page_alt >= 2) {\n echo ' | '.sprintf( 'Página %s', max( $paged, $page, $page_alt ) );\n }\n ?>\n </title>\n\n <!-- Stylesheets & others -->\n <link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"<?php bloginfo( 'stylesheet_url' ); ?>?version=4\"/>\n <link rel=\"pingback\" href=\"<?php bloginfo( 'pingback_url' ); ?>\"/>\n <link rel=\"alternate\" type=\"application/rss+xml\" title=\"RSS\" href=\"<?php echo SITEURL; ?>/feed/\"/>\n <link rel=\"alternate\" type=\"application/atom+xml\" title=\"Atom\" href=\"<?php echo SITEURL; ?>/feed/atom/\"/>\n\n <link rel=\"shortcut icon\" href=\"<?php echo TEMPLATEURL ?>/images/favicon.ico\"/>\n <link rel=\"shortcut icon\" href=\"<?php echo TEMPLATEURL ?>/images/favicon.png\"/>\n <link rel=\"apple-shortcut icon\" href=\"<?php echo TEMPLATEURL ?>/images/favicon_iphone.png\"/>\n <link rel=\"apple-touch-icon-precomposed\" href=\"<?php echo TEMPLATEURL ?>/images/favicon_iphone.png\">\n <link rel=\"apple-touch-icon\" href=\"<?php echo TEMPLATEURL ?>/images/favicon_iphone.png\">\n\n <!-- WP Files -->\n <?php wp_head(); ?>\n</head>\n<body>\n<div class=\"for_overlays\">\n <?php\n if (is_front_page()) {\n $prepost = $post;\n $normal_args = Array(\n 'post_type' => 'portadadeldia',\n 'post_status' => 'publish',\n 'posts_per_page' => 1\n );\n $normal_query = new WP_Query( $normal_args );\n if ($normal_query->have_posts()) {\n while ($normal_query->have_posts()) {\n $normal_query->the_post();\n ?>\n <?php\n if (has_post_thumbnail()) {\n $large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );\n ?>\n <div id=\"portadadeldia\" class=\"from_overlay\">\n <a href=\"<?php echo $large_image_url[0]; ?>\" target=\"_blank\">\n <?php echo get_the_post_timthumbnail(\n $post->ID,\n 'portadadeldia_frontpage_overlay',\n array( 'alt' => trim( get_the_title() ), 'title' => trim( get_the_title() ) )\n ); ?>\n </a>\n </div>\n <?php } ?>\n <?php\n }\n }\n $post = $prepost;\n wp_reset_postdata();\n }\n ?>\n <svg>\n <filter id=\"firefoxblur\">\n <feGaussianBlur stdDeviation=\"4\"/>\n </filter>\n </svg>\n</div>\n<header>\n <div class=\"center_content\">\n <div id=\"header_publicity\" class=\"publicity\">\n <span>Publicidad</span>\n\n <div>\n <script type='text/javascript'><!--// <![CDATA[\n /* [id18] Header Top */\n OA_show(18);\n // ]]> --></script>\n <noscript><a target='_blank' href='http://openx.elclarinweb.com/www/delivery/ck.php?n=1073df0'><img\n border='0' alt=''\n src='http://openx.elclarinweb.com/www/delivery/avw.php?zoneid=18&amp;n=1073df0'/></a>\n </noscript>\n </div>\n </div>\n <h1 id=\"header_logo\"><a href=\"<?php echo SITEURL; ?>\">\n <?php\n $prepost = $post;\n $normal_args = Array(\n 'post_status' => 'publish',\n 'posts_per_page' => 1,\n 'post_type' => 'logos',\n );\n $normal_query = new WP_Query( $normal_args );\n if ($normal_query->have_posts()) {\n $normal_query->the_post();\n $thumbnail_id = get_post_thumbnail_id( $post->ID );\n $thumbnail_object = get_post( $thumbnail_id );\n $url = $thumbnail_object->guid;\n ?><img src=\"<?PHP echo $url; ?>\" alt=\"<?php bloginfo( 'name' ); ?>\"><?php\n } else {\n ?><img src=\"<?PHP echo TEMPLATEURL; ?>/images/logo.png\" alt=\"<?php bloginfo( 'name' ); ?>\"><?php\n }\n $post = $prepost;\n wp_reset_postdata();\n ?>\n </a></h1>\n <?php custom_secondary_nav( \"executive_menu\", 'header_lateral_superior', 'Menú corporativo' ); ?>\n <div id=\"header_lateral_inferior\">\n <div id=\"header_buscador\" role=\"search\" title=\"Buscar\">\n <div id=\"header_buscador_inner\">\n <form method=\"get\" action=\"<?php echo SITEURL; ?>\">\n Buscar\n <input title=\"Buscar\" type=\"text\" name=\"s\"\n value=\"<?php echo str_replace( \"+\", \" \", $wp_query->query_vars['s'] ); ?>\">\n </form>\n </div>\n </div>\n <div id=\"header_redes\">\n <a href=\"http://twitter.com/elclarin_aragua\" target=\"_blank\"><img\n src=\"<?php echo TEMPLATEURL ?>/images/icons/tw.png\"></a>\n <a href=\"<?php echo SITEURL; ?>/rss\" target=\"_blank\"><img\n src=\"<?php echo TEMPLATEURL ?>/images/icons/rs.png\"></a>\n <a href=\"<?php echo SITEURL; ?>\"><img src=\"<?php echo TEMPLATEURL ?>/images/icons/ho.png\"></a>\n </div>\n </div>\n <div id=\"header_menu\">\n <?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_id' => 3 ) ); ?>\n </div>\n </div>\n</header>\n<div role=\"main\" id=\"main\" class=\"main\">\n <div class=\"center_content\">\n</code></pre>\n"
},
{
"answer_id": 357131,
"author": "Hans Ganteng",
"author_id": 176590,
"author_profile": "https://wordpress.stackexchange.com/users/176590",
"pm_score": 0,
"selected": false,
"text": "<p>I think your script is correct, but maybe you must fix this element </p>\n\n<pre><code>add_action('after_setup_theme', 'footer_enqueue_scripts');\n</code></pre>\n\n<p>Change to </p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'oiw_remove_head_scripts' );\n</code></pre>\n\n<p>You can find <a href=\"https://ohiwill.com/move-javascript-to-footer-in-wordpress-improve-first-contentful-paint/\" rel=\"nofollow noreferrer\">reference here</a> and I've tested it and work`</p>\n"
}
] |
2015/02/17
|
[
"https://wordpress.stackexchange.com/questions/178376",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16412/"
] |
In order to speedup my site load and prevent scripts from render the page I'm trying to move all the **possible** scripts (meaning JS files) from `head` to `footer`. After read and do some research I made this code:
```
function footer_enqueue_scripts() {
remove_action('wp_head', 'wp_print_scripts');
remove_action('wp_head', 'wp_print_head_scripts', 9);
remove_action('wp_head', 'wp_enqueue_scripts', 1);
add_action('wp_footer', 'wp_print_scripts', 5);
add_action('wp_footer', 'wp_enqueue_scripts', 5);
add_action('wp_footer', 'wp_print_head_scripts', 5);
}
add_action('after_setup_theme', 'footer_enqueue_scripts');
```
But it's not working since some scripts still loaded at `head`, see the output below:
```
<head>
<link rel="stylesheet" type="text/css" href="http://elclarin.dev/wp-content/cache/minify/000000/d4587/default.include.993ea9.css" media="all" />
<script type="text/javascript" src="http://elclarin.dev/wp-content/cache/minify/000000/d4587/default.include.0fe0ac.js"></script>
....
<!-- Metas -->
<meta charset="utf-8">
<!-- JS Files -->
<script type="text/javascript" src="http://elclarin.dev/wp-content/themes/elclarin_v2/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="http://elclarin.dev/wp-content/themes/elclarin_v2/js/jquery.tools-1.2.7.min.js"></script>
<script type="text/javascript" src="http://elclarin.dev/wp-content/themes/elclarin_v2/js/prefixfree-1.0.6.min.js"></script>
<script type="text/javascript" src="http://elclarin.dev/wp-content/themes/elclarin_v2/js/modernizr.js"></script>
<!--[if lt IE 9]>
<script type="text/javascript" src="http://elclarin.dev/wp-content/themes/elclarin_v2/js/html5shiv.js"></script>
<![endif]-->
<!--[if (gte IE 6)&(lte IE 8)]>
<script type="text/javascript" src="http://elclarin.dev/wp-content/themes/elclarin_v2/js/selectivizr-1.0.2.min.js"></script>
<![endif]-->
<script type="text/javascript">
var TEMPLATEURL = 'http://elclarin.dev/wp-content/themes/elclarin_v2';
</script>
<!-- Generated by OpenX 2.8.9 -->
<script type='text/javascript' src='http://openx.elclarinweb.com/www/delivery/spcjs.php?id=2&target=_blank'></script>
<!-- Analytics Files -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-29394358-3']);
_gaq.push(['_trackPageview']);
_gaq.push(['elclarin._setAccount', 'UA-36592785-1']);
_gaq.push(['elclarin._trackPageview']);
_gaq.push(['elclarin._setAccount', 'UA-49334701-1']);
_gaq.push(['elclarin._trackPageview']);
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
...
</footer>
<script type='text/javascript' src='http://elclarin.dev/wp-includes/js/admin-bar.min.js?ver=4.1'></script>
<script type='text/javascript' src='http://elclarin.dev/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.2.1'></script>
<script type='text/javascript' src='http://elclarin.dev/wp-includes/js/hoverIntent.min.js?ver=r7'></script>
...
```
Any workaround on this topic? Live site for testing purposes is [here](http://elclarinweb.com)
**Update**
After **@Milo** tip I found that scripts as he said are not enqueued properly at theme in `header.php` file since I can see this:
```
<!-- JS Files -->
<script type="text/javascript" src="<?php echo TEMPLATEURL ?>/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="<?php echo TEMPLATEURL ?>/js/jquery.tools-1.2.7.min.js"></script>
<script type="text/javascript" src="<?php echo TEMPLATEURL ?>/js/prefixfree-1.0.6.min.js"></script>
<script type="text/javascript" src="<?php echo TEMPLATEURL ?>/js/modernizr.js"></script>
<!--[if lt IE 9]>
<script type="text/javascript" src="<?php echo TEMPLATEURL ?>/js/html5shiv.js"></script>
<![endif]-->
<!--[if (gte IE 6)&(lte IE 8)]>
<script type="text/javascript" src="<?php echo TEMPLATEURL ?>/js/selectivizr-1.0.2.min.js"></script>
<![endif]-->
<script type="text/javascript">
var TEMPLATEURL = '<?php echo TEMPLATEURL; ?>';
</script>
<script type="text/javascript" src="<?php echo TEMPLATEURL ?>/js/acciones.js"></script>
<!-- Generated by OpenX 2.8.9 -->
<script type='text/javascript' src='http://openx.elclarinweb.com/www/delivery/spcjs.php?id=2&target=_blank'></script>
<!-- Analytics Files -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-29394358-3']);
_gaq.push(['_trackPageview']);
_gaq.push(['elclarin._setAccount', 'UA-36592785-1']);
_gaq.push(['elclarin._trackPageview']);
_gaq.push(['elclarin._setAccount', 'UA-49334701-1']);
_gaq.push(['elclarin._trackPageview']);
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
<!-- WP Files -->
<?php wp_head(); ?>
```
My question regarding those includes (I'm not the developer of theme but I'm pretty sure this can be fixed): what's the right|proper way to load them without break the theme and keeping performance and page speedup in mind?
|
IMHO, I still think that loading scripts and styles directly in the header is bad practice as it is always a problem removing them and loading them coditionally.
The best way to work around this is to create a [child theme] and then copy `header.php` to your child theme. Wordpress will load your child theme's header instead of the parent theme's header.
You can now delete all the scripts from your header and properly enqueue and register them through the [`wp_enqueue_scripts`](http://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts) hook in your child theme `functions.php`. Just remember to set the `$in_footer` parameter in the [`wp_enqueue_script()`](http://codex.wordpress.org/Function_Reference/wp_enqueue_script) and [`wp_register_script()`](http://codex.wordpress.org/Function_Reference/wp_register_script) functions to `true
EDIT
----
From your [linked `header.php`](https://gist.github.com/paquitodev/ff96fe0cce53334a6e2f), your scripts is added between lines 56 - 95. This you will need to delete. If you visit the site, you will not see any jquery being loaded.
Thenbuild in jquery library is already being loaded, no need to worry about that. The rest you need to enqueue yourself. Here is an example (*Remember, each script should have a unique handle, so name them something that is unique that will not create conflict*)
```
add_action('wp_enqueue_scripts', 'enqueue_my_scripts');
function enqueue_my_scripts()
{
wp_enqueue_script('jquery-tools', get_template_directory_uri() . '/js/jquery.tools.js-1.2.7.min.js', array('jquery'), false, true);
//Do the same for the other scripts
}
```
Notice I have used `get_template_directory_uri()` here as you will be leaving your js folder in your parent theme. You can, however, move your js folder to your child theme, but then you will need to use `get_stylesheet_directory_uri()`
NOTES ON THE CONDITIONAL SCRIPTS
--------------------------------
There is still, after four years after being raised, no build in way to load scripts conditionally according to IE browser like there is for styles. You can check out the trac ticket and another question raising this same issue [here](https://wordpress.stackexchange.com/a/54331/31545)
I have never tried loading scripts conditionally according to browser, so I cannot comment on this section or state whether any solution work which is mentioned in the linked answer or trac ticket. What I can tell you, if the solutions don't work, you will need to copy `footer.php` to your child theme and then move lines 61 -66 from your header to your footer
NOTES ON THE SCRIPT LINES 67 -69
--------------------------------
This sections passes a php variable to jquery. The correct way to do this will be to use [`wp_localize_script()`](http://codex.wordpress.org/Function_Reference/wp_localize_script). You will need to contact the developer here for assistance as this is frankly theme related, and I do really not know where this is actually used in your scripts. Check out the link also for usage and info
NOTES ON THE ANALYTICS SCRIPT LINES 75 - 94
-------------------------------------------
You will need to create a js file for this section. If you haven't copied the js folder from the parent to your child theme, create a new js folder for your child theme. Open it up and create a new js file and call it what you like, something like `analytics.script.js`.
Next you will move everything inside the script tags to this folder, this is lines 77 - 92. Be sure to use the no conflict wrapper to wrap this script in as described [here](http://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_Wrappers)
You can just enqueue this script as normal as described earlier, just remember to use `get_stylesheet_directory_uri()` and not `get_template_directory_uri()`
EDIT 2
------
The patch from the linked answer under *NOTES ON THE CONDITIONAL SCRIPTS* does not work, it is not yet implemented and as I said in comments, it will most probably not be included in version 10 in a 100 years time :-). Unfortunately you will need to live with this, there is just no way to achieve this at present. This is really the draw back for supporting IE6 - 8. Well, to be honest, if you still support IE6 and 7, you are fighting a battle that was lost long ago. All major software developers has dropped IE6 (this includes Wordpress), IE7 was dropped by Microsoft themselves, so software developers will follow soon, and IE 8 will not live to see end 2016 IMHO
To overcome this compatibility issue with jquery, it might be better to stick with what the theme itself offers
You can try something like this
```
add_action('wp_enqueue_scripts', 'enqueue_my_scripts', PHP_INT_MAX);
function enqueue_my_scripts()
{
/**
* Make sure, get_template_directory_uri() if script stays in parent theme
* Use get_stylesheet_directory_uri() if script is in child theme
*/
wp_enqueue_script('jquery-min', get_template_directory_uri() . '/js/jquery-1.7.2.min.js', array(), false, true);
wp_enqueue_script('jquery-tools', get_template_directory_uri() . '/js/jquery.tools.js-1.2.7.min.js', array('jquery-min'), false, true);
wp_enqueue_script('prefixfree', get_template_directory_uri() . '/js/prefixfree-1.0.6.min.js', array(), false, true);
wp_enqueue_script('modernizr', get_template_directory_uri() . '/js/modernizr.js', array(), false, true);
/**
* The two conditional scripts which there is no work around for, load them or drop support
*/
wp_enqueue_script('html5shiv', get_template_directory_uri() . '/js/html5shiv.js', array(), false, true);
wp_enqueue_script('selectivizr', get_template_directory_uri() . '/js/selectivizr-1.0.2.min.js', array(), false, true);
wp_enqueue_script('acciones', get_template_directory_uri() . '/js/acciones.js', array(), false, true);
wp_enqueue_script('openx', 'http://openx.elclarinweb.com/www/delivery/spcjs.php?id=2&target=_blank', array(), false, true);
wp_enqueue_script('analytics', get_stylesheet_directory_uri() . '/js/analytics.script.js', array(), false, true);
}
```
As I said before, there is a php variable passed to a script which you should talk to the theme author about. Also, any compatibility issues should be further discussed with the them authors. This is the correct layout and should in theory work. For any other theme related and compatibility issues, feel free to contact the theme author for support
EDIT 3
------
This is how your child theme header.php should look like
```
<!DOCTYPE html>
<html itemscope itemtype="http://schema.org/Blog">
<head>
<!-- Metas -->
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="google-site-verification" content="V022hygXU9AHEdTBX2BFnTBYeo4SsaTjC7aGdoIMPL4"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<meta name="description" content="<?php bloginfo( 'description' ); ?>">
<?php if (is_single()) { ?>
<meta property="og:title" content="<?php the_title(); ?>"/>
<meta itemprop="name" content="<?php the_title(); ?>">
<meta property="og:type" content="article"/>
<meta property="og:url" content="<?php the_permalink(); ?>"/>
<?php
if (has_post_thumbnail()) {
$src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), array( 490, 290 ), false );
?>
<meta property="og:image" content="<?php echo $src[0]; ?>"/>
<meta itemprop="image" content="<?php echo $src[0]; ?>">
<?php } else { ?>
<meta property="og:image" content="<?php echo TEMPLATEURL; ?>/images/logo.png"/>
<meta itemprop="image" content="<?php echo TEMPLATEURL; ?>/images/logo.png">
<?php } ?>
<meta property="og:site_name" content="<?php bloginfo( 'name' ); ?>"/>
<meta itemprop="description" content="<?php the_excerpt(); ?>">
<?php } ?>
<!-- Title -->
<title>
<?php
if (isset($wp_query->query_vars['b'])) {
echo str_replace( "+", " ", $wp_query->query_vars['b'] )." | ";
}
wp_title( '|', true, 'right' );
bloginfo( 'name' );
if (isset($paged) && $paged >= 2 || isset($page) && $page >= 2 || isset($page_alt) && $page_alt >= 2) {
echo ' | '.sprintf( 'Página %s', max( $paged, $page, $page_alt ) );
}
?>
</title>
<!-- Stylesheets & others -->
<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>?version=4"/>
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>"/>
<link rel="alternate" type="application/rss+xml" title="RSS" href="<?php echo SITEURL; ?>/feed/"/>
<link rel="alternate" type="application/atom+xml" title="Atom" href="<?php echo SITEURL; ?>/feed/atom/"/>
<link rel="shortcut icon" href="<?php echo TEMPLATEURL ?>/images/favicon.ico"/>
<link rel="shortcut icon" href="<?php echo TEMPLATEURL ?>/images/favicon.png"/>
<link rel="apple-shortcut icon" href="<?php echo TEMPLATEURL ?>/images/favicon_iphone.png"/>
<link rel="apple-touch-icon-precomposed" href="<?php echo TEMPLATEURL ?>/images/favicon_iphone.png">
<link rel="apple-touch-icon" href="<?php echo TEMPLATEURL ?>/images/favicon_iphone.png">
<!-- WP Files -->
<?php wp_head(); ?>
</head>
<body>
<div class="for_overlays">
<?php
if (is_front_page()) {
$prepost = $post;
$normal_args = Array(
'post_type' => 'portadadeldia',
'post_status' => 'publish',
'posts_per_page' => 1
);
$normal_query = new WP_Query( $normal_args );
if ($normal_query->have_posts()) {
while ($normal_query->have_posts()) {
$normal_query->the_post();
?>
<?php
if (has_post_thumbnail()) {
$large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
?>
<div id="portadadeldia" class="from_overlay">
<a href="<?php echo $large_image_url[0]; ?>" target="_blank">
<?php echo get_the_post_timthumbnail(
$post->ID,
'portadadeldia_frontpage_overlay',
array( 'alt' => trim( get_the_title() ), 'title' => trim( get_the_title() ) )
); ?>
</a>
</div>
<?php } ?>
<?php
}
}
$post = $prepost;
wp_reset_postdata();
}
?>
<svg>
<filter id="firefoxblur">
<feGaussianBlur stdDeviation="4"/>
</filter>
</svg>
</div>
<header>
<div class="center_content">
<div id="header_publicity" class="publicity">
<span>Publicidad</span>
<div>
<script type='text/javascript'><!--// <![CDATA[
/* [id18] Header Top */
OA_show(18);
// ]]> --></script>
<noscript><a target='_blank' href='http://openx.elclarinweb.com/www/delivery/ck.php?n=1073df0'><img
border='0' alt=''
src='http://openx.elclarinweb.com/www/delivery/avw.php?zoneid=18&n=1073df0'/></a>
</noscript>
</div>
</div>
<h1 id="header_logo"><a href="<?php echo SITEURL; ?>">
<?php
$prepost = $post;
$normal_args = Array(
'post_status' => 'publish',
'posts_per_page' => 1,
'post_type' => 'logos',
);
$normal_query = new WP_Query( $normal_args );
if ($normal_query->have_posts()) {
$normal_query->the_post();
$thumbnail_id = get_post_thumbnail_id( $post->ID );
$thumbnail_object = get_post( $thumbnail_id );
$url = $thumbnail_object->guid;
?><img src="<?PHP echo $url; ?>" alt="<?php bloginfo( 'name' ); ?>"><?php
} else {
?><img src="<?PHP echo TEMPLATEURL; ?>/images/logo.png" alt="<?php bloginfo( 'name' ); ?>"><?php
}
$post = $prepost;
wp_reset_postdata();
?>
</a></h1>
<?php custom_secondary_nav( "executive_menu", 'header_lateral_superior', 'Menú corporativo' ); ?>
<div id="header_lateral_inferior">
<div id="header_buscador" role="search" title="Buscar">
<div id="header_buscador_inner">
<form method="get" action="<?php echo SITEURL; ?>">
Buscar
<input title="Buscar" type="text" name="s"
value="<?php echo str_replace( "+", " ", $wp_query->query_vars['s'] ); ?>">
</form>
</div>
</div>
<div id="header_redes">
<a href="http://twitter.com/elclarin_aragua" target="_blank"><img
src="<?php echo TEMPLATEURL ?>/images/icons/tw.png"></a>
<a href="<?php echo SITEURL; ?>/rss" target="_blank"><img
src="<?php echo TEMPLATEURL ?>/images/icons/rs.png"></a>
<a href="<?php echo SITEURL; ?>"><img src="<?php echo TEMPLATEURL ?>/images/icons/ho.png"></a>
</div>
</div>
<div id="header_menu">
<?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_id' => 3 ) ); ?>
</div>
</div>
</header>
<div role="main" id="main" class="main">
<div class="center_content">
```
|
178,386 |
<p>Bit of a odd question. I want to be able to host example simple websites on my Wordpress Site. These "simple" sites would just consist of client side code.</p>
<p>Is there a way to create a page which just uses these files, possible a plugin I am unaware of?</p>
<p>Thank you.</p>
|
[
{
"answer_id": 178394,
"author": "Florian Grell",
"author_id": 66399,
"author_profile": "https://wordpress.stackexchange.com/users/66399",
"pm_score": 0,
"selected": false,
"text": "<p>Create a directory named <em>(for example)</em> <code>example</code> in the root directory of your domain (where the WordPress <code>index.php</code> lives).</p>\n\n<p>In that directory you can create your \"simple\" sites.\nSo if you create a HTML document named <code>mysite.htm</code> and visit <code>yourdomain.com/example/mysite.htm</code> the browser should display that page.</p>\n\n<p>This is the default webserver behaviour - no need for a plugin.</p>\n"
},
{
"answer_id": 178454,
"author": "chantron",
"author_id": 45530,
"author_profile": "https://wordpress.stackexchange.com/users/45530",
"pm_score": 3,
"selected": true,
"text": "<p>I've done this in the past by using <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">custom page templates</a>.</p>\n<p>Basically, there are two ways to create a custom page template.</p>\n<ol>\n<li><p>You can create a file in your themes directory and name it <code>page-vanilla-html.php</code>.</p>\n</li>\n<li><p>You can create a file and name it whatever you want (for example <code>vanilla-html.php</code>). You just need to include a template description at the top of the file:</p>\n<pre><code> <?php\n /*\n * Template Name: A Vanilla HTML/CSS/JS Custom Page Template\n * Description: This template is nothing but vanilla HTML/CSS/JS!\n */\n ?>\n</code></pre>\n</li>\n</ol>\n<p>Once you've created the custom template, you simply create a new page within Wordpress. If the name of the page is "Vanilla HTML" it will search for a file named <code>page-vanilla-html.php</code> and load it automatically. If you used the second method, you can select the template from the drop down on the right side of the page creation screen.</p>\n"
}
] |
2015/02/17
|
[
"https://wordpress.stackexchange.com/questions/178386",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44487/"
] |
Bit of a odd question. I want to be able to host example simple websites on my Wordpress Site. These "simple" sites would just consist of client side code.
Is there a way to create a page which just uses these files, possible a plugin I am unaware of?
Thank you.
|
I've done this in the past by using [custom page templates](https://developer.wordpress.org/themes/template-files-section/page-template-files/).
Basically, there are two ways to create a custom page template.
1. You can create a file in your themes directory and name it `page-vanilla-html.php`.
2. You can create a file and name it whatever you want (for example `vanilla-html.php`). You just need to include a template description at the top of the file:
```
<?php
/*
* Template Name: A Vanilla HTML/CSS/JS Custom Page Template
* Description: This template is nothing but vanilla HTML/CSS/JS!
*/
?>
```
Once you've created the custom template, you simply create a new page within Wordpress. If the name of the page is "Vanilla HTML" it will search for a file named `page-vanilla-html.php` and load it automatically. If you used the second method, you can select the template from the drop down on the right side of the page creation screen.
|
178,405 |
<p>I cannot seem to save the value of a checkbox in a plugin I am creating. When I uncheck it and click Save Settings, it reverts to being checked again.
I'm not sure where I have gone wrong. Any help would be most appreciated. </p>
<pre><code>//Global Variable
$options = array();
//Options Page
function iwmp_options_page() {
if( !current_user_can('manage_options') ) {
wp_die('You do not have sufficient permission to access this page.');
}
global $options;
if( isset($_POST['iwmp_settings_form_submitted']) ) {
$hidden_field = esc_html( $_POST['iwmp_settings_form_submitted'] );
if($hidden_field == "Y") {
$iwmp_single_images = esc_html( $POST['iwmp_single_images'] );
$options['iwmp_single_images'] = $iwmp_single_images;
update_option('iwmp_settings', $options);
}
}
$options = get_option('iwmp_settings');
if( $options != '' ) {
$iwmp_single_images = $options['iwmp_single_images'];
}
require('plugin-settings-page-wrapper.php');
}
</code></pre>
<p>Inside the 'plugin-settings-page-wrapper.php' file: (Stripped down of course)</p>
<pre><code><label for="iwmp_single_images">Enable on Single Images:
<input checked="checked" name="iwmp_single_images" type="checkbox" id="iwmp_single_images" value="1" <? checked( $options['iwmp_single_images'], 1, false );?> />
</label>
</code></pre>
|
[
{
"answer_id": 178506,
"author": "Nikola Ivanov Nikolov",
"author_id": 23604,
"author_profile": "https://wordpress.stackexchange.com/users/23604",
"pm_score": 3,
"selected": true,
"text": "<p>If a checkbox is unchecked, it doesn't get submitted with the form values. So when using checkboxes, you should have an <code>else</code> statement for <code>isset( $_POST['iwmp_settings_form_submitted'] )</code> and it basically will be triggered when the checkbox is unchecked. Here's the fixed code. </p>\n\n<pre><code>//Global Variable\n$options = array();\n\n//Options Page\nfunction iwmp_options_page() {\n\n if( ! current_user_can( 'manage_options' ) ) {\n wp_die( 'You do not have sufficient permission to access this page.' );\n }\n\n global $options;\n\n // Make sure this is a POST request\n if ( 'POST' == $_SERVER['REQUEST_METHOD'] ) {\n if ( ! isset( $_POST['_iwmp_nonce'] ) || ! wp_verify_nonce( $_POST['_iwmp_nonce'], 'iwmp_settings_nonce' ) ) {\n wp_die( 'Cheating, Huh?' );\n }\n\n if( isset($_POST['iwmp_settings_form_submitted']) ) {\n\n $hidden_field = esc_html( $_POST['iwmp_settings_form_submitted'] );\n\n if($hidden_field == \"Y\") {\n\n if ( isset( $_POST['iwmp_single_images'] ) ) {\n $options['iwmp_single_images'] = esc_html( $_POST['iwmp_single_images'] );\n } else {\n $options['iwmp_single_images'] = '';\n }\n\n update_option('iwmp_settings', $options);\n\n }\n\n }\n\n }\n\n $options = get_option('iwmp_settings');\n\n if( $options != '' ) {\n\n $iwmp_single_images = $options['iwmp_single_images'];\n\n }\n\n require('plugin-settings-page-wrapper.php');\n\n}\n</code></pre>\n\n<p>I also added a nonce validation in your code(because they're a good practice). In addition to the extra code below, you should also add the following code inside of your <code><form></code> in your settings page HTML: </p>\n\n<p><code><?php wp_nonce_field( 'iwmp_settings_nonce', '_iwmp_nonce' ); ?></code></p>\n\n<p>Using nonces is a good practice that makes your plugin more secure. You can read more on Nonces here: <a href=\"http://codex.wordpress.org/WordPress_Nonces\" rel=\"nofollow\">http://codex.wordpress.org/WordPress_Nonces</a> </p>\n\n<p>And the code for your checkbox should be as follows: </p>\n\n<p><code><input name=\"iwmp_single_images\" type=\"checkbox\" id=\"iwmp_single_images\" value=\"1\" <?php checked( $options['iwmp_single_images'], 1 ); ?> /></code></p>\n"
},
{
"answer_id": 178509,
"author": "cristian.raiber",
"author_id": 52524,
"author_profile": "https://wordpress.stackexchange.com/users/52524",
"pm_score": 1,
"selected": false,
"text": "<p>Adding to what @Nikola Ivanov Nikolov said you shouldn't be formatting your input like this:</p>\n\n<pre><code> <input checked=\"checked\">\n</code></pre>\n\n<p>Basically, what you've done, you've made the checkbox be always checked (notice the <code>checked=\"checked\"</code> value).</p>\n\n<p>Instead, you should be using: </p>\n\n<pre><code><input type=\"checkbox\" name=\"iwmp_single_images\" value=\"1\" <?php checked( $options['iwmp_single_images'], 1 ); ?> />\n</code></pre>\n"
},
{
"answer_id": 340563,
"author": "Ajay Malhotra",
"author_id": 118989,
"author_profile": "https://wordpress.stackexchange.com/users/118989",
"pm_score": 0,
"selected": false,
"text": "<p>I got work like below code:</p>\n\n<pre><code> <input type=\"checkbox\" name=\"new_option_name\" value=\"1\" <?php checked( esc_attr( get_option('new_option_name')), 1 );?> /></td>\n</code></pre>\n\n<p>Hope this will help you..</p>\n"
}
] |
2015/02/17
|
[
"https://wordpress.stackexchange.com/questions/178405",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57571/"
] |
I cannot seem to save the value of a checkbox in a plugin I am creating. When I uncheck it and click Save Settings, it reverts to being checked again.
I'm not sure where I have gone wrong. Any help would be most appreciated.
```
//Global Variable
$options = array();
//Options Page
function iwmp_options_page() {
if( !current_user_can('manage_options') ) {
wp_die('You do not have sufficient permission to access this page.');
}
global $options;
if( isset($_POST['iwmp_settings_form_submitted']) ) {
$hidden_field = esc_html( $_POST['iwmp_settings_form_submitted'] );
if($hidden_field == "Y") {
$iwmp_single_images = esc_html( $POST['iwmp_single_images'] );
$options['iwmp_single_images'] = $iwmp_single_images;
update_option('iwmp_settings', $options);
}
}
$options = get_option('iwmp_settings');
if( $options != '' ) {
$iwmp_single_images = $options['iwmp_single_images'];
}
require('plugin-settings-page-wrapper.php');
}
```
Inside the 'plugin-settings-page-wrapper.php' file: (Stripped down of course)
```
<label for="iwmp_single_images">Enable on Single Images:
<input checked="checked" name="iwmp_single_images" type="checkbox" id="iwmp_single_images" value="1" <? checked( $options['iwmp_single_images'], 1, false );?> />
</label>
```
|
If a checkbox is unchecked, it doesn't get submitted with the form values. So when using checkboxes, you should have an `else` statement for `isset( $_POST['iwmp_settings_form_submitted'] )` and it basically will be triggered when the checkbox is unchecked. Here's the fixed code.
```
//Global Variable
$options = array();
//Options Page
function iwmp_options_page() {
if( ! current_user_can( 'manage_options' ) ) {
wp_die( 'You do not have sufficient permission to access this page.' );
}
global $options;
// Make sure this is a POST request
if ( 'POST' == $_SERVER['REQUEST_METHOD'] ) {
if ( ! isset( $_POST['_iwmp_nonce'] ) || ! wp_verify_nonce( $_POST['_iwmp_nonce'], 'iwmp_settings_nonce' ) ) {
wp_die( 'Cheating, Huh?' );
}
if( isset($_POST['iwmp_settings_form_submitted']) ) {
$hidden_field = esc_html( $_POST['iwmp_settings_form_submitted'] );
if($hidden_field == "Y") {
if ( isset( $_POST['iwmp_single_images'] ) ) {
$options['iwmp_single_images'] = esc_html( $_POST['iwmp_single_images'] );
} else {
$options['iwmp_single_images'] = '';
}
update_option('iwmp_settings', $options);
}
}
}
$options = get_option('iwmp_settings');
if( $options != '' ) {
$iwmp_single_images = $options['iwmp_single_images'];
}
require('plugin-settings-page-wrapper.php');
}
```
I also added a nonce validation in your code(because they're a good practice). In addition to the extra code below, you should also add the following code inside of your `<form>` in your settings page HTML:
`<?php wp_nonce_field( 'iwmp_settings_nonce', '_iwmp_nonce' ); ?>`
Using nonces is a good practice that makes your plugin more secure. You can read more on Nonces here: <http://codex.wordpress.org/WordPress_Nonces>
And the code for your checkbox should be as follows:
`<input name="iwmp_single_images" type="checkbox" id="iwmp_single_images" value="1" <?php checked( $options['iwmp_single_images'], 1 ); ?> />`
|
178,416 |
<p>I searched in various places and am battling to find the correct place or terms used for the following.</p>
<p>I am only using posts as an example.</p>
<p>When you view all posts in wp-admin you get the title of the post and below it the Edit, Quick Edit, Trash and Preview links. By using the post_row_actions action hook I can change the links below the title but not the link on the title itself. </p>
<p>Are there an alternate way to change the link on the post title to open a different url? or can I change it with the same hook?</p>
<p>I am developing front-end content management screen and want to point all edit links to point to the front of the website. </p>
<p>Many thanks :)</p>
|
[
{
"answer_id": 178421,
"author": "mjakic",
"author_id": 67333,
"author_profile": "https://wordpress.stackexchange.com/users/67333",
"pm_score": 4,
"selected": true,
"text": "<p>Use <a href=\"https://core.trac.wordpress.org/browser/tags/4.1/src/wp-includes/link-template.php#L1193\" rel=\"noreferrer\"><code>get_edit_post_link</code> filter</a>.</p>\n\n<pre><code>add_filter('get_edit_post_link', 'get_edit_post_link_178416', 99, 3);\n\nfunction get_edit_post_link_178416($link, $post_id, $context) {\n $scr = get_current_screen();\n\n if ($scr->id == 'edit-post' && $context == 'display') {\n return 'http://google.com';\n } else {\n return $link;\n }\n}\n</code></pre>\n\n<p>You can see it's used <a href=\"https://core.trac.wordpress.org/browser/tags/4.1/src/wp-includes/link-template.php#L1193\" rel=\"noreferrer\">here</a></p>\n"
},
{
"answer_id": 178423,
"author": "geomagas",
"author_id": 39275,
"author_profile": "https://wordpress.stackexchange.com/users/39275",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>I am developing front-end content management screen and want to point\n all edit links to point to the front of the website.</p>\n</blockquote>\n\n<p>If you want to point all edit links to the FE, you should go for the <code>get_edit_post_link</code> filter solution (see Marko's answer). That will cover all cases where either the core or a plugin calls <a href=\"http://codex.wordpress.org/Template_Tags/get_edit_post_link\" rel=\"nofollow\"><code>get_edit_post_link()</code></a>.</p>\n\n<p>But if you want to implement \"proper\" front-end content management, you should go beyond that. I've seen plugins that bypass the API and hardcode the edit post url calculation. Moreover, there's always a chance that a user could type the admin url and land on the default edit post admin screen.</p>\n\n<p>So I think you should redirect the default post edit url to your frontend:</p>\n\n<pre><code>add_action(\n 'admin_init',\n function()\n {\n global $pagenow;\n if($pagenow=='post.php'\n && isset($_GET['action']) && $_GET['action']=='edit'\n && isset($_GET['post']))\n {\n $post_id=$_GET['post'];\n // calculate $fe_edit_screen using $post_id\n wp_redirect($fe_edit_screen);\n exit;\n }\n },\n 1\n );\n</code></pre>\n\n<p>This way, everyone will be redirected to your frontend, no matter how they ended up accessing the post edit screen. Moreover, you could add more checks, in case for example you want to redirect only users that have (or don't have) specific capabilities, or only for certain post types, or whatever.</p>\n"
}
] |
2015/02/17
|
[
"https://wordpress.stackexchange.com/questions/178416",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63672/"
] |
I searched in various places and am battling to find the correct place or terms used for the following.
I am only using posts as an example.
When you view all posts in wp-admin you get the title of the post and below it the Edit, Quick Edit, Trash and Preview links. By using the post\_row\_actions action hook I can change the links below the title but not the link on the title itself.
Are there an alternate way to change the link on the post title to open a different url? or can I change it with the same hook?
I am developing front-end content management screen and want to point all edit links to point to the front of the website.
Many thanks :)
|
Use [`get_edit_post_link` filter](https://core.trac.wordpress.org/browser/tags/4.1/src/wp-includes/link-template.php#L1193).
```
add_filter('get_edit_post_link', 'get_edit_post_link_178416', 99, 3);
function get_edit_post_link_178416($link, $post_id, $context) {
$scr = get_current_screen();
if ($scr->id == 'edit-post' && $context == 'display') {
return 'http://google.com';
} else {
return $link;
}
}
```
You can see it's used [here](https://core.trac.wordpress.org/browser/tags/4.1/src/wp-includes/link-template.php#L1193)
|
178,433 |
<p>I'm searching for science related terms. Here's what I need my query to do. If someone searches 'bio', they should not get results for terms 'biology' but they should for 'bio science'. I need the query to return results for the whole word. Any suggestions are appreciated. Thanks!</p>
<p>Here is my code:</p>
<pre><code> $queryArgs = array(
'post_type' => 'faculty',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'proposed_keywords', // name of custom field
'value' => $keyword, // matches exaclty "123", not just 123. This prevents a match for "1234"
'compare' => 'LIKE'
)
)
);
</code></pre>
|
[
{
"answer_id": 178439,
"author": "geomagas",
"author_id": 39275,
"author_profile": "https://wordpress.stackexchange.com/users/39275",
"pm_score": 3,
"selected": true,
"text": "<p>You're gonna need regular expressions to accomplish that.</p>\n\n<p>First of all, you need to change <code>'LIKE'</code> to <code>'RLIKE'</code> (or <code>'REGEXP'</code>).</p>\n\n<p>Second, replace <code>$keyword</code> in <code>'value'</code> with a regex that involves word boundaries.</p>\n\n<p>Like so:</p>\n\n<pre><code> $queryArgs = array(\n 'post_type' => 'faculty',\n 'posts_per_page' => -1,\n 'meta_query' => array(\n 'relation' => 'OR',\n array( \n 'key' => 'proposed_keywords', // name of custom field\n 'value' => \"[[:<:]]$keyword[[:>:]]\", // matches exaclty \"123\", not just 123. This prevents a match for \"1234\"\n 'compare' => 'RLIKE'\n )\n )\n );\n</code></pre>\n"
},
{
"answer_id": 221294,
"author": "john",
"author_id": 45140,
"author_profile": "https://wordpress.stackexchange.com/users/45140",
"pm_score": 1,
"selected": false,
"text": "<p>The above 500's on me (wp-engine) so instead I used:</p>\n\n<pre><code>'value' => '[[:<:]]'.$keyword.'[[:>:]]',\n'compare' => 'REGEXP'\n</code></pre>\n\n<p>Which works fine :-)</p>\n"
}
] |
2015/02/17
|
[
"https://wordpress.stackexchange.com/questions/178433",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37809/"
] |
I'm searching for science related terms. Here's what I need my query to do. If someone searches 'bio', they should not get results for terms 'biology' but they should for 'bio science'. I need the query to return results for the whole word. Any suggestions are appreciated. Thanks!
Here is my code:
```
$queryArgs = array(
'post_type' => 'faculty',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'proposed_keywords', // name of custom field
'value' => $keyword, // matches exaclty "123", not just 123. This prevents a match for "1234"
'compare' => 'LIKE'
)
)
);
```
|
You're gonna need regular expressions to accomplish that.
First of all, you need to change `'LIKE'` to `'RLIKE'` (or `'REGEXP'`).
Second, replace `$keyword` in `'value'` with a regex that involves word boundaries.
Like so:
```
$queryArgs = array(
'post_type' => 'faculty',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'proposed_keywords', // name of custom field
'value' => "[[:<:]]$keyword[[:>:]]", // matches exaclty "123", not just 123. This prevents a match for "1234"
'compare' => 'RLIKE'
)
)
);
```
|
178,437 |
<p>I'm trying to make a couple of Page Templates for different Pages that should act as an archive to display posts (a Custom Post Type actually) in a certain date range.</p>
<p>The website it concerns is <a href="http://memstories.com" rel="nofollow">http://memstories.com</a> and the CPT is "Events". I already found some mentions of a thread on WP Support (<a href="https://wordpress.org/support/topic/show-the-posts-published-before-a-specific-date?replies=2#post-1066144" rel="nofollow">https://wordpress.org/support/topic/show-the-posts-published-before-a-specific-date?replies=2#post-1066144</a>), but I cannot get it to work:</p>
<pre><code><?php
function filter_where($where = '') {
$where .= " AND post_date >= '1900-01-01' AND post_date <= '1949-12-31'";
return $where;
}
add_filter('posts_where', 'filter_where');
query_posts($query_string);
?>
</code></pre>
<p>Because the Event posts on this website are all historic events, I'm using the Published Date as the actual date a historic event happened and I'm going as far back as the year 1900. In the above query I'm trying to accomplish a list of posts that fit within the date range of the first half of the 20th century (1900 - 1949), but it's a fail any way I try it.</p>
<p>There really isn't anywhere else I can find more information, in fact all similar questions on stackexchange are answered with a link to the exact same thread (5 years old!) on Wordpress Support. </p>
<p>Anyone have an idea how to work this out?</p>
|
[
{
"answer_id": 178441,
"author": "Sean Grant",
"author_id": 67105,
"author_profile": "https://wordpress.stackexchange.com/users/67105",
"pm_score": 1,
"selected": false,
"text": "<p>Well, WP may be suppressing your filter.</p>\n\n<p>Per the WP Codex on posts_where @: <a href=\"http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where\" rel=\"nofollow\">http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where</a></p>\n\n<blockquote>\n <p>Certain functions which retrieve posts do not run filters, so the posts_where filter functions you attach will not modify the query. To overcome this, set suppress_filters to false in the argument array passed to the function.</p>\n</blockquote>\n\n<p>This is the code they reference:</p>\n\n<pre><code>//get posts AND make sure filters are NOT suppressed\n$posts = get_posts( array( 'suppress_filters' => FALSE ) );\n</code></pre>\n\n<p>Are you using this on your get_posts() call ?</p>\n"
},
{
"answer_id": 178442,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 3,
"selected": true,
"text": "<p>Saving the date in post meta is a slightly more sane approach, the <code>post_date</code> column was not designed with your use case in mind. You may get weird results with dates before the Unix epoch (January 1, 1970). Then it's just a simple <code>meta_query</code> to load posts between dates, no filter necessary.</p>\n\n<pre><code>$start = '1900-01-01';\n$end = '1949-12-31';\n$args = array(\n 'post_type' => 'events',\n 'posts_per_page' => -1,\n 'orderby' => 'meta_value',\n 'order' => 'ASC',\n 'meta_key' => '_event_date',\n 'meta_query' => array(\n array(\n 'key' => '_event_date',\n 'value' => array( $start, $end ),\n 'compare' => 'BETWEEN',\n 'type' => 'DATE'\n )\n )\n);\n$events_query = new WP_query( $args );\n</code></pre>\n"
}
] |
2015/02/17
|
[
"https://wordpress.stackexchange.com/questions/178437",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35523/"
] |
I'm trying to make a couple of Page Templates for different Pages that should act as an archive to display posts (a Custom Post Type actually) in a certain date range.
The website it concerns is <http://memstories.com> and the CPT is "Events". I already found some mentions of a thread on WP Support (<https://wordpress.org/support/topic/show-the-posts-published-before-a-specific-date?replies=2#post-1066144>), but I cannot get it to work:
```
<?php
function filter_where($where = '') {
$where .= " AND post_date >= '1900-01-01' AND post_date <= '1949-12-31'";
return $where;
}
add_filter('posts_where', 'filter_where');
query_posts($query_string);
?>
```
Because the Event posts on this website are all historic events, I'm using the Published Date as the actual date a historic event happened and I'm going as far back as the year 1900. In the above query I'm trying to accomplish a list of posts that fit within the date range of the first half of the 20th century (1900 - 1949), but it's a fail any way I try it.
There really isn't anywhere else I can find more information, in fact all similar questions on stackexchange are answered with a link to the exact same thread (5 years old!) on Wordpress Support.
Anyone have an idea how to work this out?
|
Saving the date in post meta is a slightly more sane approach, the `post_date` column was not designed with your use case in mind. You may get weird results with dates before the Unix epoch (January 1, 1970). Then it's just a simple `meta_query` to load posts between dates, no filter necessary.
```
$start = '1900-01-01';
$end = '1949-12-31';
$args = array(
'post_type' => 'events',
'posts_per_page' => -1,
'orderby' => 'meta_value',
'order' => 'ASC',
'meta_key' => '_event_date',
'meta_query' => array(
array(
'key' => '_event_date',
'value' => array( $start, $end ),
'compare' => 'BETWEEN',
'type' => 'DATE'
)
)
);
$events_query = new WP_query( $args );
```
|
178,455 |
<p>The <code><title></code> of each page on my site shows correctly with the following code:</p>
<pre><code><title><?php wp_title(''); ?></title>
</code></pre>
<p>But on my home page, which is set to a static page called 'Home', the <code><title></code> attribute is blank. The HTML for 'Home' page looks like this:</p>
<pre><code><title></title>
</code></pre>
<p>The settings for the 'Home' page has 'Home' as the page title, but it doesn't show on the actual page output. Any idea why? The issue can be seen <a href="https://www.dcturano.com/" rel="nofollow">here</a>.</p>
|
[
{
"answer_id": 178457,
"author": "czerspalace",
"author_id": 47406,
"author_profile": "https://wordpress.stackexchange.com/users/47406",
"pm_score": 3,
"selected": true,
"text": "<p>From the <a href=\"http://codex.wordpress.org/Function_Reference/wp_title#Covering_Homepage\" rel=\"nofollow\">Codex</a></p>\n\n<p><code>If you are using a custom homepage with custom loops and stuff or a custom front-page, you will have an empty wp_title. Here goes a neat hack to add the description/tagline at the wp_title place on homepage:</code></p>\n\n<pre><code>add_filter( 'wp_title', 'baw_hack_wp_title_for_home' );\nfunction baw_hack_wp_title_for_home( $title )\n{\n if( empty( $title ) && ( is_home() || is_front_page() ) ) {\n return __( 'Home', 'theme_domain' ) . ' | ' . get_bloginfo( 'description' );\n }\n return $title;\n}\n</code></pre>\n"
},
{
"answer_id": 269182,
"author": "akvenk",
"author_id": 101336,
"author_profile": "https://wordpress.stackexchange.com/users/101336",
"pm_score": 0,
"selected": false,
"text": "<p>This works for me, place it in header.php:</p>\n\n<pre><code><title><?php wp_title('');?><?php if(is_front_page()) {bloginfo('name');}?></title>\n</code></pre>\n"
}
] |
2015/02/17
|
[
"https://wordpress.stackexchange.com/questions/178455",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34397/"
] |
The `<title>` of each page on my site shows correctly with the following code:
```
<title><?php wp_title(''); ?></title>
```
But on my home page, which is set to a static page called 'Home', the `<title>` attribute is blank. The HTML for 'Home' page looks like this:
```
<title></title>
```
The settings for the 'Home' page has 'Home' as the page title, but it doesn't show on the actual page output. Any idea why? The issue can be seen [here](https://www.dcturano.com/).
|
From the [Codex](http://codex.wordpress.org/Function_Reference/wp_title#Covering_Homepage)
`If you are using a custom homepage with custom loops and stuff or a custom front-page, you will have an empty wp_title. Here goes a neat hack to add the description/tagline at the wp_title place on homepage:`
```
add_filter( 'wp_title', 'baw_hack_wp_title_for_home' );
function baw_hack_wp_title_for_home( $title )
{
if( empty( $title ) && ( is_home() || is_front_page() ) ) {
return __( 'Home', 'theme_domain' ) . ' | ' . get_bloginfo( 'description' );
}
return $title;
}
```
|
178,466 |
<p>I am trying to change the comment author name (or more specifically, the review author in WooCommerce) to be First name Last Initial (e.g., "John D." for "John Doe").</p>
<p>I got most of the way there with the following code in functions.php, but for some reason (perhaps because of how the comment/review was submitted) it tends to blank out the name and replace it with a period (".") in some (not all) of the reviews.</p>
<pre><code>add_filter('get_comment_author', 'my_comment_author', 10, 1);
function my_comment_author( $author = '' ) {
// Get the comment ID from WP_Query
$comment = get_comment( $comment_ID );
if ( empty($comment->comment_author) ) {
if (!empty($comment->user_id)){
$user=get_userdata($comment->user_id);
$author=$user->first_name.' '.substr($user->last_name,0,1).'.'; // this is the actual line you want to change
} else {
$author = __('Anonymous');
}
} else {
$user=get_userdata($comment->user_id);
$author=$user->first_name.' '.substr($user->last_name,0,1).'.'; // this is the actual line you want to change
}
return $author;
}
</code></pre>
<p>If I tweak the code like this as a fallback, however, it always displays the full name:</p>
<pre><code>add_filter('get_comment_author', 'my_comment_author', 10, 1);
function my_comment_author( $author = '' ) {
// Get the comment ID from WP_Query
$comment = get_comment( $comment_ID );
if ( empty($comment->comment_author) ) {
if (!empty($comment->user_id)){
$user=get_userdata($comment->user_id);
$author=$user->first_name.' '.substr($user->last_name,0,1).'.'; // this is the actual line you want to change
} else {
$author = __('Anonymous');
}
} else {
$author = $comment->comment_author;
}
return $author;
}
</code></pre>
<p>I would prefer to leave the actual names in the database intact, and just filter the output on the public-facing side of the site for comments (we might need their full name to display elsewhere, but can't really test it until the comment authors are displaying correctly).</p>
|
[
{
"answer_id": 178478,
"author": "Roman Candle Thoughts",
"author_id": 23211,
"author_profile": "https://wordpress.stackexchange.com/users/23211",
"pm_score": 2,
"selected": false,
"text": "<p>You are missing a \"NOT\" logical operator (!) in your if statement. \nYou want to say \"if comment author IS NOT empty\". As of now, the function is reading that the author is not empty and defaulting to your else statement that tells it to output the author's full name. Use the second block of code but make the following change.</p>\n\n<p>Change the following:</p>\n\n<pre><code>if ( empty($comment->comment_author) ) {\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>if ( !empty($comment->comment_author) ) {\n</code></pre>\n\n<p>Otherwise it looks ok to me.</p>\n"
},
{
"answer_id": 237562,
"author": "GDY",
"author_id": 52227,
"author_profile": "https://wordpress.stackexchange.com/users/52227",
"pm_score": 2,
"selected": false,
"text": "<p>Had the same problem ...</p>\n<p>Heres my piece of code for that:</p>\n<pre><code>add_filter( 'comment_author', 'custom_comment_author', 10, 2 );\n\nfunction custom_comment_author( $author, $commentID ) {\n\n $comment = get_comment( $commentID );\n $user = get_user_by( 'email', $comment->comment_author_email );\n\n if( !$user ):\n\n return $author;\n\n else:\n\n $firstname = get_user_meta( $user->ID, 'first_name', true );\n $lastname = get_user_meta( $user->ID, 'last_name', true );\n\n if( empty( $firstname ) OR empty( $lastname ) ):\n\n return $author;\n\n else:\n\n return $firstname . ' ' . $lastname;\n\n endif;\n\n endif;\n\n}\n</code></pre>\n<p>It checks if there is a firstname and lastname and outputs these. If there are not the regular author is returned.</p>\n"
},
{
"answer_id": 338965,
"author": "Eduard",
"author_id": 78539,
"author_profile": "https://wordpress.stackexchange.com/users/78539",
"pm_score": 0,
"selected": false,
"text": "<p>Hmm, after a few minutes of debugging and reading through this topic, I've come to conclusion that is more easy to go through <a href=\"https://developer.wordpress.org/reference/functions/get_user_by/\" rel=\"nofollow noreferrer\">get_user_by()</a> function</p>\n\n<p>So I've went through <code>get_user_by('email',$comment->comment_author_email)</code> and managed to get the user details even if the comment/review is sent without user being logged in.</p>\n\n<p>This is my full code</p>\n\n<pre><code>add_filter('get_comment_author', 'comments_filter_uprise', 10, 1);\n\nfunction comments_filter_uprise( $author = '' ) {\n $comment = get_comment( $comment_author_email );\n\n if ( !empty($comment->comment_author_email) ) {\n if (!empty($comment->comment_author_email)){\n $user=get_user_by('email', $comment->comment_author_email);\n $author=$user->first_name.' '.substr($user->last_name,0,1).'.';\n } else {\n $user = get_user_by( 'email', $comment->comment_author_email );\n $author = $user->first_name;\n }\n } else {\n $user=get_userdata($comment->user_id);\n $author=$user->first_name.' '.substr($user->last_name,0,1).'.';\n $author = $comment->comment_author;\n }\n return $author;\n}\n</code></pre>\n"
}
] |
2015/02/17
|
[
"https://wordpress.stackexchange.com/questions/178466",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67654/"
] |
I am trying to change the comment author name (or more specifically, the review author in WooCommerce) to be First name Last Initial (e.g., "John D." for "John Doe").
I got most of the way there with the following code in functions.php, but for some reason (perhaps because of how the comment/review was submitted) it tends to blank out the name and replace it with a period (".") in some (not all) of the reviews.
```
add_filter('get_comment_author', 'my_comment_author', 10, 1);
function my_comment_author( $author = '' ) {
// Get the comment ID from WP_Query
$comment = get_comment( $comment_ID );
if ( empty($comment->comment_author) ) {
if (!empty($comment->user_id)){
$user=get_userdata($comment->user_id);
$author=$user->first_name.' '.substr($user->last_name,0,1).'.'; // this is the actual line you want to change
} else {
$author = __('Anonymous');
}
} else {
$user=get_userdata($comment->user_id);
$author=$user->first_name.' '.substr($user->last_name,0,1).'.'; // this is the actual line you want to change
}
return $author;
}
```
If I tweak the code like this as a fallback, however, it always displays the full name:
```
add_filter('get_comment_author', 'my_comment_author', 10, 1);
function my_comment_author( $author = '' ) {
// Get the comment ID from WP_Query
$comment = get_comment( $comment_ID );
if ( empty($comment->comment_author) ) {
if (!empty($comment->user_id)){
$user=get_userdata($comment->user_id);
$author=$user->first_name.' '.substr($user->last_name,0,1).'.'; // this is the actual line you want to change
} else {
$author = __('Anonymous');
}
} else {
$author = $comment->comment_author;
}
return $author;
}
```
I would prefer to leave the actual names in the database intact, and just filter the output on the public-facing side of the site for comments (we might need their full name to display elsewhere, but can't really test it until the comment authors are displaying correctly).
|
You are missing a "NOT" logical operator (!) in your if statement.
You want to say "if comment author IS NOT empty". As of now, the function is reading that the author is not empty and defaulting to your else statement that tells it to output the author's full name. Use the second block of code but make the following change.
Change the following:
```
if ( empty($comment->comment_author) ) {
```
to:
```
if ( !empty($comment->comment_author) ) {
```
Otherwise it looks ok to me.
|
178,468 |
<p>I have a question about changing the default sender From name/email on default wp_mail notifications (e.g., Lost Password response), but WITHOUT it messing up notifications being passed on by Gravity Forms.</p>
<p>I've found a few threads on changing the default From name/email, and this is what I ended up using. It did work properly to change the default sender from 'Wordpress' & '[email protected]'.</p>
<pre><code>// Change default WP email sender
add_filter('wp_mail_from', 'new_mail_from');
add_filter('wp_mail_from_name', 'new_mail_from_name');
function new_mail_from($old) {
return '[email protected]';
}
function new_mail_from_name($old) {
return 'Site Admin';
}
</code></pre>
<p>But it ended up also changing all form submissions being passed on from Gravity Forms, as that just uses wp_mail to process the completed form submissions. The Gravity Forms submissions SHOULD retain the From name/email entered by the user when completing the form. This info is stored in the header and passed on to wp_mail for sending.</p>
<ul>
<li>Is there a way to modify the function so it ONLY affects any mail being sent by the default address (Wordpress & [email protected])? Maybe some sort of search/replace?</li>
</ul>
<p>I'm also open to using SMTP sending if this could help and be more secure/robust. Unfortunately, I'm just not fluent in PHP to be able to write the function myself.</p>
|
[
{
"answer_id": 178475,
"author": "Kenny J",
"author_id": 67697,
"author_profile": "https://wordpress.stackexchange.com/users/67697",
"pm_score": 1,
"selected": false,
"text": "<p>I think I found the answer on another forum discussing using Contact Form7, with the same issue I was having.</p>\n\n<p>This is what I got from that thread and tried. It does appear to work and does appear to be only targeting email from the default 'Wordpress' sender name/email.</p>\n\n<pre><code>// Change default WP email sender\nadd_filter('wp_mail_from', 'doEmailFilter');\nadd_filter('wp_mail_from_name', 'doEmailNameFilter');\n\nfunction doEmailFilter($email_address){\nif($email_address === \"[email protected]\")\n return '[email protected]';\nelse\n return $email_address;\n}\nfunction doEmailNameFilter($email_from){\nif($email_from === \"WordPress\")\n return 'Site Admin';\nelse\n return $email_from;\n}\n</code></pre>\n\n<p>Let me know if there is a better way to do this. Sorry if obvious...</p>\n"
},
{
"answer_id": 178968,
"author": "Hannes",
"author_id": 31716,
"author_profile": "https://wordpress.stackexchange.com/users/31716",
"pm_score": 0,
"selected": false,
"text": "<p>I had a related issue and coded a plugin a few weeks ago. <a href=\"http://wp-html-mail.com\" rel=\"nofollow\">WP-HTML Mail</a> doesn't support gravity forms now, but if you decide to change you form to Ninja Forms, the plugin is perfect for you.\nI added detectors for plugins to find out which plugin just sent the mail.\nChanging formatting and sender can be turned on/off for detected plugins.</p>\n"
},
{
"answer_id": 179845,
"author": "Jason Hendriks",
"author_id": 68390,
"author_profile": "https://wordpress.stackexchange.com/users/68390",
"pm_score": 0,
"selected": false,
"text": "<p>I have an SMTP plugin that will set the default Sender Address and Sender Name, but still allow plugins (like Gravity Forms) to override these values.</p>\n\n<p><a href=\"https://wordpress.org/plugins/postman-smtp/\" rel=\"nofollow\">https://wordpress.org/plugins/postman-smtp/</a></p>\n\n<p>Having said that, depending on who your email accounts belong to, changing the Sender Email address to a different value than what you authenticate with may help mark your Email as Spam. Namely Gmail, Hotmail and Yahoo Mail.</p>\n"
}
] |
2015/02/17
|
[
"https://wordpress.stackexchange.com/questions/178468",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67697/"
] |
I have a question about changing the default sender From name/email on default wp\_mail notifications (e.g., Lost Password response), but WITHOUT it messing up notifications being passed on by Gravity Forms.
I've found a few threads on changing the default From name/email, and this is what I ended up using. It did work properly to change the default sender from 'Wordpress' & '[email protected]'.
```
// Change default WP email sender
add_filter('wp_mail_from', 'new_mail_from');
add_filter('wp_mail_from_name', 'new_mail_from_name');
function new_mail_from($old) {
return '[email protected]';
}
function new_mail_from_name($old) {
return 'Site Admin';
}
```
But it ended up also changing all form submissions being passed on from Gravity Forms, as that just uses wp\_mail to process the completed form submissions. The Gravity Forms submissions SHOULD retain the From name/email entered by the user when completing the form. This info is stored in the header and passed on to wp\_mail for sending.
* Is there a way to modify the function so it ONLY affects any mail being sent by the default address (Wordpress & [email protected])? Maybe some sort of search/replace?
I'm also open to using SMTP sending if this could help and be more secure/robust. Unfortunately, I'm just not fluent in PHP to be able to write the function myself.
|
I think I found the answer on another forum discussing using Contact Form7, with the same issue I was having.
This is what I got from that thread and tried. It does appear to work and does appear to be only targeting email from the default 'Wordpress' sender name/email.
```
// Change default WP email sender
add_filter('wp_mail_from', 'doEmailFilter');
add_filter('wp_mail_from_name', 'doEmailNameFilter');
function doEmailFilter($email_address){
if($email_address === "[email protected]")
return '[email protected]';
else
return $email_address;
}
function doEmailNameFilter($email_from){
if($email_from === "WordPress")
return 'Site Admin';
else
return $email_from;
}
```
Let me know if there is a better way to do this. Sorry if obvious...
|
178,484 |
<p>How do I query by meta_value or title? </p>
<p>If I set meta_values,</p>
<pre><code>$args['meta_query'] = array(
'relation' => 'OR',
array(
'key' => 'model_name',
'value' => $thesearch,
'compare' => 'like'
)
);
</code></pre>
<p>they automatically get added as AND.</p>
<p>This search would be:</p>
<pre><code> WHERE title = 'Search' AND (model_name = 'Search' OR ...)
</code></pre>
<p>I need</p>
<pre><code>WHERE title = 'Search' OR (model_name = 'Search' OR ...)
</code></pre>
|
[
{
"answer_id": 178492,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 6,
"selected": true,
"text": "<p>Note that the <code>relation</code> part in the <code>meta_query</code> argument, is only used to define the relation between the <em>sub meta</em> queries.</p>\n\n<p>You can try this setup:</p>\n\n<pre><code>$args = [ \n '_meta_or_title' => $thesearch, // Our new custom argument!\n 'meta_query' => [\n [\n 'key' => 'model_name',\n 'value' => $thesearch,\n 'compare' => 'like'\n ]\n ],\n];\n</code></pre>\n\n<p>where we have introduced a custom argument <code>_meta_or_title</code> to activate the <em>meta OR title</em> query.</p>\n\n<p>This is supported by the following plugin:</p>\n\n<pre><code><?php\n/**\n * Plugin Name: Meta OR Title query in WP_Query\n * Description: Activated through the '_meta_or_title' argument of WP_Query \n * Plugin URI: http://wordpress.stackexchange.com/a/178492/26350\n * Plugin Author: Birgir Erlendsson (birgire)\n * Version: 0.0.1\n */\n\nadd_action( 'pre_get_posts', function( $q )\n{\n if( $title = $q->get( '_meta_or_title' ) )\n {\n add_filter( 'get_meta_sql', function( $sql ) use ( $title )\n {\n global $wpdb;\n\n // Only run once:\n static $nr = 0; \n if( 0 != $nr++ ) return $sql;\n\n // Modify WHERE part:\n $sql['where'] = sprintf(\n \" AND ( %s OR %s ) \",\n $wpdb->prepare( \"{$wpdb->posts}.post_title = '%s'\", $title ),\n mb_substr( $sql['where'], 5, mb_strlen( $sql['where'] ) )\n );\n return $sql;\n });\n }\n});\n</code></pre>\n"
},
{
"answer_id": 373254,
"author": "rAthus",
"author_id": 154000,
"author_profile": "https://wordpress.stackexchange.com/users/154000",
"pm_score": 2,
"selected": false,
"text": "<p>I couldn't find a solution to look for multiple keywords that can be mixed in either post title, description AND/OR one or several metas, so I made my own addition to the search function.</p>\n<p>All you is to add the following code in <em>function.php</em>, and whenever you us the 's' argument in WP_Query() and want it to search in one or several as well you simply add a 's_meta_keys' argument that is an array of the meta(s) key you want to search in:</p>\n<pre><code>/************************************************************************\\\n|** **|\n|** Allow WP_Query() search function to look for multiple keywords **|\n|** in metas in addition to post_title and post_content **|\n|** **|\n|** By rAthus @ Arkanite **|\n|** Created: 2020-08-18 **|\n|** Updated: 2020-08-19 **|\n|** **|\n|** Just use the usual 's' argument and add a 's_meta_keys' argument **|\n|** containing an array of the meta(s) key you want to search in :) **|\n|** **|\n|** Example : **|\n|** **|\n|** $args = array( **|\n|** 'numberposts' => -1, **|\n|** 'post_type' => 'post', **|\n|** 's' => $MY_SEARCH_STRING, **|\n|** 's_meta_keys' => array('META_KEY_1','META_KEY_2'); **|\n|** 'orderby' => 'date', **|\n|** 'order' => 'DESC', **|\n|** ); **|\n|** $posts = new WP_Query($args); **|\n|** **|\n\\************************************************************************/\nadd_action('pre_get_posts', 'my_search_query'); // add the special search fonction on each get_posts query (this includes WP_Query())\nfunction my_search_query($query) {\n if ($query->is_search() and $query->query_vars and $query->query_vars['s'] and $query->query_vars['s_meta_keys']) { // if we are searching using the 's' argument and added a 's_meta_keys' argument\n global $wpdb;\n $search = $query->query_vars['s']; // get the search string\n $ids = array(); // initiate array of martching post ids per searched keyword\n foreach (explode(' ',$search) as $term) { // explode keywords and look for matching results for each\n $term = trim($term); // remove unnecessary spaces\n if (!empty($term)) { // check the the keyword is not empty\n $query_posts = $wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE post_status='publish' AND ((post_title LIKE '%%%s%%') OR (post_content LIKE '%%%s%%'))", $term, $term); // search in title and content like the normal function does\n $ids_posts = [];\n $results = $wpdb->get_results($query_posts);\n if ($wpdb->last_error)\n die($wpdb->last_error);\n foreach ($results as $result)\n $ids_posts[] = $result->ID; // gather matching post ids\n $query_meta = [];\n foreach($query->query_vars['s_meta_keys'] as $meta_key) // now construct a search query the search in each desired meta key\n $query_meta[] = $wpdb->prepare("meta_key='%s' AND meta_value LIKE '%%%s%%'", $meta_key, $term);\n $query_metas = $wpdb->prepare("SELECT * FROM {$wpdb->postmeta} WHERE ((".implode(') OR (',$query_meta)."))");\n $ids_metas = [];\n $results = $wpdb->get_results($query_metas);\n if ($wpdb->last_error)\n die($wpdb->last_error);\n foreach ($results as $result)\n $ids_metas[] = $result->post_id; // gather matching post ids\n $merged = array_merge($ids_posts,$ids_metas); // merge the title, content and meta ids resulting from both queries\n $unique = array_unique($merged); // remove duplicates\n if (!$unique)\n $unique = array(0); // if no result, add a "0" id otherwise all posts wil lbe returned\n $ids[] = $unique; // add array of matching ids into the main array\n }\n }\n if (count($ids)>1)\n $intersected = call_user_func_array('array_intersect',$ids); // if several keywords keep only ids that are found in all keywords' matching arrays\n else\n $intersected = $ids[0]; // otherwise keep the single matching ids array\n $unique = array_unique($intersected); // remove duplicates\n if (!$unique)\n $unique = array(0); // if no result, add a "0" id otherwise all posts wil lbe returned\n unset($query->query_vars['s']); // unset normal search query\n $query->set('post__in',$unique); // add a filter by post id instead\n }\n}\n</code></pre>\n<p>Example use:</p>\n<pre><code>$search= "kewords to search";\n\n$args = array(\n 'numberposts' => -1,\n 'post_type' => 'post',\n 's' => $search,\n 's_meta_keys' => array('short_desc','tags');\n 'orderby' => 'date',\n 'order' => 'DESC',\n);\n\n$posts = new WP_Query($args);\n</code></pre>\n<p>This example will look for the keywords "kewords to search" in post titles, descriptions, and meta keys 'short_desc' and 'tags'.</p>\n<p>Keywords can be found in one or several of the fileds, in any order, it will return any post that has all the keywords in any of the designated fields.</p>\n<p>You can obiously force the search in a list of meta keys you include in the fonction and get rid of the extra agruments if you want ALL search queries to include these meta keys :)</p>\n<p>Hope that will help anyone who face the same issue I did!</p>\n"
},
{
"answer_id": 392702,
"author": "Jeff Oliva",
"author_id": 209642,
"author_profile": "https://wordpress.stackexchange.com/users/209642",
"pm_score": 1,
"selected": false,
"text": "<p>I'm quite new in WP, I haven't tested too much this approach I've came up with. Maybe you can help me to check if i am correct. The solution I've found so far is to implement the same meta_query logic, just making some replacements.</p>\n<p>First, the usage:</p>\n<pre><code>$args = array(\n 'lang' => 'pt', //this function does not conflict (example: polylang)\n 'post_type' => 'produtos', \n 'post_status' => 'publish',\n 'posts_per_page' => 10,\n 'paged' => 1,\n 'fields' => 'ids',\n);\n$args['meta_query] = [\n ['relation'] => 'OR'; //any relation you desire\n [\n 'key' => 'acf_field', //any custom field (regular usage)\n 'value' => $search, //any value (regular usage)\n 'compare' => 'LIKE', //any comparition (regular usage)\n ],\n [\n 'key' => 'post_title', //set the default post content of wordpress you desire ('post_content', 'post_title' and 'post_excerpt')\n 'value' => $search, //any value\n 'compare' => 'LIKE', //tested with 'LIKE and '=', works great and I can't realize other needs.\n ],\n [\n 'key' => 'post_exerpt', // you can add how many times you need\n 'value' => $search_2,\n 'compare' => 'LIKE', \n ],\n];\n$the_query = new WP_Query( $args ); //jus query\nwp_reset_postdata(); //clean your query\n</code></pre>\n<p>To work, add this function to your theme functions.php</p>\n<pre><code>function post_content_to_meta_queries($where, $wp_query){\n global $wpdb;\n\n //if there is no metaquery, bye!\n $meta_queries = $wp_query->get( 'meta_query' );\n if( !$meta_queries || $meta_queries == '' ) return $where;\n\n //if only one relation\n $where = str_replace($wpdb->postmeta . ".meta_key = 'post_title' AND " . $wpdb->postmeta . ".meta_value", $wpdb->posts . ".post_title", $where);\n $where = str_replace($wpdb->postmeta . ".meta_key = 'post_content' AND " . $wpdb->postmeta . ".meta_value", $wpdb->posts . ".post_content", $where);\n $where = str_replace($wpdb->postmeta . ".meta_key = 'post_excerpt' AND " . $wpdb->postmeta . ".meta_value", $wpdb->posts . ".post_excerpt", $where);\n\n ////for nested relations\n\n //count the numbers of meta queries for possible replacements\n $number_of_relations = count($meta_queries);\n\n //replace 'WHERE' using the multidimensional postmeta naming logic used by wordpress core\n $i = 1;\n while($i<=$number_of_relations && $number_of_relations > 0){\n $where = str_replace("mt".$i.".meta_key = 'post_title' AND mt".$i.".meta_value", $wpdb->posts . ".post_title", $where);\n $where = str_replace("mt".$i.".meta_key = 'post_content' AND mt".$i.".meta_value", $wpdb->posts . ".post_content", $where);\n $where = str_replace("mt".$i.".meta_key = 'post_excerpt' AND mt".$i.".meta_value", $wpdb->posts . ".post_excerpt", $where);\n $i++;\n }\n\n return $where;\n}\n\nadd_filter('posts_where','post_content_to_meta_queries',10,2);\n</code></pre>\n<p>I'm pretty sure it can be improved! Hope it helps!</p>\n"
}
] |
2015/02/18
|
[
"https://wordpress.stackexchange.com/questions/178484",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67686/"
] |
How do I query by meta\_value or title?
If I set meta\_values,
```
$args['meta_query'] = array(
'relation' => 'OR',
array(
'key' => 'model_name',
'value' => $thesearch,
'compare' => 'like'
)
);
```
they automatically get added as AND.
This search would be:
```
WHERE title = 'Search' AND (model_name = 'Search' OR ...)
```
I need
```
WHERE title = 'Search' OR (model_name = 'Search' OR ...)
```
|
Note that the `relation` part in the `meta_query` argument, is only used to define the relation between the *sub meta* queries.
You can try this setup:
```
$args = [
'_meta_or_title' => $thesearch, // Our new custom argument!
'meta_query' => [
[
'key' => 'model_name',
'value' => $thesearch,
'compare' => 'like'
]
],
];
```
where we have introduced a custom argument `_meta_or_title` to activate the *meta OR title* query.
This is supported by the following plugin:
```
<?php
/**
* Plugin Name: Meta OR Title query in WP_Query
* Description: Activated through the '_meta_or_title' argument of WP_Query
* Plugin URI: http://wordpress.stackexchange.com/a/178492/26350
* Plugin Author: Birgir Erlendsson (birgire)
* Version: 0.0.1
*/
add_action( 'pre_get_posts', function( $q )
{
if( $title = $q->get( '_meta_or_title' ) )
{
add_filter( 'get_meta_sql', function( $sql ) use ( $title )
{
global $wpdb;
// Only run once:
static $nr = 0;
if( 0 != $nr++ ) return $sql;
// Modify WHERE part:
$sql['where'] = sprintf(
" AND ( %s OR %s ) ",
$wpdb->prepare( "{$wpdb->posts}.post_title = '%s'", $title ),
mb_substr( $sql['where'], 5, mb_strlen( $sql['where'] ) )
);
return $sql;
});
}
});
```
|
178,514 |
<p>When I call <strong>the_content()</strong> i am getting</p>
<pre><code><div class="page" title="Page 1">
<div class="section">
<div class="layoutArea">
<div class="column">
<p>my text</p>
</div>
</div>
</div>
</div>
</code></pre>
<p>I would expect just</p>
<pre><code><p>my text</p>
</code></pre>
<p>I am confused about that. I think I have never had all these wrappers returned. Moreover, I have not found a match for layoutArea in the whole wordpress install, nor in my bootsrtap starter theme.</p>
<p>Any ideas?</p>
<p>--
<strong>UPDATE</strong>: just saw that all those divs were automatically generated by the editor. I was able to remove them via the tinymce text view tab. Still confused, anyway.</p>
|
[
{
"answer_id": 178516,
"author": "cristian.raiber",
"author_id": 52524,
"author_profile": "https://wordpress.stackexchange.com/users/52524",
"pm_score": 0,
"selected": false,
"text": "<p>Usually, all those divs surround the <code>the_content();</code> function. Theme developers use these divs to wrap the content that's going to be outputted by the <code>the_content();</code> function. </p>\n\n<p>Having those divs present there, makes it a whole lot easier to style the content that's coming out from <code>the_content();</code></p>\n\n<p>Bottom line: I don't think you should be removing those divs.</p>\n"
},
{
"answer_id": 178767,
"author": "Marc",
"author_id": 66405,
"author_profile": "https://wordpress.stackexchange.com/users/66405",
"pm_score": 1,
"selected": false,
"text": "<p>As @TheDeadMedic pointed out, I was copying-pasting text directly from an external source, and that is why the wrappers were in the tinymce as well.</p>\n\n<p>Those divs in my case, were copied from a pdf that was probably exported from illustrator or indesign.</p>\n"
}
] |
2015/02/18
|
[
"https://wordpress.stackexchange.com/questions/178514",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66405/"
] |
When I call **the\_content()** i am getting
```
<div class="page" title="Page 1">
<div class="section">
<div class="layoutArea">
<div class="column">
<p>my text</p>
</div>
</div>
</div>
</div>
```
I would expect just
```
<p>my text</p>
```
I am confused about that. I think I have never had all these wrappers returned. Moreover, I have not found a match for layoutArea in the whole wordpress install, nor in my bootsrtap starter theme.
Any ideas?
--
**UPDATE**: just saw that all those divs were automatically generated by the editor. I was able to remove them via the tinymce text view tab. Still confused, anyway.
|
As @TheDeadMedic pointed out, I was copying-pasting text directly from an external source, and that is why the wrappers were in the tinymce as well.
Those divs in my case, were copied from a pdf that was probably exported from illustrator or indesign.
|
178,517 |
<p>My categories are basically authors, and I would like to create a function to list them according to their surname. For example I'd like to have something like:</p>
<p>E:</p>
<ul>
<li>Heinz Erhardt</li>
<li>Albert Einstein</li>
<li>Eminem</li>
</ul>
<p>The problem is, I also have authors with only one name (like "Eminem") which I would also like to be sorted according to the letter E.
The only way I know of to do this in wordpress is with the <code>get_terms</code> function and the <code>name__like</code>.</p>
<pre><code>function getAuthors(){
$args = array(
'name__like' => 'E',
);
return get_terms('category', $args );
}
</code></pre>
<p>this creates the sql query which only lists categories with an "E" in it:</p>
<pre><code>AND t.name LIKE %E%;
</code></pre>
<p>I however need something like:</p>
<pre><code>AND t.name NOT LIKE '% %' AND t.name LIKE E% OR t.name LIKE '% E';
</code></pre>
<p>I tried to change the code in the get_terms function in the core file where the query is set up (taxonomies.php, line 1809). However I wasn't successfull and I wouldn't like to change something in the core files.</p>
<p>How can I customize the query passed by the <code>name__like</code>? Are there other better ways I can achieve my goal?</p>
<p><strong>--- EDIT ---</strong></p>
<p>I used TheDeadMedic's solution and was able to list categories according to a specific letter by using for example <code>get_terms( 'my_taxonomy', 'surname=E' );</code> However this <code>surname</code> argument doesn't work if I want to use the <code>get_terms</code> function multiple times on one page (for example in a loop - if I'd like to create A-Z headings and display the according sorted categories below the headings).</p>
<p>Here's the function I'm trying to execute. The problem is that it just keeps listing the categorys for <code>surname=A</code> under every heading.</p>
<pre><code>function getAuthors()
{
$letters = range('A', 'Z'); // create Alphabet array
foreach ($letters as $letter) {
echo '<h4>' . $letter . '</h4>';
$args = array(
'surname' => $letter
);
$cats = get_terms('category', $args);
foreach ($cats as $cat) {
echo "<ul>";
echo "<li>" . $cat->name . "</li>";
echo "</ul>";
}
}
}
</code></pre>
<p>The <code>name__like</code> argument seems to work in the loop though.</p>
|
[
{
"answer_id": 178518,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 4,
"selected": true,
"text": "<p>Use the <code>terms_clauses</code> filter, which passes all the various components of the query (fields, join, where, orderby, order & limits), and implement your own \"search\" argument:</p>\n\n<pre><code>function wpse_178511_get_terms_fields( $clauses, $taxonomies, $args ) {\n if ( ! empty( $args['surname'] ) ) {\n global $wpdb;\n\n $surname_like = $wpdb->esc_like( $args['surname'] );\n\n if ( ! isset( $clauses['where'] ) )\n $clauses['where'] = '1=1';\n\n $clauses['where'] .= $wpdb->prepare( \" AND t.name LIKE %s OR t.name LIKE %s\", \"$surname_like%\", \"% $surname_like%\" );\n }\n\n return $clauses;\n}\n\nadd_filter( 'terms_clauses', 'wpse_178511_get_terms_fields', 10, 3 );\n</code></pre>\n\n<p>Put in use:</p>\n\n<pre><code> get_terms( 'my_taxonomy', 'surname=E' );\n</code></pre>\n"
},
{
"answer_id": 367628,
"author": "Rahman Rezaee",
"author_id": 176503,
"author_profile": "https://wordpress.stackexchange.com/users/176503",
"pm_score": 0,
"selected": false,
"text": "<p>look to this argument that get like in name</p>\n\n<pre><code> $get_terms_default_attributes = array (\n 'taxonomy' => 'category', //empty string(''), false, 0 don't work, and return empty array\n 'orderby' => 'name',\n 'order' => 'ASC',\n 'hide_empty' => true, //can be 1, '1' too\n 'include' => 'all', //empty string(''), false, 0 don't work, and return empty array\n 'exclude' => 'all', //empty string(''), false, 0 don't work, and return empty array\n 'exclude_tree' => 'all', //empty string(''), false, 0 don't work, and return empty array\n 'number' => false, //can be 0, '0', '' too\n 'offset' => '',\n 'fields' => 'all',\n 'name' => '',\n 'slug' => '',\n 'hierarchical' => true, //can be 1, '1' too\n 'search' => '',\n\n //this part\n\n 'name__like' => '',\n 'description__like' => '',\n\n 'pad_counts' => false, //can be 0, '0', '' too\n 'get' => '',\n 'child_of' => false, //can be 0, '0', '' too\n 'childless' => false,\n 'cache_domain' => 'core',\n 'update_term_meta_cache' => true, //can be 1, '1' too\n 'meta_query' => '',\n 'meta_key' => array(),\n 'meta_value'=> '',\n );\n</code></pre>\n"
}
] |
2015/02/18
|
[
"https://wordpress.stackexchange.com/questions/178517",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/30939/"
] |
My categories are basically authors, and I would like to create a function to list them according to their surname. For example I'd like to have something like:
E:
* Heinz Erhardt
* Albert Einstein
* Eminem
The problem is, I also have authors with only one name (like "Eminem") which I would also like to be sorted according to the letter E.
The only way I know of to do this in wordpress is with the `get_terms` function and the `name__like`.
```
function getAuthors(){
$args = array(
'name__like' => 'E',
);
return get_terms('category', $args );
}
```
this creates the sql query which only lists categories with an "E" in it:
```
AND t.name LIKE %E%;
```
I however need something like:
```
AND t.name NOT LIKE '% %' AND t.name LIKE E% OR t.name LIKE '% E';
```
I tried to change the code in the get\_terms function in the core file where the query is set up (taxonomies.php, line 1809). However I wasn't successfull and I wouldn't like to change something in the core files.
How can I customize the query passed by the `name__like`? Are there other better ways I can achieve my goal?
**--- EDIT ---**
I used TheDeadMedic's solution and was able to list categories according to a specific letter by using for example `get_terms( 'my_taxonomy', 'surname=E' );` However this `surname` argument doesn't work if I want to use the `get_terms` function multiple times on one page (for example in a loop - if I'd like to create A-Z headings and display the according sorted categories below the headings).
Here's the function I'm trying to execute. The problem is that it just keeps listing the categorys for `surname=A` under every heading.
```
function getAuthors()
{
$letters = range('A', 'Z'); // create Alphabet array
foreach ($letters as $letter) {
echo '<h4>' . $letter . '</h4>';
$args = array(
'surname' => $letter
);
$cats = get_terms('category', $args);
foreach ($cats as $cat) {
echo "<ul>";
echo "<li>" . $cat->name . "</li>";
echo "</ul>";
}
}
}
```
The `name__like` argument seems to work in the loop though.
|
Use the `terms_clauses` filter, which passes all the various components of the query (fields, join, where, orderby, order & limits), and implement your own "search" argument:
```
function wpse_178511_get_terms_fields( $clauses, $taxonomies, $args ) {
if ( ! empty( $args['surname'] ) ) {
global $wpdb;
$surname_like = $wpdb->esc_like( $args['surname'] );
if ( ! isset( $clauses['where'] ) )
$clauses['where'] = '1=1';
$clauses['where'] .= $wpdb->prepare( " AND t.name LIKE %s OR t.name LIKE %s", "$surname_like%", "% $surname_like%" );
}
return $clauses;
}
add_filter( 'terms_clauses', 'wpse_178511_get_terms_fields', 10, 3 );
```
Put in use:
```
get_terms( 'my_taxonomy', 'surname=E' );
```
|
178,533 |
<p>I'm trying to convert a bunch of posts within a CPT to items within a Custom Taxonomy, where the post titles become the taxonomy names and the post content becomes the taxonomy descriptions. I have the below code (<a href="http://pastebin.com/Ukrmw2Jt" rel="nofollow">also here</a>) in a plugin but am not sure where to add my CPT and Tax names. Or if the code will fire properly from within the plugin. Any ideas?</p>
<pre><code>/**
* Create slugs/terms in jjm_author_tax taxonomy for all jjm_authors posts
*
*/
function make_taxonomy_from_posts($post_type, $taxonomy){
// Get all posts
$query_posts = query_posts(array(
// ... of the requested type
'post_type'=> $post_type,
// ... and it supports the taxonomy
'taxonomy' => $taxonomy,
// ... without limit
'nopaging' => true,
));
// Reset the main query
wp_reset_query();
foreach ($query_posts as $query_post) {
$post_id = $query_post->ID;
$raw_title = $query_post->post_title;
// Generate a slug based on the title.
// We want to check for auto-draft so we don't create a term for a post with no title
$slug_title = sanitize_title($raw_title);
// Do the checks for empty titles
// If the title is blank, skip it
if ($slug_title == 'auto-draft' || empty($raw_title)) continue;
// Get all of the terms associated with the post
$terms = get_the_terms($post_id, $taxonomy);
$term_id = 0;
if (!empty($terms)) {
$term_id = $terms[0]->term_id;
}
if ($term_id > 0) {
// If the post has a term, update the term
wp_update_term($term_id, $taxonomy, array(
'description' => $raw_title,
'slug' => $raw_title,
'name' => $raw_title,
));
} else {
// Otherwise add a new term
wp_set_object_terms($post_id, $raw_title, $taxonomy, false);
}
}
}
</code></pre>
|
[
{
"answer_id": 178535,
"author": "David Gard",
"author_id": 10097,
"author_profile": "https://wordpress.stackexchange.com/users/10097",
"pm_score": 1,
"selected": false,
"text": "<p>First we create a new custom query containing all published posts of type <code>$post_type</code>, which you pass to the function. If you don't just want published posts you can pick and choose the status' that you require - <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query#Status_Parameters\" rel=\"nofollow noreferrer\">see this part of the WP_Query Codex</a>.</p>\n<p>Next we use <a href=\"http://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">The Loop</a> to loop through the resultant posts and for each check if the post name exists as a term within $taxonomy (which you also pass to the function) using <a href=\"http://codex.wordpress.org/Function_Reference/term_exists\" rel=\"nofollow noreferrer\"><code>term_exists()</code></a>, and if not, we add it using <a href=\"http://codex.wordpress.org/Function_Reference/wp_insert_term\" rel=\"nofollow noreferrer\"><code>wp_insert_term()</code></a>. Using this means that we only have to pass the name and description, while the slug will be automatically created based on the name.</p>\n<p>Finally, just before exiting <a href=\"http://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">The Loop</a> we reset the global <code>$post</code> using <a href=\"http://codex.wordpress.org/Function_Reference/wp_reset_postdata\" rel=\"nofollow noreferrer\"><code>wp_reset_postdata()</code></a></p>\n<p>Place this entire code block into <strong>functions.php</strong> in the order that it is on here. While you can just leave this code to run on every page load (duplicate category names <strong>will not</strong> be created), it's recommended for permormance reasons and you should ensure that you comment the call to <code>add_action()</code> when you are done.</p>\n<pre><code>add_action('init', 'init_make_taxonomy_from_posts');\nfunction init_make_taxonomy_from_posts(){\n make_taxonomy_from_posts('jjm_authors', 'jjm_author_tax');\n}\n\n/**\n * Create slugs/terms in jjm_author_tax taxonomy for all jjm_authors posts\n */\nfunction make_taxonomy_from_posts($post_type, $taxonomy){\n\n /** Grab the relevant posts */\n $args = array(\n 'post_status' => 'publish',\n 'post_type' => $post_type,\n 'posts_per_page' => -1\n );\n $my_query = new WP_Query($args);\n \n /** Check that some posts were found and loop through them */\n if($my_query->have_posts()) : while($my_query->have_posts()) : $my_query->the_post();\n \n /** Check to see if a term with the same title as the post currently exists in $taxonomy */\n if(!term_exists(get_the_title(), $taxonomy)) : // It doesn't\n \n /** Add a new term to $taxonomy */\n $args = array(\n 'description' => get_the_content()\n );\n wp_insert_term(get_the_title(), $taxonomy);\n \n endif;\n \n endwhile;\n \n /** Reset the '$post' global */\n wp_reset_postdata();\n\n endif;\n\n}\n</code></pre>\n<hr />\n<h1>Note</h1>\n<p>This code is tested and <strong>100%</strong> working.</p>\n"
},
{
"answer_id": 178545,
"author": "Josh M",
"author_id": 9764,
"author_profile": "https://wordpress.stackexchange.com/users/9764",
"pm_score": 3,
"selected": true,
"text": "<p>Here's the solution that worked for me. I added the below code to a page template (page-test.php) and then created a page called "test," loaded the page, and all the CPTS were converted to taxonomies. Not sure if this happened when I created the page or when I loaded it... And then I quickly deleted the page template so I didn't end up with a bunch of duplicates.</p>\n<pre><code><?php\n function cpt_to_tax($post_type, $taxonomy) {\n $posts = get_posts(array(\n 'post_type' => $post_type,\n 'posts_per_page' => -1,\n ));\n \n foreach($posts as $post) {\n wp_insert_term($post->post_title, $taxonomy, array(\n 'description' => $post->post_content,\n ));\n }\n }\n\n cpt_to_tax('jjm_authors', 'jjm_author_tax');\n?>\n</code></pre>\n<p>The solution itself was provide by <a href=\"https://wordpress.stackexchange.com/users/35470/circuuz\">https://wordpress.stackexchange.com/users/35470/circuuz</a>, though his post seems to be deleted now. :(</p>\n"
}
] |
2015/02/18
|
[
"https://wordpress.stackexchange.com/questions/178533",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9764/"
] |
I'm trying to convert a bunch of posts within a CPT to items within a Custom Taxonomy, where the post titles become the taxonomy names and the post content becomes the taxonomy descriptions. I have the below code ([also here](http://pastebin.com/Ukrmw2Jt)) in a plugin but am not sure where to add my CPT and Tax names. Or if the code will fire properly from within the plugin. Any ideas?
```
/**
* Create slugs/terms in jjm_author_tax taxonomy for all jjm_authors posts
*
*/
function make_taxonomy_from_posts($post_type, $taxonomy){
// Get all posts
$query_posts = query_posts(array(
// ... of the requested type
'post_type'=> $post_type,
// ... and it supports the taxonomy
'taxonomy' => $taxonomy,
// ... without limit
'nopaging' => true,
));
// Reset the main query
wp_reset_query();
foreach ($query_posts as $query_post) {
$post_id = $query_post->ID;
$raw_title = $query_post->post_title;
// Generate a slug based on the title.
// We want to check for auto-draft so we don't create a term for a post with no title
$slug_title = sanitize_title($raw_title);
// Do the checks for empty titles
// If the title is blank, skip it
if ($slug_title == 'auto-draft' || empty($raw_title)) continue;
// Get all of the terms associated with the post
$terms = get_the_terms($post_id, $taxonomy);
$term_id = 0;
if (!empty($terms)) {
$term_id = $terms[0]->term_id;
}
if ($term_id > 0) {
// If the post has a term, update the term
wp_update_term($term_id, $taxonomy, array(
'description' => $raw_title,
'slug' => $raw_title,
'name' => $raw_title,
));
} else {
// Otherwise add a new term
wp_set_object_terms($post_id, $raw_title, $taxonomy, false);
}
}
}
```
|
Here's the solution that worked for me. I added the below code to a page template (page-test.php) and then created a page called "test," loaded the page, and all the CPTS were converted to taxonomies. Not sure if this happened when I created the page or when I loaded it... And then I quickly deleted the page template so I didn't end up with a bunch of duplicates.
```
<?php
function cpt_to_tax($post_type, $taxonomy) {
$posts = get_posts(array(
'post_type' => $post_type,
'posts_per_page' => -1,
));
foreach($posts as $post) {
wp_insert_term($post->post_title, $taxonomy, array(
'description' => $post->post_content,
));
}
}
cpt_to_tax('jjm_authors', 'jjm_author_tax');
?>
```
The solution itself was provide by <https://wordpress.stackexchange.com/users/35470/circuuz>, though his post seems to be deleted now. :(
|
178,539 |
<p>I install Tinymce editor to my site. And now i need to set the default direction to <code>RTL</code> not <code>LTR</code>.</p>
<p>I try this way but not work with me :-</p>
<pre><code>#tinymce p {
direction : rtl;
}
</code></pre>
<p>How can do that ??</p>
|
[
{
"answer_id": 253721,
"author": "aytan",
"author_id": 111635,
"author_profile": "https://wordpress.stackexchange.com/users/111635",
"pm_score": 2,
"selected": false,
"text": "<pre><code> tinymce.init({\n selector: 'textarea#editor', \n directionality :\"rtl\"\n});\n</code></pre>\n"
},
{
"answer_id": 323357,
"author": "eyal_123",
"author_id": 151328,
"author_profile": "https://wordpress.stackexchange.com/users/151328",
"pm_score": 2,
"selected": false,
"text": "<p>In wordpress, the editor will support and will be in RTL by default if you install it in an rtl language, for example, if you install wordpress with the hebrew UI the editor will be rtl by default.</p>\n\n<p>The problem is if you install the hebrew UI but change your profile to use the English one, in order to still use the editor in rtl mode while using the English UI you can add this code to functions.php or a site plugin:</p>\n\n<pre><code>function Eyal_setEditorToRTL($settings)\n{\n $settings['directionality'] = 'rtl';\n return $settings;\n}\nadd_filter('tiny_mce_before_init', 'Eyal_setEditorToRTL');\n</code></pre>\n\n<p>The filter alters the default settings for the tinyMCE editor and set it in rtl mode.</p>\n"
}
] |
2015/02/18
|
[
"https://wordpress.stackexchange.com/questions/178539",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67551/"
] |
I install Tinymce editor to my site. And now i need to set the default direction to `RTL` not `LTR`.
I try this way but not work with me :-
```
#tinymce p {
direction : rtl;
}
```
How can do that ??
|
```
tinymce.init({
selector: 'textarea#editor',
directionality :"rtl"
});
```
|
178,547 |
<p>Here's a quick example of I am trying to achieve:</p>
<p><strong>I am using this filter:</strong></p>
<pre><code>add_filter('manage_edit-member_columns', 'set_custom_edit_member_columns');
function set_custom_edit_member_columns($columns) {
$columns['photo'] = "Photo";
return $columns;
}
</code></pre>
<p>The function has one parameter passed ($columns). I want to see what's inside of $columns. By the example in the codex, I know it's an array with column names.</p>
<p>Question... how can I dump/log the values of in that array?</p>
<p>I am using Chrome. So I installed Chromelogger. This will let me log arrays, but it does not seem to work when it's called inside the function set_custom_edit_member_columns(). Thus, I can't get the values of $columns.</p>
<p>This is just an example. But, pretty much I am struggling to find a way to dump variables that are used inside functions.php or other php files that do not directly print to the page I am currently viewing.</p>
|
[
{
"answer_id": 178550,
"author": "Bruno Rodrigues",
"author_id": 42886,
"author_profile": "https://wordpress.stackexchange.com/users/42886",
"pm_score": 0,
"selected": false,
"text": "<p>Place the following function in your <code>functions.php</code>:</p>\n\n<pre><code>function wpse_178547_log( $message ) {\n file_put_contents( 'custom.log', date( \"d-m-Y H:i:s\" ) . ' ::::: ' . $message . PHP_EOL, FILE_APPEND );\n}\n</code></pre>\n\n<p>Then: </p>\n\n<pre><code>function set_custom_edit_member_columns($columns) {\n\n wpse_178547_log('$columns');\n\n foreach($columns as $column){\n wpse_178547_log($column);\n }\n\n $columns['photo'] = \"Photo\";\n\n return $columns;\n\n}\n</code></pre>\n\n<p>A file named <code>custom.log</code> will be created in project's root.</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 178552,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 1,
"selected": false,
"text": "<p>When a <a href=\"http://php.net/manual/es/function.var-dump.php\" rel=\"nofollow noreferrer\">var_dump</a> or any other screen output is not posible, you can use <a href=\"http://php.net/manual/es/function.error-log.php\" rel=\"nofollow noreferrer\">error_log</a>. The message will be added to the error_log file on your server. To log variables I like <a href=\"https://stackoverflow.com/questions/7878279/how-to-debug-save-post-actions-in-wordpress\">this small function</a>:</p>\n\n<pre><code>function log_it( $message ) {\n if( WP_DEBUG === true ){\n if( is_array( $message ) || is_object( $message ) ){\n //error_log will be located according to server configuration\n //you can specify a custom location if needed like this\n //error_log( $var, 0, \"full-path-to/error_log.txt\")\n error_log( print_r( $message, true ) );\n } else {\n error_log( $message );\n }\n }\n}\n</code></pre>\n\n<p>To use use it, <a href=\"http://codex.wordpress.org/WP_DEBUG\" rel=\"nofollow noreferrer\">turn WP_DEBUG on</a> and do someting like this:</p>\n\n<pre><code>function set_custom_edit_member_columns($columns) {\n\n log_it( $columns );\n\n $columns['photo'] = \"Photo\";\n\n return $columns;\n\n}\n</code></pre>\n"
},
{
"answer_id": 178554,
"author": "geomagas",
"author_id": 39275,
"author_profile": "https://wordpress.stackexchange.com/users/39275",
"pm_score": 3,
"selected": true,
"text": "<p>If you want to keep your log on the server, try using php's <a href=\"http://php.net/manual/en/function.error-log.php\" rel=\"nofollow\"><code>error_log()</code></a> which is more flexible than just writing to files on disk. Something along the lines of:</p>\n\n<pre><code>add_filter('manage_edit-member_columns', 'set_custom_edit_member_columns');\n\nfunction set_custom_edit_member_columns($columns) {\n\n error_log(print_r($columns,true),3,__DIR__.\"/log.txt\");\n\n $columns['photo'] = \"Photo\";\n\n return $columns;\n\n}\n</code></pre>\n\n<p>OTOH, if you find the browser console more convenient, you should include a js script to <a href=\"https://developer.chrome.com/devtools/docs/console\" rel=\"nofollow\"><code>console.log()</code></a> your data. Like so:</p>\n\n<pre><code>$log_msgs=array();\n\nadd_filter('manage_edit-member_columns', 'set_custom_edit_member_columns');\n\nfunction set_custom_edit_member_columns($columns) {\n global $log_msgs;\n\n $log_msgs[]=json_encode($columns);\n\n $columns['photo'] = \"Photo\";\n\n return $columns;\n\n}\n\nfunction console_log_msgs()\n {\n global $log_msgs;\n foreach($log_msgs as $msg)\n echo \"<script>console.log($msg);</script>\";\n }\n\nadd_action('wp_footer','console_log_msgs');\n</code></pre>\n\n<p><em>(didn't test the above code, but you get the idea)</em></p>\n"
}
] |
2015/02/18
|
[
"https://wordpress.stackexchange.com/questions/178547",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/30984/"
] |
Here's a quick example of I am trying to achieve:
**I am using this filter:**
```
add_filter('manage_edit-member_columns', 'set_custom_edit_member_columns');
function set_custom_edit_member_columns($columns) {
$columns['photo'] = "Photo";
return $columns;
}
```
The function has one parameter passed ($columns). I want to see what's inside of $columns. By the example in the codex, I know it's an array with column names.
Question... how can I dump/log the values of in that array?
I am using Chrome. So I installed Chromelogger. This will let me log arrays, but it does not seem to work when it's called inside the function set\_custom\_edit\_member\_columns(). Thus, I can't get the values of $columns.
This is just an example. But, pretty much I am struggling to find a way to dump variables that are used inside functions.php or other php files that do not directly print to the page I am currently viewing.
|
If you want to keep your log on the server, try using php's [`error_log()`](http://php.net/manual/en/function.error-log.php) which is more flexible than just writing to files on disk. Something along the lines of:
```
add_filter('manage_edit-member_columns', 'set_custom_edit_member_columns');
function set_custom_edit_member_columns($columns) {
error_log(print_r($columns,true),3,__DIR__."/log.txt");
$columns['photo'] = "Photo";
return $columns;
}
```
OTOH, if you find the browser console more convenient, you should include a js script to [`console.log()`](https://developer.chrome.com/devtools/docs/console) your data. Like so:
```
$log_msgs=array();
add_filter('manage_edit-member_columns', 'set_custom_edit_member_columns');
function set_custom_edit_member_columns($columns) {
global $log_msgs;
$log_msgs[]=json_encode($columns);
$columns['photo'] = "Photo";
return $columns;
}
function console_log_msgs()
{
global $log_msgs;
foreach($log_msgs as $msg)
echo "<script>console.log($msg);</script>";
}
add_action('wp_footer','console_log_msgs');
```
*(didn't test the above code, but you get the idea)*
|
178,564 |
<p>I want to remove the last updated / last modified date from pages (not posts) via functions.php (could this be done by making that hook __null?)</p>
<p>The goal is to remove the google search result description date time stamp that shows up because of the date modified code. I only want the function to run on pages (since it usually doesn't matter when the page was last updated / created).</p>
<p>I realize this could be done by modifying the underlying code in the page template, but this method would be much easier to implement.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 178570,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>It depends on what the template uses to output whatever you're trying to remove. If you look in source at whatever function is outputting what you want to remove, they each have a filter to let you modify output where you can <code>__return_false</code> instead, however, if there's text or markup surrounding those template tags, your only option is to modify the template, preferably via a child theme.</p>\n\n<pre><code>function wpd_remove_modified_date(){\n if( is_page() ){\n add_filter( 'the_time', '__return_false' );\n add_filter( 'the_modified_time', '__return_false' );\n add_filter( 'get_the_modified_time', '__return_false' );\n add_filter( 'the_date', '__return_false' );\n add_filter( 'the_modified_date', '__return_false' );\n add_filter( 'get_the_modified_date', '__return_false' );\n }\n}\nadd_action( 'template_redirect', 'wpd_remove_modified_date' );\n</code></pre>\n"
},
{
"answer_id": 178619,
"author": "user1681839",
"author_id": 62312,
"author_profile": "https://wordpress.stackexchange.com/users/62312",
"pm_score": 0,
"selected": false,
"text": "<p>All of the code needed to work:</p>\n\n<pre><code>function wpd_remove_modified_date(){\n if( is_page() ){\n add_filter( 'the_time', '__return_false' );\n add_filter( 'the_modified_time', '__return_false' );\n add_filter( 'get_the_modified_time', '__return_false' );\n add_filter( 'the_date', '__return_false' );\n add_filter( 'the_modified_date', '__return_false' );\n add_filter( 'get_the_modified_date', '__return_false' );\n }\n}\nadd_action( 'template_redirect', 'wpd_remove_modified_date' );\n</code></pre>\n\n<p>I use a plugin called <a href=\"https://wordpress.org/plugins/code-snippets/\" rel=\"nofollow\" title=\"Wordpress Plugin Repository\">Code Snippets</a> to have this code run on all sites in my wordpress multisite installation.</p>\n"
}
] |
2015/02/18
|
[
"https://wordpress.stackexchange.com/questions/178564",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62312/"
] |
I want to remove the last updated / last modified date from pages (not posts) via functions.php (could this be done by making that hook \_\_null?)
The goal is to remove the google search result description date time stamp that shows up because of the date modified code. I only want the function to run on pages (since it usually doesn't matter when the page was last updated / created).
I realize this could be done by modifying the underlying code in the page template, but this method would be much easier to implement.
Thanks!
|
It depends on what the template uses to output whatever you're trying to remove. If you look in source at whatever function is outputting what you want to remove, they each have a filter to let you modify output where you can `__return_false` instead, however, if there's text or markup surrounding those template tags, your only option is to modify the template, preferably via a child theme.
```
function wpd_remove_modified_date(){
if( is_page() ){
add_filter( 'the_time', '__return_false' );
add_filter( 'the_modified_time', '__return_false' );
add_filter( 'get_the_modified_time', '__return_false' );
add_filter( 'the_date', '__return_false' );
add_filter( 'the_modified_date', '__return_false' );
add_filter( 'get_the_modified_date', '__return_false' );
}
}
add_action( 'template_redirect', 'wpd_remove_modified_date' );
```
|
178,566 |
<p>I have an Elegant Estate Theme and I am using Multiple Category Selection to display some posts, the Result Page is displaying the Feature SlideShow on the top, and I want to eliminate this; I want it to work just as Wordpress Search displays the result (without the Feature Slider).</p>
<p>I found out that the Multiple Category Plugin is using <code>get_bloginfo('url')</code>, the home page, to display the results. So I want to create another <code>home.php</code>, but without the slider; <code>homesearch.php</code>, but how can I call this page instead of <code>home.php</code> </p>
<p><a href="http://creta.enmty.com" rel="nofollow">This</a> is the page</p>
|
[
{
"answer_id": 178572,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>You could <a href=\"http://codex.wordpress.org/Template_Hierarchy#Filter_Hierarchy\" rel=\"nofollow\">filter <code>home_template</code></a>, check for the presence whatever <code>$_GET</code> var is reliably set for each of those requests, and load a different template for those cases.</p>\n\n<pre><code>function wpd_home_template( $home_template = '' ){\n if( isset( $_GET['search_type'] ) ){\n $home_template = locate_template( 'homesearch.php', false );\n }\n return $home_template;\n}\nadd_filter( 'home_template', 'wpd_home_template' );\n</code></pre>\n\n<p>EDIT- fixed incorrect var test.</p>\n"
},
{
"answer_id": 178721,
"author": "Nathan",
"author_id": 11952,
"author_profile": "https://wordpress.stackexchange.com/users/11952",
"pm_score": 0,
"selected": false,
"text": "<p>Can you not just create a Page Template which duplicates the home.php functionality and then remove whatever you need to from that?</p>\n\n<p><a href=\"http://codex.wordpress.org/Page_Templates\" rel=\"nofollow\">http://codex.wordpress.org/Page_Templates</a></p>\n"
}
] |
2015/02/18
|
[
"https://wordpress.stackexchange.com/questions/178566",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67757/"
] |
I have an Elegant Estate Theme and I am using Multiple Category Selection to display some posts, the Result Page is displaying the Feature SlideShow on the top, and I want to eliminate this; I want it to work just as Wordpress Search displays the result (without the Feature Slider).
I found out that the Multiple Category Plugin is using `get_bloginfo('url')`, the home page, to display the results. So I want to create another `home.php`, but without the slider; `homesearch.php`, but how can I call this page instead of `home.php`
[This](http://creta.enmty.com) is the page
|
You could [filter `home_template`](http://codex.wordpress.org/Template_Hierarchy#Filter_Hierarchy), check for the presence whatever `$_GET` var is reliably set for each of those requests, and load a different template for those cases.
```
function wpd_home_template( $home_template = '' ){
if( isset( $_GET['search_type'] ) ){
$home_template = locate_template( 'homesearch.php', false );
}
return $home_template;
}
add_filter( 'home_template', 'wpd_home_template' );
```
EDIT- fixed incorrect var test.
|
178,577 |
<p>I need to modify the outputted <code><title></title></code> tag of a few specific templates, and it has to be done in php so I can dynamically generate content for it. I've been playing around with these two snippets of code to get it to work, but so far the only change I've gotten is a duplicated title tag:</p>
<pre><code>remove_filter('wp_title','genesis_default_title', 10, 3);
add_filter('wp_title', 'process_page_titles', 10, 3);
function process_page_titles($title){
if ( is_page_template( 'landing-page-template.php' ) ) {
return 'Select Your Car';
}
elseif( is_page_template( 'dealer-page-template.php' ) ) {
return 'Select Dealers';
}
elseif( is_page_template( 'thank-you-page-template.php' ) ) {
return 'Thank You';
}
elseif( is_page_template( 'ad-page-template.php' ) ) {
return 'Deals!';
}
}
</code></pre>
<p>And this one</p>
<pre><code>remove_action('genesis_title','genesis_do_title');
add_action('genesis_title', 'process_page_titles');
function process_page_titles(){
if ( is_page_template( 'landing-page-template.php' ) ) {
echo '<title>';
wp_title( '|','Select Car','right' );
echo '</title>';
}
elseif( is_page_template( 'dealer-page-template.php' ) ) {
echo '<title>';
wp_title( '|','Select Dealer','right' );
echo '</title>';
}
elseif( is_page_template( 'thank-you-page-template.php' ) ) {
echo '<title>';
wp_title( '|','Thank You','right' );
echo '</title>';
}
elseif( is_page_template( 'ad-page-template.php' ) ) {
echo '<title>';
wp_title( '|','Deals!','right' );
echo '</title>';
}
else{
echo '<title>';
wp_title();
echo '</title>';
}
}
</code></pre>
<p>These snippets are going to be placed in a PHP file that will be required by each of these page templates; so no need to worry about affecting other page templates since its not in functions.php.</p>
|
[
{
"answer_id": 178589,
"author": "Pat Gilmour",
"author_id": 48679,
"author_profile": "https://wordpress.stackexchange.com/users/48679",
"pm_score": 2,
"selected": false,
"text": "<p>Try this to create your custom titles.</p>\n\n<pre><code>remove_filter( 'wp_title', 'genesis_default_title', 10, 3 ); //Default title\nremove_action( 'genesis_site_title', 'genesis_seo_site_title' ); //Genesis Extra Stuff\nremove_action( 'genesis_site_description', 'genesis_seo_site_description' ); //Genesis Extra Stuff\n\nadd_filter( 'wp_title', 'genesis_default_title_new', 10, 3 );\nfunction genesis_default_title_new( $title) {\n\n $title = 'Hello World!';\n return $title;\n}\n</code></pre>\n"
},
{
"answer_id": 351140,
"author": "Josh Bradley",
"author_id": 177275,
"author_profile": "https://wordpress.stackexchange.com/users/177275",
"pm_score": 1,
"selected": false,
"text": "<p>If you wanted to customize the title in the most Genesis way, you can create your own filter for <code>document_title_parts</code></p>\n<pre><code>remove_filter( 'document_title_parts', 'genesis_document_title_parts' );\nadd_filter( 'document_title_parts', 'custom_document_title_parts' );\n\nfunction custom_document_title_parts( $parts ) {\n $genesis_document_title_parts = new Genesis_SEO_Document_Title_Parts();\n $custom_document_title_parts = $genesis_document_title_parts->get_parts( $parts );\n $custom_document_title_parts['title'] = 'Hello world';\n return $custom_document_title_parts;\n}\n</code></pre>\n<hr />\n<h2>Background</h2>\n<p>In the latest version of Genesis, <code>do_action( 'genesis_title' );</code> found inside of <code>genesis/header.php</code> doesn't actually do anything. There is never an action added to <code>genesis_title</code> in the latest version.</p>\n<p>Instead, the <code><title></code> is being rendered as is rendered by <code>wp_head();</code> in <code>header.php</code>, as is standard.</p>\n<p>Genesis customizes the title by adding the filter <code>genesis_document_title_parts</code> to <code>'document_title_parts</code> located in <code>genesis/lib/structure/header.php</code>.</p>\n<p>To understand how this works you need to know what <code>document_title_parts</code> is doing. You'll find it in <code>wp-includes/general-template.php</code> within the function <code>wp_get_document_title()</code> as the last step before the title text is sanitized and returned. Because Genesis is adding a filter to this step, it is able to override the title with any custom value they choose.</p>\n<p>If you continue following the logic, you'll find that <code>wp_get_document_title()</code> is responsible for creating the title used in <code>wp_head</code>.</p>\n<p>If you want to understand how, look in <code>/wp-includes/default-filters.php</code>. There is an action added to <code>wp_head</code> for <code>_wp_render_title_tag</code>. And aha, this function simply wraps the output of <code>wp_get_document_title()</code> in <code><title></code> tags.</p>\n<p>Back to how Genesis is using this functionality to customize the title, recall that\n<code>genesis_document_title_parts</code> was added as a filter to <code>document_title_parts</code>.</p>\n<p><code>genesis_document_title_parts</code> is a function that returns a custom SEO title if it is available in the database. It uses the class <code>Genesis_SEO_Document_Title_Parts</code> found in <code>genesis/lib/classes/class-genesis-seo-document-title-parts.php</code>.</p>\n"
}
] |
2015/02/18
|
[
"https://wordpress.stackexchange.com/questions/178577",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64943/"
] |
I need to modify the outputted `<title></title>` tag of a few specific templates, and it has to be done in php so I can dynamically generate content for it. I've been playing around with these two snippets of code to get it to work, but so far the only change I've gotten is a duplicated title tag:
```
remove_filter('wp_title','genesis_default_title', 10, 3);
add_filter('wp_title', 'process_page_titles', 10, 3);
function process_page_titles($title){
if ( is_page_template( 'landing-page-template.php' ) ) {
return 'Select Your Car';
}
elseif( is_page_template( 'dealer-page-template.php' ) ) {
return 'Select Dealers';
}
elseif( is_page_template( 'thank-you-page-template.php' ) ) {
return 'Thank You';
}
elseif( is_page_template( 'ad-page-template.php' ) ) {
return 'Deals!';
}
}
```
And this one
```
remove_action('genesis_title','genesis_do_title');
add_action('genesis_title', 'process_page_titles');
function process_page_titles(){
if ( is_page_template( 'landing-page-template.php' ) ) {
echo '<title>';
wp_title( '|','Select Car','right' );
echo '</title>';
}
elseif( is_page_template( 'dealer-page-template.php' ) ) {
echo '<title>';
wp_title( '|','Select Dealer','right' );
echo '</title>';
}
elseif( is_page_template( 'thank-you-page-template.php' ) ) {
echo '<title>';
wp_title( '|','Thank You','right' );
echo '</title>';
}
elseif( is_page_template( 'ad-page-template.php' ) ) {
echo '<title>';
wp_title( '|','Deals!','right' );
echo '</title>';
}
else{
echo '<title>';
wp_title();
echo '</title>';
}
}
```
These snippets are going to be placed in a PHP file that will be required by each of these page templates; so no need to worry about affecting other page templates since its not in functions.php.
|
Try this to create your custom titles.
```
remove_filter( 'wp_title', 'genesis_default_title', 10, 3 ); //Default title
remove_action( 'genesis_site_title', 'genesis_seo_site_title' ); //Genesis Extra Stuff
remove_action( 'genesis_site_description', 'genesis_seo_site_description' ); //Genesis Extra Stuff
add_filter( 'wp_title', 'genesis_default_title_new', 10, 3 );
function genesis_default_title_new( $title) {
$title = 'Hello World!';
return $title;
}
```
|
178,586 |
<p>I am working with categories (cities) and subcategories with the same menu (for example: cars, animals, houses).</p>
<p>Therefore right now my categories structure looks like this:</p>
<pre><code>- London
-- cars
-- animals
-- houses
- Manchester
--cars
--animals
--houses
</code></pre>
<p>The slugs for each subcategory (as it seems they have to be unique), are named like this <code>category_name + subcategory_name</code> looking like <code>london-cars</code>, <code>manchester-cars</code>.</p>
<p>Now, I would like to use a different template for my main categories (cities) than for the subcategories (cars, animals, houses).</p>
<p>I've read <a href="https://stackoverflow.com/questions/3114934/make-wordpress-subcategories-use-category-template">this topic</a> that suggest a way to do it, but there's a big problem with it: I would need to create as many conditions as subcategories I have within all categories.</p>
<p>This makes it unmaintainable.</p>
<p><a href="https://wordpress.org/support/topic/different-template-for-subcategory-any-conditions" rel="nofollow noreferrer">The other option I found</a> was to create use the theme <code>category-slug.php</code>, but this would also imply that I have to create as many subcategory themes as subcategories in all sections.</p>
<p>Is there any other way to do it?</p>
|
[
{
"answer_id": 178608,
"author": "Privateer",
"author_id": 66020,
"author_profile": "https://wordpress.stackexchange.com/users/66020",
"pm_score": 2,
"selected": true,
"text": "<p>You could use the template_redirect hook to check and see if your post is a category and then whether it is a sub-category ... and if so, force a different template.</p>\n\n<p>For example (assuming you are using wordpress categories)</p>\n\n<pre><code>function my_maybe_override_category_template( $template ) {\n # Make sure you are about to show a category term\n if ( is_category() ) {\n # Grab the term that content is to be displayed for\n global $wp_query;\n $term = $wp_query->get_queried_object();\n if ( 0 < (int)$term->parent ) {\n # This term has a parent, try to find your special child term template\n $found = locate_template('template_child_categories.php');\n if ( !empty( $found ) ) {\n # Override the normal template as we found the one we created\n $template = $found;\n }\n }\n }\n}\nadd_action('template_redirect', 'my_maybe_override_category_template');\n</code></pre>\n\n<p>Unless I got something slightly off, that should do what you are wanting provided that:</p>\n\n<ul>\n<li>You create a special template called template_child_categories.php, which will be used to show your child terms.</li>\n</ul>\n"
},
{
"answer_id": 178714,
"author": "Alvaro",
"author_id": 66167,
"author_profile": "https://wordpress.stackexchange.com/users/66167",
"pm_score": 0,
"selected": false,
"text": "<p>Ended up doing this, which seems much more simple:</p>\n\n<pre><code>if (is_category()) {\n $this_category = get_category($cat);\n if (get_category_children($this_category->cat_ID) != \"\") {\n // This is the Template for Category level 1\n include(TEMPLATEPATH.'/location.php');\n }\n else{\n // This is the Template for Category level 2\n include(TEMPLATEPATH.'/subcategory.php');\n }\n} \n</code></pre>\n"
},
{
"answer_id": 320543,
"author": "sub0",
"author_id": 154946,
"author_profile": "https://wordpress.stackexchange.com/users/154946",
"pm_score": 0,
"selected": false,
"text": "<p>Problem with above structure is slugs of sub-categories. </p>\n\n<pre><code>USA > (slug: usa)\n-News (slug: news)\n-Attractions (slug: attractions)\n</code></pre>\n\n<p>Once above is done and you create same structure with more Categories, you will get problem is slugs, see example below</p>\n\n<pre><code>Canada > (slug: canada)\n-News > (slug: news-canada)\n-Attractions (slug: attractions-canada)\n</code></pre>\n\n<p>One possible solution is if you reverse the case </p>\n\n<p>Make SubCategory as Parent Category and tag them by country name, see example below. </p>\n\n<pre><code>News > Posts have tag: USA, Canada, etc\nAttractions > Posts have tag: USA, Canada, etc\n</code></pre>\n"
}
] |
2015/02/18
|
[
"https://wordpress.stackexchange.com/questions/178586",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66167/"
] |
I am working with categories (cities) and subcategories with the same menu (for example: cars, animals, houses).
Therefore right now my categories structure looks like this:
```
- London
-- cars
-- animals
-- houses
- Manchester
--cars
--animals
--houses
```
The slugs for each subcategory (as it seems they have to be unique), are named like this `category_name + subcategory_name` looking like `london-cars`, `manchester-cars`.
Now, I would like to use a different template for my main categories (cities) than for the subcategories (cars, animals, houses).
I've read [this topic](https://stackoverflow.com/questions/3114934/make-wordpress-subcategories-use-category-template) that suggest a way to do it, but there's a big problem with it: I would need to create as many conditions as subcategories I have within all categories.
This makes it unmaintainable.
[The other option I found](https://wordpress.org/support/topic/different-template-for-subcategory-any-conditions) was to create use the theme `category-slug.php`, but this would also imply that I have to create as many subcategory themes as subcategories in all sections.
Is there any other way to do it?
|
You could use the template\_redirect hook to check and see if your post is a category and then whether it is a sub-category ... and if so, force a different template.
For example (assuming you are using wordpress categories)
```
function my_maybe_override_category_template( $template ) {
# Make sure you are about to show a category term
if ( is_category() ) {
# Grab the term that content is to be displayed for
global $wp_query;
$term = $wp_query->get_queried_object();
if ( 0 < (int)$term->parent ) {
# This term has a parent, try to find your special child term template
$found = locate_template('template_child_categories.php');
if ( !empty( $found ) ) {
# Override the normal template as we found the one we created
$template = $found;
}
}
}
}
add_action('template_redirect', 'my_maybe_override_category_template');
```
Unless I got something slightly off, that should do what you are wanting provided that:
* You create a special template called template\_child\_categories.php, which will be used to show your child terms.
|
178,588 |
<p>I have an array:</p>
<pre><code> $cats = array('Hobbes', 'Simba', 'Grumpy Cat');
</code></pre>
<p>I would like to create a custom endpoint called "<a href="http://example.com/cats">http://example.com/cats</a>". Whenever you visit this URL, have it output the array as JSON:</p>
<pre><code> header('Content-Type: application/json');
$cats = array('Hobbes', 'Simba', 'Grumpy Cat');
echo json_encode($cats);
</code></pre>
<p>Ideally creating these on the fly in functions.php. So creating "/dogs" or "/birds".</p>
|
[
{
"answer_id": 178590,
"author": "Eric_WVGG",
"author_id": 67768,
"author_profile": "https://wordpress.stackexchange.com/users/67768",
"pm_score": 0,
"selected": false,
"text": "<p>I’m sure there are better ways to do it, but I’d add this to functions.php…</p>\n\n<pre><code>add_action('parse_request', 'json_cats');\nfunction json_cats() {\n if(!empty($_SERVER['REQUEST_URI']) || isset($_SERVER['argv'])) {\n $urlvars = explode('/', $_SERVER['REQUEST_URI']);\n if( ( isset($_SERVER['argv']) && count($_SERVER['argv']) > 1 && $_SERVER['argv'][1] == 'cats' ) || ( count($urlvars) > 1 && $urlvars[1] == 'cats' ) ) {\n header('Content-Type: application/json');\n $cats = array('Hobbes', 'Simba', 'Grumpy Cat');\n echo json_encode($cats);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 178591,
"author": "Uriel Hernández",
"author_id": 67767,
"author_profile": "https://wordpress.stackexchange.com/users/67767",
"pm_score": 2,
"selected": false,
"text": "<p>The easiest way I can think of (and the only one) is create a page with the permalink you're indicating, create a custom template in your theme folder, let's say it's json_output.php with the following content:</p>\n\n<pre><code><?php\n/*\n* Template Name: JSON Output\n*/\nheader('Content-Type: application/json');\n$cats = array('Hobbes', 'Simba', 'Grumpy Cat');\necho json_encode($cats);\n</code></pre>\n\n<p>When creating the page in the wordpress admin, select your new created template, in this case it has to be named JSON Output</p>\n\n<p><img src=\"https://i.stack.imgur.com/rNEtM.png\" alt=\"enter image description here\"></p>\n\n<p>There you go, publish the page and you'll get what you want:\n<img src=\"https://i.stack.imgur.com/5auNd.png\" alt=\"enter image description here\"></p>\n\n<p>Hope it helps</p>\n"
},
{
"answer_id": 178592,
"author": "pixeline",
"author_id": 82,
"author_profile": "https://wordpress.stackexchange.com/users/82",
"pm_score": 1,
"selected": false,
"text": "<p>It seems to me you could use pre_get_posts action hook to modify the query, but it feels a bit of a hack. Anyways, something like this ?</p>\n\n<pre><code>add_action( 'pre_get_posts', 'cats_endpoint' );\n\nfunction cats_endpoint($query ){\n if ( !is_admin() && $query->is_main_query() ) {\n if ($query->query_vars['post_type'] == 'cats'){\n header('Content-Type: application/json');\n $cats = array('Hobbes', 'Simba', 'Grumpy Cat');\n echo json_encode($cats);\n exit;\n }\n }\n}\n</code></pre>\n\n<p>keep in mind that pre_get_posts runs for every page request. Also, you might need to register the cats post_type (if it doesn't work out of the box).</p>\n"
},
{
"answer_id": 178596,
"author": "Ben",
"author_id": 4415,
"author_profile": "https://wordpress.stackexchange.com/users/4415",
"pm_score": 4,
"selected": true,
"text": "<p>You can use <code>pre_get_posts</code> as suggested but simply check the global <code>$wp</code> object for the request url.. like so:</p>\n\n<pre><code>add_action( 'pre_get_posts', function ($query ){\n global $wp;\n\n if ( !is_admin() && $query->is_main_query() ) {\n if ($wp->request == 'cats'){\n header('Content-Type: application/json');\n $cats = array('Hobbes', 'Simba', 'Grumpy Cat');\n echo json_encode($cats);\n exit;\n }\n }\n});\n</code></pre>\n\n<p>(PHP 5.3+ in this example)</p>\n\n<p><strong>Note 1:</strong> The <code>$query->is_main_query()</code> test is important as it will prevent it from running again in subsequent context of WP_Query instances (eg. if you use a WP_Query to fetch your list of cats, you will end up with an infinite nested loop). <code>is_admin()</code> isn't critical but it's a good practice to use. </p>\n\n<p><strong>Note 2:</strong> Wordpress seems to trim trailing slashes in <code>request</code> so this works for <code>/cats</code> & <code>/cats/</code> the same way</p>\n\n<p><strong>Note 3:</strong> You <strong>must</strong> <code>exit;</code> in your handler otherwise it will keep executing the regular wordpress workflow and likely show a 404 page.</p>\n"
},
{
"answer_id": 178597,
"author": "jphase",
"author_id": 67771,
"author_profile": "https://wordpress.stackexchange.com/users/67771",
"pm_score": 3,
"selected": false,
"text": "<p>This is the approach to add a rewrite rule for swapping out the template that WP wants to render (usually the 404 template) with something else. In your case you're just wanting to die with some JSON data so there are a bunch of different ways to do this. This is the \"by the book\" approach to adding a rewrite rule instead of a hack to check the URL on your own. Going to post this here in the event someone needs to see how this could be done to swap out the template <em>or</em> die with some encoded data.</p>\n\n<pre><code><?php\n\nfunction cats_rewrite() {\n add_rewrite_rule( 'cats/(.*)/?', 'index.php?cats=$matches[1]', 'top' );\n}\nadd_action( 'init', 'cats_rewrite' );\n\nfunction filter_query_vars( $query_vars ) {\n $query_vars[] = 'cats';\n\n return $query_vars;\n}\nadd_filter( 'query_vars', 'filter_query_vars' );\n\nfunction my_template_include( $template ) {\n global $wp_query;\n\n // You could normally swap out the template WP wants to use here, but we'll just die\n if ( isset( $wp_query->query_vars['cats'] ) && ! is_page() && ! is_single() ) {\n $wp_query->is_404 = false;\n $wp_query->is_archive = true;\n $wp_query->is_category = true;\n $cats = array( 'Hobbes', 'Simba', 'Grumpy Cat' );\n header( 'Content-Type: application/json' );\n die( json_encode( $cats ) );\n } else {\n return $template;\n }\n}\nadd_filter( 'template_include', 'my_template_include' );\n</code></pre>\n\n<p><strong>Important:</strong> don't forget to flush your permalink settings. Just visit (Admin) Settings > Permalinks. You don't even need to click <em>save</em> as the rewrite settings are \"flushed\" when you visit the admin page.</p>\n"
},
{
"answer_id": 178655,
"author": "Nathan Roberts",
"author_id": 67801,
"author_profile": "https://wordpress.stackexchange.com/users/67801",
"pm_score": 0,
"selected": false,
"text": "<p>Heres another solution</p>\n\n<pre><code><?php\n\n//Configruations\n$endpoints = array(\n '/' => array( 'homepage', '404 Not found' ),\n 'cats' => array( 'Hobbes', 'Simba', 'Grumpy Cat' ),\n 'dogs' => array( 'Hobbes Dog', 'Simba Dog', 'Grumpy Dog' ),\n 'birds' => array( 'Hobbes Bird', 'Simba Bird', 'Grumpy Bird' ),\n);\n\n//Parsing Request :: Take the last element from endpoint /abc/def/xyz\n$endpoint = isset( $_SERVER['REQUEST_URI'] ) ? strtolower( $_SERVER['REQUEST_URI'] ) : \"/\";\n$endpoint = parse_url( $endpoint, PHP_URL_PATH );\n$endpoint = array_filter(explode(\"/\", $endpoint));\n$endpoint = array_pop($endpoint);\n$endpoint = array_key_exists($endpoint, $endpoints) ? $endpoint : \"/\";\n\n//Print Response\nheader('Content-Type: application/json');\necho json_encode($endpoints[$endpoint], JSON_PRETTY_PRINT);\n</code></pre>\n"
}
] |
2015/02/18
|
[
"https://wordpress.stackexchange.com/questions/178588",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38881/"
] |
I have an array:
```
$cats = array('Hobbes', 'Simba', 'Grumpy Cat');
```
I would like to create a custom endpoint called "<http://example.com/cats>". Whenever you visit this URL, have it output the array as JSON:
```
header('Content-Type: application/json');
$cats = array('Hobbes', 'Simba', 'Grumpy Cat');
echo json_encode($cats);
```
Ideally creating these on the fly in functions.php. So creating "/dogs" or "/birds".
|
You can use `pre_get_posts` as suggested but simply check the global `$wp` object for the request url.. like so:
```
add_action( 'pre_get_posts', function ($query ){
global $wp;
if ( !is_admin() && $query->is_main_query() ) {
if ($wp->request == 'cats'){
header('Content-Type: application/json');
$cats = array('Hobbes', 'Simba', 'Grumpy Cat');
echo json_encode($cats);
exit;
}
}
});
```
(PHP 5.3+ in this example)
**Note 1:** The `$query->is_main_query()` test is important as it will prevent it from running again in subsequent context of WP\_Query instances (eg. if you use a WP\_Query to fetch your list of cats, you will end up with an infinite nested loop). `is_admin()` isn't critical but it's a good practice to use.
**Note 2:** Wordpress seems to trim trailing slashes in `request` so this works for `/cats` & `/cats/` the same way
**Note 3:** You **must** `exit;` in your handler otherwise it will keep executing the regular wordpress workflow and likely show a 404 page.
|
178,669 |
<p>So, I have a widget that I only want to show it to the page author.</p>
<p>I used the following logic: is_author()</p>
<p>However it does not seem to work (it shows non-author)</p>
<p>Am I using this logic right?</p>
<p>Any suggestions?</p>
<p>Thank you</p>
|
[
{
"answer_id": 178679,
"author": "Sean Grant",
"author_id": 67105,
"author_profile": "https://wordpress.stackexchange.com/users/67105",
"pm_score": 3,
"selected": true,
"text": "<p>is_author() is only for Archive pages. \nQuote from the Codex: </p>\n\n<blockquote>\n <p>is_author() checks if an Author archive page is being displayed</p>\n</blockquote>\n\n<p>So viewing a single Post or Page isn't going to get a TRUE from is_author().</p>\n\n<p>I think you'll want something more like this:</p>\n\n<pre><code>global $post,$current_user; // get the global variables to check\nget_currentuserinfo(); // get current user info\n// Now check if the author of this post is the same as the current logged in user\nif ($post->post_author == $current_user->ID) {\n // do code here\n}\n</code></pre>\n\n<p>I hope this helps. :)</p>\n\n<p>EDIT #1:\nShortened code version.</p>\n\n<pre><code>// Check if the author of this post is the same as the current logged in user\nif ( $post->post_author == get_current_user_id() ) {\n // do code here\n}\n</code></pre>\n"
},
{
"answer_id": 178682,
"author": "mjakic",
"author_id": 67333,
"author_profile": "https://wordpress.stackexchange.com/users/67333",
"pm_score": 0,
"selected": false,
"text": "<p>You can use:</p>\n\n<pre><code>$obj = get_queried_object();\n$user_id = get_current_user_id();\n\n// check if page's post author is same as logged in user\nif (isset($obj->post_author) && $obj->post_author == $user_id) {\n // ... do your stuff here\n}\n</code></pre>\n\n<p>With <code>get_queried_object</code> function you get object of the current page. As it's requested that page should be of \"page\" type you'll get WP_Post object of the current page (post_type = 'page').</p>\n\n<p>The <code>get_current_user_id</code> is self-explanatory.</p>\n\n<p>So if both match, you'll get code running for current user which is creator of the page.</p>\n\n<p>You can also place a check that queried object is 'page':</p>\n\n<pre><code>if ($obj instanceof WP_Post && $obj->post_type == 'page') {\n // ...\n}\n</code></pre>\n"
}
] |
2015/02/19
|
[
"https://wordpress.stackexchange.com/questions/178669",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67604/"
] |
So, I have a widget that I only want to show it to the page author.
I used the following logic: is\_author()
However it does not seem to work (it shows non-author)
Am I using this logic right?
Any suggestions?
Thank you
|
is\_author() is only for Archive pages.
Quote from the Codex:
>
> is\_author() checks if an Author archive page is being displayed
>
>
>
So viewing a single Post or Page isn't going to get a TRUE from is\_author().
I think you'll want something more like this:
```
global $post,$current_user; // get the global variables to check
get_currentuserinfo(); // get current user info
// Now check if the author of this post is the same as the current logged in user
if ($post->post_author == $current_user->ID) {
// do code here
}
```
I hope this helps. :)
EDIT #1:
Shortened code version.
```
// Check if the author of this post is the same as the current logged in user
if ( $post->post_author == get_current_user_id() ) {
// do code here
}
```
|
178,681 |
<p>I have a client whose dev team set up a wordpress site for development (dev server on a subdomain), but didn't check the "Search Engine Visibility" checkbox when creating the site and now the site is showing up in the google search engine results.</p>
<p>Will checking the box now remove it from google or are they screwed?</p>
|
[
{
"answer_id": 178679,
"author": "Sean Grant",
"author_id": 67105,
"author_profile": "https://wordpress.stackexchange.com/users/67105",
"pm_score": 3,
"selected": true,
"text": "<p>is_author() is only for Archive pages. \nQuote from the Codex: </p>\n\n<blockquote>\n <p>is_author() checks if an Author archive page is being displayed</p>\n</blockquote>\n\n<p>So viewing a single Post or Page isn't going to get a TRUE from is_author().</p>\n\n<p>I think you'll want something more like this:</p>\n\n<pre><code>global $post,$current_user; // get the global variables to check\nget_currentuserinfo(); // get current user info\n// Now check if the author of this post is the same as the current logged in user\nif ($post->post_author == $current_user->ID) {\n // do code here\n}\n</code></pre>\n\n<p>I hope this helps. :)</p>\n\n<p>EDIT #1:\nShortened code version.</p>\n\n<pre><code>// Check if the author of this post is the same as the current logged in user\nif ( $post->post_author == get_current_user_id() ) {\n // do code here\n}\n</code></pre>\n"
},
{
"answer_id": 178682,
"author": "mjakic",
"author_id": 67333,
"author_profile": "https://wordpress.stackexchange.com/users/67333",
"pm_score": 0,
"selected": false,
"text": "<p>You can use:</p>\n\n<pre><code>$obj = get_queried_object();\n$user_id = get_current_user_id();\n\n// check if page's post author is same as logged in user\nif (isset($obj->post_author) && $obj->post_author == $user_id) {\n // ... do your stuff here\n}\n</code></pre>\n\n<p>With <code>get_queried_object</code> function you get object of the current page. As it's requested that page should be of \"page\" type you'll get WP_Post object of the current page (post_type = 'page').</p>\n\n<p>The <code>get_current_user_id</code> is self-explanatory.</p>\n\n<p>So if both match, you'll get code running for current user which is creator of the page.</p>\n\n<p>You can also place a check that queried object is 'page':</p>\n\n<pre><code>if ($obj instanceof WP_Post && $obj->post_type == 'page') {\n // ...\n}\n</code></pre>\n"
}
] |
2015/02/19
|
[
"https://wordpress.stackexchange.com/questions/178681",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67810/"
] |
I have a client whose dev team set up a wordpress site for development (dev server on a subdomain), but didn't check the "Search Engine Visibility" checkbox when creating the site and now the site is showing up in the google search engine results.
Will checking the box now remove it from google or are they screwed?
|
is\_author() is only for Archive pages.
Quote from the Codex:
>
> is\_author() checks if an Author archive page is being displayed
>
>
>
So viewing a single Post or Page isn't going to get a TRUE from is\_author().
I think you'll want something more like this:
```
global $post,$current_user; // get the global variables to check
get_currentuserinfo(); // get current user info
// Now check if the author of this post is the same as the current logged in user
if ($post->post_author == $current_user->ID) {
// do code here
}
```
I hope this helps. :)
EDIT #1:
Shortened code version.
```
// Check if the author of this post is the same as the current logged in user
if ( $post->post_author == get_current_user_id() ) {
// do code here
}
```
|
178,684 |
<p>i want to remove screen options from wordpress admin panel and remove default dashboard items and add quick draft widget in dashboard for custom post type "gallery".
<img src="https://i.stack.imgur.com/4E4sP.png" alt="enter image description here"></p>
|
[
{
"answer_id": 178688,
"author": "mikemanger",
"author_id": 48357,
"author_profile": "https://wordpress.stackexchange.com/users/48357",
"pm_score": 2,
"selected": true,
"text": "<p>You can remove the Screen Options with the 'screen_options_show_screen' filter.</p>\n\n<pre><code>function myplugin_disable_screen_options( $show_screen ) {\n // Logic to allow admins to still access the menu\n if ( current_user_can( 'manage_options' ) ) {\n return $show_screen;\n }\n return false;\n}\nadd_filter( 'screen_options_show_screen', 'myplugin_disable_screen_options' );\n</code></pre>\n"
},
{
"answer_id": 178784,
"author": "Shahrukh Khan",
"author_id": 67596,
"author_profile": "https://wordpress.stackexchange.com/users/67596",
"pm_score": 3,
"selected": false,
"text": "<p>To remove all the wordpress default items use the code given below.</p>\n\n<pre><code>function remove_dashboard_meta() {\n remove_meta_box( 'dashboard_incoming_links', 'dashboard', 'normal' );\n remove_meta_box( 'dashboard_plugins', 'dashboard', 'normal' );\n remove_meta_box( 'dashboard_primary', 'dashboard', 'side' );\n remove_meta_box( 'dashboard_secondary', 'dashboard', 'normal' );\n remove_meta_box( 'dashboard_quick_press', 'dashboard', 'side' );\n remove_meta_box( 'dashboard_recent_drafts', 'dashboard', 'side' );\n remove_meta_box( 'dashboard_recent_comments', 'dashboard', 'normal' );\n remove_meta_box( 'dashboard_right_now', 'dashboard', 'normal' );\n remove_meta_box( 'dashboard_activity', 'dashboard', 'normal');//since 3.8\n}\nadd_action( 'admin_init', 'remove_dashboard_meta' );\n</code></pre>\n"
}
] |
2015/02/19
|
[
"https://wordpress.stackexchange.com/questions/178684",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67596/"
] |
i want to remove screen options from wordpress admin panel and remove default dashboard items and add quick draft widget in dashboard for custom post type "gallery".

|
You can remove the Screen Options with the 'screen\_options\_show\_screen' filter.
```
function myplugin_disable_screen_options( $show_screen ) {
// Logic to allow admins to still access the menu
if ( current_user_can( 'manage_options' ) ) {
return $show_screen;
}
return false;
}
add_filter( 'screen_options_show_screen', 'myplugin_disable_screen_options' );
```
|
178,693 |
<p>I Write Code to Save data in the Wordpress database table (table name is wp_fafa)</p>
<p>But Can't Save data in </p>
<pre><code>$qry = $wpdb->query( "INSERT INTO `wp_fafa` (titile,liveprice,changing,lowest,topest,time) VALUES ('" . trim($row->item(0)->nodeValue) . "','" . trim($row->item(2)->nodeValue) . "','" . trim($row->item(4)->nodeValue) . "','" . trim($row->item(6)->nodeValue) . "','" . trim($row->item(8)->nodeValue) . "','" . trim($row->item(10)->nodeValue) . "')");
$wpdb->query($qry);
</code></pre>
|
[
{
"answer_id": 178688,
"author": "mikemanger",
"author_id": 48357,
"author_profile": "https://wordpress.stackexchange.com/users/48357",
"pm_score": 2,
"selected": true,
"text": "<p>You can remove the Screen Options with the 'screen_options_show_screen' filter.</p>\n\n<pre><code>function myplugin_disable_screen_options( $show_screen ) {\n // Logic to allow admins to still access the menu\n if ( current_user_can( 'manage_options' ) ) {\n return $show_screen;\n }\n return false;\n}\nadd_filter( 'screen_options_show_screen', 'myplugin_disable_screen_options' );\n</code></pre>\n"
},
{
"answer_id": 178784,
"author": "Shahrukh Khan",
"author_id": 67596,
"author_profile": "https://wordpress.stackexchange.com/users/67596",
"pm_score": 3,
"selected": false,
"text": "<p>To remove all the wordpress default items use the code given below.</p>\n\n<pre><code>function remove_dashboard_meta() {\n remove_meta_box( 'dashboard_incoming_links', 'dashboard', 'normal' );\n remove_meta_box( 'dashboard_plugins', 'dashboard', 'normal' );\n remove_meta_box( 'dashboard_primary', 'dashboard', 'side' );\n remove_meta_box( 'dashboard_secondary', 'dashboard', 'normal' );\n remove_meta_box( 'dashboard_quick_press', 'dashboard', 'side' );\n remove_meta_box( 'dashboard_recent_drafts', 'dashboard', 'side' );\n remove_meta_box( 'dashboard_recent_comments', 'dashboard', 'normal' );\n remove_meta_box( 'dashboard_right_now', 'dashboard', 'normal' );\n remove_meta_box( 'dashboard_activity', 'dashboard', 'normal');//since 3.8\n}\nadd_action( 'admin_init', 'remove_dashboard_meta' );\n</code></pre>\n"
}
] |
2015/02/19
|
[
"https://wordpress.stackexchange.com/questions/178693",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48589/"
] |
I Write Code to Save data in the Wordpress database table (table name is wp\_fafa)
But Can't Save data in
```
$qry = $wpdb->query( "INSERT INTO `wp_fafa` (titile,liveprice,changing,lowest,topest,time) VALUES ('" . trim($row->item(0)->nodeValue) . "','" . trim($row->item(2)->nodeValue) . "','" . trim($row->item(4)->nodeValue) . "','" . trim($row->item(6)->nodeValue) . "','" . trim($row->item(8)->nodeValue) . "','" . trim($row->item(10)->nodeValue) . "')");
$wpdb->query($qry);
```
|
You can remove the Screen Options with the 'screen\_options\_show\_screen' filter.
```
function myplugin_disable_screen_options( $show_screen ) {
// Logic to allow admins to still access the menu
if ( current_user_can( 'manage_options' ) ) {
return $show_screen;
}
return false;
}
add_filter( 'screen_options_show_screen', 'myplugin_disable_screen_options' );
```
|
178,707 |
<p>I'm unclear on the <code>get_the_foo()</code> style of functions, for example <code>get_the_permalink()</code>.</p>
<p>My main question is: when this is performed in The Loop, is another SQL query executed (besides the original <code>WP_Query()</code>)?</p>
<p>But: if performed by itself, e.g. <code>get_the_permalink($someId)</code>, a query <em>is</em> executed, correct?</p>
|
[
{
"answer_id": 178688,
"author": "mikemanger",
"author_id": 48357,
"author_profile": "https://wordpress.stackexchange.com/users/48357",
"pm_score": 2,
"selected": true,
"text": "<p>You can remove the Screen Options with the 'screen_options_show_screen' filter.</p>\n\n<pre><code>function myplugin_disable_screen_options( $show_screen ) {\n // Logic to allow admins to still access the menu\n if ( current_user_can( 'manage_options' ) ) {\n return $show_screen;\n }\n return false;\n}\nadd_filter( 'screen_options_show_screen', 'myplugin_disable_screen_options' );\n</code></pre>\n"
},
{
"answer_id": 178784,
"author": "Shahrukh Khan",
"author_id": 67596,
"author_profile": "https://wordpress.stackexchange.com/users/67596",
"pm_score": 3,
"selected": false,
"text": "<p>To remove all the wordpress default items use the code given below.</p>\n\n<pre><code>function remove_dashboard_meta() {\n remove_meta_box( 'dashboard_incoming_links', 'dashboard', 'normal' );\n remove_meta_box( 'dashboard_plugins', 'dashboard', 'normal' );\n remove_meta_box( 'dashboard_primary', 'dashboard', 'side' );\n remove_meta_box( 'dashboard_secondary', 'dashboard', 'normal' );\n remove_meta_box( 'dashboard_quick_press', 'dashboard', 'side' );\n remove_meta_box( 'dashboard_recent_drafts', 'dashboard', 'side' );\n remove_meta_box( 'dashboard_recent_comments', 'dashboard', 'normal' );\n remove_meta_box( 'dashboard_right_now', 'dashboard', 'normal' );\n remove_meta_box( 'dashboard_activity', 'dashboard', 'normal');//since 3.8\n}\nadd_action( 'admin_init', 'remove_dashboard_meta' );\n</code></pre>\n"
}
] |
2015/02/19
|
[
"https://wordpress.stackexchange.com/questions/178707",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52625/"
] |
I'm unclear on the `get_the_foo()` style of functions, for example `get_the_permalink()`.
My main question is: when this is performed in The Loop, is another SQL query executed (besides the original `WP_Query()`)?
But: if performed by itself, e.g. `get_the_permalink($someId)`, a query *is* executed, correct?
|
You can remove the Screen Options with the 'screen\_options\_show\_screen' filter.
```
function myplugin_disable_screen_options( $show_screen ) {
// Logic to allow admins to still access the menu
if ( current_user_can( 'manage_options' ) ) {
return $show_screen;
}
return false;
}
add_filter( 'screen_options_show_screen', 'myplugin_disable_screen_options' );
```
|
178,744 |
<p>So I'm displaying 3 different layout types, one for pages, one for posts (blog, archives, tags, search etc..) and one for single posts.</p>
<p>Originally, I was using this to decide whether I was on a page which displayed posts:</p>
<pre><code>if ( is_home() ||
is_category() ||
is_tag() ||
is_archive() ||
is_tax() ||
is_author() ||
is_date() ||
is_search() ||
is_attachment() ) :
</code></pre>
<p>It's not pretty, but it covers everything.</p>
<p>My question is, is this practically the same thing, but cleaner?</p>
<pre><code>if ( ! is_page() && ! is_single() ) :
</code></pre>
<p>Does that cover everything in the first block of code? Am I missing something completely obvious that will cause this to not work as intended?</p>
<p>I think it does the same thing, but I wanted to bounce this off the community as well.</p>
<p>Thanks!</p>
<p><strong>EDIT</strong> - here's what I have now:</p>
<pre><code>// Set up the layout variable for pages
$layout = $generate_settings['layout_setting'];
// If we're on the single post page
if ( is_single() ) :
$layout = null;
$layout = $generate_settings['single_layout_setting'];
endif;
// If we're on the blog, archive, attachment etc..
if ( is_home() || is_archive() || is_search() || is_attachment() || is_tax() ) :
$layout = null;
$layout = $generate_settings['blog_layout_setting'];
endif;
// Finally, return the layout
return apply_filters( 'generate_sidebar_layout', $layout );
</code></pre>
<p>Seems to work perfectly, and is cleaner than my original group of conditionals.</p>
<p>I couldn't find any proof that is_tax is taken care of by is_archive() - did I just miss it?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 178766,
"author": "Evan Van Slooten",
"author_id": 67781,
"author_profile": "https://wordpress.stackexchange.com/users/67781",
"pm_score": 1,
"selected": false,
"text": "<p>To answer the question, no it's not the same. It is cleaner, but for example a home page can have true results for is_page and is_single.</p>\n\n<p>Additionally, why are you making these checks for template display? There isn't enough detail to be sure, but it sounds like you could utilize the Wordpress template hierarchy to accomplish this without any checks and a much neater file organization / code separation. </p>\n"
},
{
"answer_id": 178769,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>Both will do the same job in the end of the day. You can however improve on the first code.</p>\n\n<p><code>is_archive()</code> returns <code>true</code> on all archives page, which includes the following</p>\n\n<ul>\n<li><p>taxonomy archive pages</p></li>\n<li><p>category archive pages</p></li>\n<li><p>date archive pages</p></li>\n<li><p>author archive pages</p></li>\n<li><p>tag archive pages</p></li>\n</ul>\n\n<p>So, if you need to target all these pages, you can simply make use of <code>is_archive()</code>. </p>\n\n<h2>ONE OTHER NOTE</h2>\n\n<p><code>is_single()</code> returns true when <code>is_attachment()</code> return true as an attachment is also a single post. So be careful when using the second block of code when you need something different on attachment pages and normal single pages</p>\n\n<h2>IN GENERAL</h2>\n\n<p>There are a few things that I don't get on your implementation. You can do what you need to do with the correct templates. You do not need conditionals</p>\n\n<p>Look at the <a href=\"http://codex.wordpress.org/Template_Hierarchy\" rel=\"nofollow\">Template Hierarchy</a>, and then look what you need to achieve. You only need 4 templates</p>\n\n<ul>\n<li><p>For pages - Create <code>page.php</code></p></li>\n<li><p>For home, archive and search pages, create <code>index.php</code>. <code>index.php</code> is a fall back if the custom templates (like <code>search.php</code> or <code>category.php</code>) don't exist. So Wordpress will use <code>index.php</code> to show the homepage, archives and search result pages</p></li>\n<li><p>For attachements, copy <code>index.php</code> and rename it <code>attachment.php</code></p></li>\n<li><p>For single posts, create <code>single.php</code>. This should be more than enough</p></li>\n</ul>\n"
}
] |
2015/02/20
|
[
"https://wordpress.stackexchange.com/questions/178744",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10946/"
] |
So I'm displaying 3 different layout types, one for pages, one for posts (blog, archives, tags, search etc..) and one for single posts.
Originally, I was using this to decide whether I was on a page which displayed posts:
```
if ( is_home() ||
is_category() ||
is_tag() ||
is_archive() ||
is_tax() ||
is_author() ||
is_date() ||
is_search() ||
is_attachment() ) :
```
It's not pretty, but it covers everything.
My question is, is this practically the same thing, but cleaner?
```
if ( ! is_page() && ! is_single() ) :
```
Does that cover everything in the first block of code? Am I missing something completely obvious that will cause this to not work as intended?
I think it does the same thing, but I wanted to bounce this off the community as well.
Thanks!
**EDIT** - here's what I have now:
```
// Set up the layout variable for pages
$layout = $generate_settings['layout_setting'];
// If we're on the single post page
if ( is_single() ) :
$layout = null;
$layout = $generate_settings['single_layout_setting'];
endif;
// If we're on the blog, archive, attachment etc..
if ( is_home() || is_archive() || is_search() || is_attachment() || is_tax() ) :
$layout = null;
$layout = $generate_settings['blog_layout_setting'];
endif;
// Finally, return the layout
return apply_filters( 'generate_sidebar_layout', $layout );
```
Seems to work perfectly, and is cleaner than my original group of conditionals.
I couldn't find any proof that is\_tax is taken care of by is\_archive() - did I just miss it?
Thanks!
|
Both will do the same job in the end of the day. You can however improve on the first code.
`is_archive()` returns `true` on all archives page, which includes the following
* taxonomy archive pages
* category archive pages
* date archive pages
* author archive pages
* tag archive pages
So, if you need to target all these pages, you can simply make use of `is_archive()`.
ONE OTHER NOTE
--------------
`is_single()` returns true when `is_attachment()` return true as an attachment is also a single post. So be careful when using the second block of code when you need something different on attachment pages and normal single pages
IN GENERAL
----------
There are a few things that I don't get on your implementation. You can do what you need to do with the correct templates. You do not need conditionals
Look at the [Template Hierarchy](http://codex.wordpress.org/Template_Hierarchy), and then look what you need to achieve. You only need 4 templates
* For pages - Create `page.php`
* For home, archive and search pages, create `index.php`. `index.php` is a fall back if the custom templates (like `search.php` or `category.php`) don't exist. So Wordpress will use `index.php` to show the homepage, archives and search result pages
* For attachements, copy `index.php` and rename it `attachment.php`
* For single posts, create `single.php`. This should be more than enough
|
178,750 |
<p>I am creating a plugin that needs to display external data, not wordpress posts.</p>
<p>What I have done: registered rewrites so wp recognizes my archive/single URLs, hooked into <code>template_include</code> to direct it to use my template if the requested URL was one of mine, and then in the template I call a function to load the external data and display it in post/archive format.</p>
<p>This works fine as long as I dont switch templates. Unfotunately, there is a variation in twentyfourteen and twentyfifteen template structure, in which <code>#content</code> and <code>#main</code> are inverted.</p>
<ul>
<li>TwentyFifteen: <code>body > #page > #content > #primary > #main</code></li>
<li>TwentyFourteen: <code>body > #page > #main > #primary > #content</code></li>
</ul>
<p>This means that whatever one I code my plugin template for, it is broken in the other.</p>
<p><code>twentyfifteen/single.php</code></p>
<pre><code>get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
// Start the loop.
while ( have_posts() ) : the_post();
</code></pre>
<p><code>twentyfourteen/single.php</code></p>
<pre><code>get_header(); ?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php
// Start the Loop.
while ( have_posts() ) : the_post();
</code></pre>
<p>So my question(s) are:</p>
<ul>
<li>Am I going about this the right way? Do you know of a better way to inject external data?</li>
<li>Why are twentyfifteen tags inverted? Is this not a bug? Because I checked going back to twentlyeleven, and they are all in the order ...#main > #primary > #content.</li>
<li>Is there a way to do this, without requiring including a template, so that it works on more sites? The templates are going to be problematic on each site the plugin is used on, for just such reasons. I would prefer to forgo including a template, and somehow hook into archive.php and single.php to display my content, given the URL matches one of my requests.</li>
</ul>
|
[
{
"answer_id": 178766,
"author": "Evan Van Slooten",
"author_id": 67781,
"author_profile": "https://wordpress.stackexchange.com/users/67781",
"pm_score": 1,
"selected": false,
"text": "<p>To answer the question, no it's not the same. It is cleaner, but for example a home page can have true results for is_page and is_single.</p>\n\n<p>Additionally, why are you making these checks for template display? There isn't enough detail to be sure, but it sounds like you could utilize the Wordpress template hierarchy to accomplish this without any checks and a much neater file organization / code separation. </p>\n"
},
{
"answer_id": 178769,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>Both will do the same job in the end of the day. You can however improve on the first code.</p>\n\n<p><code>is_archive()</code> returns <code>true</code> on all archives page, which includes the following</p>\n\n<ul>\n<li><p>taxonomy archive pages</p></li>\n<li><p>category archive pages</p></li>\n<li><p>date archive pages</p></li>\n<li><p>author archive pages</p></li>\n<li><p>tag archive pages</p></li>\n</ul>\n\n<p>So, if you need to target all these pages, you can simply make use of <code>is_archive()</code>. </p>\n\n<h2>ONE OTHER NOTE</h2>\n\n<p><code>is_single()</code> returns true when <code>is_attachment()</code> return true as an attachment is also a single post. So be careful when using the second block of code when you need something different on attachment pages and normal single pages</p>\n\n<h2>IN GENERAL</h2>\n\n<p>There are a few things that I don't get on your implementation. You can do what you need to do with the correct templates. You do not need conditionals</p>\n\n<p>Look at the <a href=\"http://codex.wordpress.org/Template_Hierarchy\" rel=\"nofollow\">Template Hierarchy</a>, and then look what you need to achieve. You only need 4 templates</p>\n\n<ul>\n<li><p>For pages - Create <code>page.php</code></p></li>\n<li><p>For home, archive and search pages, create <code>index.php</code>. <code>index.php</code> is a fall back if the custom templates (like <code>search.php</code> or <code>category.php</code>) don't exist. So Wordpress will use <code>index.php</code> to show the homepage, archives and search result pages</p></li>\n<li><p>For attachements, copy <code>index.php</code> and rename it <code>attachment.php</code></p></li>\n<li><p>For single posts, create <code>single.php</code>. This should be more than enough</p></li>\n</ul>\n"
}
] |
2015/02/20
|
[
"https://wordpress.stackexchange.com/questions/178750",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67850/"
] |
I am creating a plugin that needs to display external data, not wordpress posts.
What I have done: registered rewrites so wp recognizes my archive/single URLs, hooked into `template_include` to direct it to use my template if the requested URL was one of mine, and then in the template I call a function to load the external data and display it in post/archive format.
This works fine as long as I dont switch templates. Unfotunately, there is a variation in twentyfourteen and twentyfifteen template structure, in which `#content` and `#main` are inverted.
* TwentyFifteen: `body > #page > #content > #primary > #main`
* TwentyFourteen: `body > #page > #main > #primary > #content`
This means that whatever one I code my plugin template for, it is broken in the other.
`twentyfifteen/single.php`
```
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
// Start the loop.
while ( have_posts() ) : the_post();
```
`twentyfourteen/single.php`
```
get_header(); ?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php
// Start the Loop.
while ( have_posts() ) : the_post();
```
So my question(s) are:
* Am I going about this the right way? Do you know of a better way to inject external data?
* Why are twentyfifteen tags inverted? Is this not a bug? Because I checked going back to twentlyeleven, and they are all in the order ...#main > #primary > #content.
* Is there a way to do this, without requiring including a template, so that it works on more sites? The templates are going to be problematic on each site the plugin is used on, for just such reasons. I would prefer to forgo including a template, and somehow hook into archive.php and single.php to display my content, given the URL matches one of my requests.
|
Both will do the same job in the end of the day. You can however improve on the first code.
`is_archive()` returns `true` on all archives page, which includes the following
* taxonomy archive pages
* category archive pages
* date archive pages
* author archive pages
* tag archive pages
So, if you need to target all these pages, you can simply make use of `is_archive()`.
ONE OTHER NOTE
--------------
`is_single()` returns true when `is_attachment()` return true as an attachment is also a single post. So be careful when using the second block of code when you need something different on attachment pages and normal single pages
IN GENERAL
----------
There are a few things that I don't get on your implementation. You can do what you need to do with the correct templates. You do not need conditionals
Look at the [Template Hierarchy](http://codex.wordpress.org/Template_Hierarchy), and then look what you need to achieve. You only need 4 templates
* For pages - Create `page.php`
* For home, archive and search pages, create `index.php`. `index.php` is a fall back if the custom templates (like `search.php` or `category.php`) don't exist. So Wordpress will use `index.php` to show the homepage, archives and search result pages
* For attachements, copy `index.php` and rename it `attachment.php`
* For single posts, create `single.php`. This should be more than enough
|
178,762 |
<p>I have added a select box in the Post meta. Here is the code, and it works fine. My question is, do I need to sanitize the values before updating the post meta? If yes, how it should be done?</p>
<p>This is how I'm adding the meta field:</p>
<pre><code><?php $value = get_post_meta( $post->ID, 'my_options', true ); ?>
<select name="my_options">
<option value="option1" <?php selected( $value, 'option1'); ?>><?php _e('Option 1', 'textdomain'); ?></option>
<option value="option2" <?php selected( $value, 'option2'); ?>><?php _e('Option 2', 'textdomain'); ?></option>
</select>
</code></pre>
<p>and this is how I'm updating the value:</p>
<pre><code>if ( isset( $_POST['my_options'] )){
update_post_meta( $post->ID, 'my_options', $_POST['my_options'] );
}
</code></pre>
|
[
{
"answer_id": 178770,
"author": "Evan Van Slooten",
"author_id": 67781,
"author_profile": "https://wordpress.stackexchange.com/users/67781",
"pm_score": 0,
"selected": false,
"text": "<p>You can use any of the sanitation functions built into Wordpress (such as <a href=\"http://codex.wordpress.org/Function_Reference/sanitize_text_field\" rel=\"nofollow\">sanitize_text_field</a>). Alternatively, if you are worried about specific elements being injected into the select options you can write you own sanitation function with the <a href=\"http://codex.wordpress.org/Function_Reference/sanitize_meta\" rel=\"nofollow\">sanitize_meta</a> function.</p>\n"
},
{
"answer_id": 178785,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 4,
"selected": true,
"text": "<p>When accepting user data inputs, I think that data validation must be performed if possible, not only sanitization. For example, you could expect a number, a bool value, a text string (even when the input is a selectbox it can have a string value), etc. You can santize for that data types; then you can go further and validate the data against expected values: integer, float, true/false, emails, URLs, and so on.</p>\n\n<p>Let's go with your selectbox. It has two options with the values \"option1\" and \"option2\", so both are strings and can be sanitized it with <code>sanitize_text_field</code>:</p>\n\n<pre><code>if ( isset( $_POST['my_options'] )){\n\n $value = sanitize_text_field( $_POST['my_options'] );\n\n update_post_meta( $post->ID, 'my_options', $value ); \n\n}\n</code></pre>\n\n<p>But a user can change the value of the form select options easily from the frontend, so he/she can manipulate the form and send values different to \"option1\" or \"option2\" that you will store in the database. As you know exactly what the expected values are, you can do a data sanitization and data validation. For example:</p>\n\n<pre><code>if ( isset( $_POST['my_options'] )){\n\n $valid_values = array(\n 'option1',\n 'option2',\n );\n\n $value = sanitize_text_field( $_POST['my_options'] );\n\n if( in_array( $value, $valid_values ) ) {\n\n update_post_meta( $post->ID, 'my_options', $value );\n\n }\n\n}\n</code></pre>\n\n<p>Or you can define a custom sanitization callback for \"my_options\" option and use <code>sanitize_meta</code>:</p>\n\n<pre><code>if ( isset( $_POST['my_options'] ) ){\n\n $value = sanitize_meta( 'my_options', $_POST['my_options'], 'post' )\n\n update_post_meta( $post->ID, 'my_options', $value );\n\n}\n</code></pre>\n\n<p>And define the santitization callback:</p>\n\n<pre><code>add_filter( 'sanitize_post_meta_my_options', 'sanitize_my_options_meta' );\n\nfunction sanitize_my_options_meta( $value ) {\n\n $value = sanitize_text_field( $value );\n\n $valid_values = array(\n 'option1',\n 'option2',\n );\n\n if( ! in_array( $value, $valid_values ) ) {\n\n wp_die( 'Invalid value, go back and try again.' );\n }\n\n return $value;\n}\n</code></pre>\n"
}
] |
2015/02/20
|
[
"https://wordpress.stackexchange.com/questions/178762",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67310/"
] |
I have added a select box in the Post meta. Here is the code, and it works fine. My question is, do I need to sanitize the values before updating the post meta? If yes, how it should be done?
This is how I'm adding the meta field:
```
<?php $value = get_post_meta( $post->ID, 'my_options', true ); ?>
<select name="my_options">
<option value="option1" <?php selected( $value, 'option1'); ?>><?php _e('Option 1', 'textdomain'); ?></option>
<option value="option2" <?php selected( $value, 'option2'); ?>><?php _e('Option 2', 'textdomain'); ?></option>
</select>
```
and this is how I'm updating the value:
```
if ( isset( $_POST['my_options'] )){
update_post_meta( $post->ID, 'my_options', $_POST['my_options'] );
}
```
|
When accepting user data inputs, I think that data validation must be performed if possible, not only sanitization. For example, you could expect a number, a bool value, a text string (even when the input is a selectbox it can have a string value), etc. You can santize for that data types; then you can go further and validate the data against expected values: integer, float, true/false, emails, URLs, and so on.
Let's go with your selectbox. It has two options with the values "option1" and "option2", so both are strings and can be sanitized it with `sanitize_text_field`:
```
if ( isset( $_POST['my_options'] )){
$value = sanitize_text_field( $_POST['my_options'] );
update_post_meta( $post->ID, 'my_options', $value );
}
```
But a user can change the value of the form select options easily from the frontend, so he/she can manipulate the form and send values different to "option1" or "option2" that you will store in the database. As you know exactly what the expected values are, you can do a data sanitization and data validation. For example:
```
if ( isset( $_POST['my_options'] )){
$valid_values = array(
'option1',
'option2',
);
$value = sanitize_text_field( $_POST['my_options'] );
if( in_array( $value, $valid_values ) ) {
update_post_meta( $post->ID, 'my_options', $value );
}
}
```
Or you can define a custom sanitization callback for "my\_options" option and use `sanitize_meta`:
```
if ( isset( $_POST['my_options'] ) ){
$value = sanitize_meta( 'my_options', $_POST['my_options'], 'post' )
update_post_meta( $post->ID, 'my_options', $value );
}
```
And define the santitization callback:
```
add_filter( 'sanitize_post_meta_my_options', 'sanitize_my_options_meta' );
function sanitize_my_options_meta( $value ) {
$value = sanitize_text_field( $value );
$valid_values = array(
'option1',
'option2',
);
if( ! in_array( $value, $valid_values ) ) {
wp_die( 'Invalid value, go back and try again.' );
}
return $value;
}
```
|
178,780 |
<p>Im using the next post link function of WP to show next and previous navigation links to the "next post in same category" all good with this...the issue i have is that when I'm in the "last" post of a category, the "NEXT" link appears anyway and doing what i dont want: linking to a different category 1st post. the same with the 1st post of a category, when browsing the first post of a category the "PREVIOUS" link appears linking to previous post of a another different category... I would like that in the 1st and last post, this links aren't shown.</p>
<pre><code><div id="nav-above" class="navigation">
<div class="nav-previous"><?php previous_post_linknext_post_link( '%link', '<span class="meta-nav">' .
_x( '&#9668; Previous', 'Previous post link','category' ,TRUE ) . '</span>' ); ?></div>
<div class="nav-next"><?php next_post_link( '%link', '<span class="meta-nav">' . _x( 'Next &#9658; ', 'Next post link', 'category',TRUE ) . '</span>' ); ?> </div>
</div><!-- #nav-above -->
</code></pre>
<p><a href="http://codex.wordpress.org/Function_Reference/next_post_link" rel="nofollow">http://codex.wordpress.org/Function_Reference/next_post_link</a></p>
|
[
{
"answer_id": 178789,
"author": "David Gard",
"author_id": 10097,
"author_profile": "https://wordpress.stackexchange.com/users/10097",
"pm_score": 4,
"selected": true,
"text": "<p>You can do this by using <a href=\"http://codex.wordpress.org/Function_Reference/previous_post_link\" rel=\"nofollow noreferrer\"><code>previous_post_link()</code></a> and <a href=\"http://codex.wordpress.org/Function_Reference/next_post_link\" rel=\"nofollow noreferrer\"><code>next_post_link()</code></a>.</p>\n<p>These functions will create the links for you, and you should be able to get rid of all of the logic you are using for pagination.</p>\n<p>As you wish to only link to posts in the same category you should use the functions with the following parameters:</p>\n<pre><code>previous_post_link('&laquo; %link', '%title', true);\nnext_post_link('%link &raquo;', '%title', true);\n</code></pre>\n<hr />\n<h1>Update</h1>\n<p>In response to your updated question with regard to your issue of previous/next linking when they are the first/last post, please see this line from the Codex of both <a href=\"http://codex.wordpress.org/Function_Reference/previous_post_link\" rel=\"nofollow noreferrer\"><code>previous_post_link()</code></a> and <a href=\"http://codex.wordpress.org/Function_Reference/next_post_link\" rel=\"nofollow noreferrer\"><code>next_post_link()</code></a> in relation to the <code>$in_same_term</code> parameter:</p>\n<blockquote>\n<p>Indicates whether next post must be within the same taxonomy term as the current post. If set to 'true', only posts from the current taxonomy term will be displayed. If the post is in both the parent and subcategory, or more than one term, the next post link will lead to the next post in any of those terms.</p>\n</blockquote>\n<p>With that in mind, I suspect your first last Posts may be associated with more than one category? If that's the case the <code>wp_get_object_terms</code> filter may be able to help.</p>\n<p>In your original question (pre-edit) you were only searching for posts in the very first category, so I'll apply that logic here:</p>\n<pre><code><?php add_filter('wp_get_object_terms', 'my_custom_post_navigation', 4, 99); ?>\n<div id="nav-above" class="navigation">\n <div class="nav-previous">\n <?php previous_post_link( '<span class="meta-nav"> %link </span>', _x( '&#9668; Previous', 'Previous post link', 'category') , TRUE ); ?>\n </div>\n <div class="nav-previous">\n <?php next_post_link( '<span class="meta-nav"> %link </span>', _x( 'Next &#9658;', 'Next post link', 'category') , TRUE ); ?>\n </div>\n</div><!-- #nav-above -->\n<?php remove_filter('wp_get_object_terms', 'my_custom_post_navigation', 99); ?>\n</code></pre>\n<p>In addition to the above, you should place this in your <strong>functions.php</strong> file:</p>\n<pre><code>/**\n * Return only the first category when outputting the previous/next post links\n */\nfunction my_custom_post_navigation($terms, $object_ids, $taxonomies, $args){\n \n return array_slice($terms, 0, 1);\n \n}\n</code></pre>\n"
},
{
"answer_id": 264331,
"author": "Muhammad Usama",
"author_id": 59878,
"author_profile": "https://wordpress.stackexchange.com/users/59878",
"pm_score": 1,
"selected": false,
"text": "<p>If you need to restrict prev or next post link for specific <strong>custom taxonomy</strong> or <strong>term</strong>, <strong>custom post type</strong>, <strong>custom field</strong> or <strong>format</strong> then you should try <a href=\"https://wordpress.org/plugins/ambrosite-nextprevious-post-link-plus/\" rel=\"nofollow noreferrer\">Ambrosite Next/Previous Post Link Plus</a>. This plugin creates two new template tags — <strong>next_post_link_plus</strong> and <strong>previous_post_link_plus</strong> — which are upgraded versions of the core WordPress <strong>next_post_link</strong> and <strong>previous_post_link</strong> template tags.</p>\n\n<ul>\n<li>Sort next/previous post links on columns other than post_date (e.g.\nalphabetically).</li>\n<li>Sort next/previous links on custom fields (both string and integer sorts are supported).</li>\n<li>Full WordPress 3.3 compatibility, including support for custom post types, custom taxonomies, and post formats.</li>\n<li>Loop around to the first post if there is no next post (and vice versa).\nRetrieve the first/last post, rather than the previous/next post (for First|Previous|Next|Last navigation links).</li>\n<li>Display post thumbnails alongside the links (WordPress 2.9 or higher).</li>\n<li>Truncate the link titles to any length, and display custom text in the tooltip.</li>\n<li>Display the title, date, author, category, and meta value of the next/previous links.</li>\n<li>Specify a custom date format for the %date variable.</li>\n<li>Restrict next/previous links to same category, taxonomy, format, author, custom field value, custom post ID list, or custom category list.</li>\n<li>Exclude categories, custom taxonomies, post formats, or individual post IDs.</li>\n<li>Three category exclusion methods for greater control over the navigation stream.</li>\n<li>Return multiple next/previous links (e.g. the next N links, in an HTML list).</li>\n<li>Return the ID, title, date, href attribute, or post object of the next/previous links, instead of echoing them to the screen.</li>\n<li>Return false if no next/previous link is found, so themes may conditionally display alternate text.</li>\n<li>Works with Post Types Order and other popular post reordering plugins.</li>\n</ul>\n"
},
{
"answer_id": 272703,
"author": "Surender",
"author_id": 123432,
"author_profile": "https://wordpress.stackexchange.com/users/123432",
"pm_score": 1,
"selected": false,
"text": "<p>Copy the single.php page from your Parent theme and Paste it to your Child-theme's directory. Open the single.php from child-theme directory and add the following code at the end of file [before get_footer(); ]</p>\n\n<pre><code><?php\n$post_id = $post->ID; // Get current post ID\n$cat = get_the_category(); \n$current_cat_id = $cat[0]->cat_ID; // Get current Category ID \n\n$args = array('category'=>$current_cat_id,'orderby'=>'post_date','order'=> 'DESC');\n$posts = get_posts($args);\n// Get IDs of posts retrieved by get_posts function\n$ids = array();\nforeach ($posts as $thepost) {\n $ids[] = $thepost->ID;\n}\n// Get and Echo the Previous and Next post link within same Category\n$index = array_search($post->ID, $ids);\n$prev_post = $ids[$index+1];\n$next_post = $ids[$index-1];\n?>\n\n<?php if (!empty($prev_post)){ ?> <a class=\"previous-post\" rel=\"prev\" href=\"<?php echo get_permalink($prev_post) ?>\"> <span class=\"meta-icon\"><i class=\"fa fa-angle-left fa-lg\"></i></span> Previous</a> <?php } ?>\n\n<?php if (!empty($next_post)){ ?> <a class=\"next-post\" rel=\"next\" href=\"<?php echo get_permalink($next_post) ?>\">Next <span class=\"meta-icon\"><i class=\"fa fa-angle-right fa-lg\"></i></span> </a> <?php } ?>\n</code></pre>\n\n<p>After adding this code, paste the following code into your child-theme's Style.css to style the links:</p>\n\n<pre><code>a.previous-post, a.next-post {\n color: #fff;\n background-color: #4498e7;\n text-align: center;\n height: 34px;\n line-height: 34px;\n font-size: 14px;\n border: 1px solid;\n padding: 0 20px;\n margin-bottom: 30px;\n text-transform: uppercase;\n border-radius: 4px;\n font-weight: bold;\n}\n\na.previous-post:hover, a.next-post:hover {\n color: #4498e7;\n background-color: #fff;\n}\n\na.previous-post {\n float: left !important;\n}\n\na.next-post {\n float: right !important;\n}\n</code></pre>\n\n<p>Let me know the results :)</p>\n"
}
] |
2015/02/20
|
[
"https://wordpress.stackexchange.com/questions/178780",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/50943/"
] |
Im using the next post link function of WP to show next and previous navigation links to the "next post in same category" all good with this...the issue i have is that when I'm in the "last" post of a category, the "NEXT" link appears anyway and doing what i dont want: linking to a different category 1st post. the same with the 1st post of a category, when browsing the first post of a category the "PREVIOUS" link appears linking to previous post of a another different category... I would like that in the 1st and last post, this links aren't shown.
```
<div id="nav-above" class="navigation">
<div class="nav-previous"><?php previous_post_linknext_post_link( '%link', '<span class="meta-nav">' .
_x( '◄ Previous', 'Previous post link','category' ,TRUE ) . '</span>' ); ?></div>
<div class="nav-next"><?php next_post_link( '%link', '<span class="meta-nav">' . _x( 'Next ► ', 'Next post link', 'category',TRUE ) . '</span>' ); ?> </div>
</div><!-- #nav-above -->
```
<http://codex.wordpress.org/Function_Reference/next_post_link>
|
You can do this by using [`previous_post_link()`](http://codex.wordpress.org/Function_Reference/previous_post_link) and [`next_post_link()`](http://codex.wordpress.org/Function_Reference/next_post_link).
These functions will create the links for you, and you should be able to get rid of all of the logic you are using for pagination.
As you wish to only link to posts in the same category you should use the functions with the following parameters:
```
previous_post_link('« %link', '%title', true);
next_post_link('%link »', '%title', true);
```
---
Update
======
In response to your updated question with regard to your issue of previous/next linking when they are the first/last post, please see this line from the Codex of both [`previous_post_link()`](http://codex.wordpress.org/Function_Reference/previous_post_link) and [`next_post_link()`](http://codex.wordpress.org/Function_Reference/next_post_link) in relation to the `$in_same_term` parameter:
>
> Indicates whether next post must be within the same taxonomy term as the current post. If set to 'true', only posts from the current taxonomy term will be displayed. If the post is in both the parent and subcategory, or more than one term, the next post link will lead to the next post in any of those terms.
>
>
>
With that in mind, I suspect your first last Posts may be associated with more than one category? If that's the case the `wp_get_object_terms` filter may be able to help.
In your original question (pre-edit) you were only searching for posts in the very first category, so I'll apply that logic here:
```
<?php add_filter('wp_get_object_terms', 'my_custom_post_navigation', 4, 99); ?>
<div id="nav-above" class="navigation">
<div class="nav-previous">
<?php previous_post_link( '<span class="meta-nav"> %link </span>', _x( '◄ Previous', 'Previous post link', 'category') , TRUE ); ?>
</div>
<div class="nav-previous">
<?php next_post_link( '<span class="meta-nav"> %link </span>', _x( 'Next ►', 'Next post link', 'category') , TRUE ); ?>
</div>
</div><!-- #nav-above -->
<?php remove_filter('wp_get_object_terms', 'my_custom_post_navigation', 99); ?>
```
In addition to the above, you should place this in your **functions.php** file:
```
/**
* Return only the first category when outputting the previous/next post links
*/
function my_custom_post_navigation($terms, $object_ids, $taxonomies, $args){
return array_slice($terms, 0, 1);
}
```
|
178,816 |
<p>I'm using the following code to list all years from my blog, I guess we can call it an archive.</p>
<pre><code><?php
$years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts ORDER BY post_date DESC");
foreach($years as $year) : ?>
<?php echo $year ?>
<?php endforeach; ?>
</code></pre>
<p>What I'd like to achieve though is to also display, in front of each year, the number of posts (count) that each year has. Example:</p>
<pre><code>2015 (5 posts)
2014 (3 posts)
2011 (10 posts)
</code></pre>
<p>I found a hint somewhere and tried to implement it, but didn't work. Here's what I was trying:</p>
<pre><code><?php
$years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts ORDER BY post_date DESC");
$count = $years->post_count;
foreach($years as $year) : ?>
<?php echo $year ?> (<?php echo $count ?> posts)
<?php endforeach; ?>
</code></pre>
<p>Any ideas?</p>
<p>Thank you.</p>
<p><strong>EDIT @David</strong></p>
<pre><code><?php
/** Grab the years that contain published posts, and a count of how many */
$query = $wpdb->prepare('
SELECT YEAR(%1$s.post_date) AS `year`, count(%1$s.ID) as `posts`
FROM %1$s
WHERE %1$s.post_type IN ("post")
AND %1$s.post_status IN ("publish")
GROUP BY YEAR(%1$s.post_date)
ORDER BY %1$s.post_date DESC',
$wpdb->posts
);
$results = $wpdb->get_results($query);
/** Create the '$years' array, a list of all yearly archives */
$years = array();
if(!empty($results)) : foreach($results as $result) :
$url = get_year_link($result->year); // The archive link URL for the current year
$text = $result->year; // The archive link text for the current year
$count = $result->posts; // The number of posts in the current year
$years[] = get_archives_link($url, $text, 'html', '', $count); // Create the archive link for the current year
endforeach;
endif;
?>
<a href="<?php echo $url; ?>"><li><?php echo $text ?> <span class="lower">(<?php echo $count ?>)</span></li></a>
</code></pre>
|
[
{
"answer_id": 178941,
"author": "David Gard",
"author_id": 10097,
"author_profile": "https://wordpress.stackexchange.com/users/10097",
"pm_score": 2,
"selected": false,
"text": "<h1>The Easy Way</h1>\n\n<p>This is by far and away the easiest approach to this, but unless you are willing to be a little bit flexible with how you present your archive it's not for you.</p>\n\n<p>The easy solution is achieved using the <a href=\"http://codex.wordpress.org/Function_Reference/wp_get_archives\" rel=\"nofollow\"><code>wp_get_archives()</code></a> function. Unfortunately though there is no filter available to manipulate the output, so you'll be left with a list like this. The count will not be part of the link -</p>\n\n<blockquote>\n <p>2015 (5)<br>\n 2014 (3)<br>\n 2011 (10)</p>\n</blockquote>\n\n<p>And here is the code -</p>\n\n<pre><code>$args = array(\n 'type' => 'yearly',\n 'show_post_count' => true\n);\nwp_get_archives($args);\n</code></pre>\n\n<h1>The Hard Way</h1>\n\n<p>So if you decide the easy way isn't for you that only leave the hard way. Essentially we are replicating the functionality of <code>wp_get_archives()</code>, but you can format the output exactly as you wish.</p>\n\n<p>The code below makes use of a custom query, not dissimilar from your own (except that we grab the count of posts as well as the years), as well as the functions <a href=\"http://codex.wordpress.org/Function_Reference/get_year_link\" rel=\"nofollow\"><code>get_year_link()</code></a> and <a href=\"http://codex.wordpress.org/Function_Reference/get_archives_link\" rel=\"nofollow\"><code>get_archives_link()</code></a>.</p>\n\n<p>The output will leave you with a list formatted as you posted in the update to your question. The count will be part of the link -</p>\n\n<blockquote>\n <p>2015 (5)<br>\n 2014 (3)<br>\n 2011 (10)</p>\n</blockquote>\n\n<p>And here is the code -</p>\n\n<pre><code>/** Grab the years that contain published posts, and a count of how many */\n$query = $wpdb->prepare('\n SELECT YEAR(%1$s.post_date) AS `year`, count(%1$s.ID) as `posts`\n FROM %1$s\n WHERE %1$s.post_type IN (\"post\")\n AND %1$s.post_status IN (\"publish\")\n GROUP BY YEAR(%1$s.post_date)\n ORDER BY %1$s.post_date',\n $wpdb->posts\n );\n$results = $wpdb->get_results($query); \n\n/** Create the '$years' array, a list of all yearly archives */\n$years = array();\nif(!empty($results)) : foreach($results as $result) :\n\n $count = '<span class=\"lower\">(' . $result->posts . ')</span>'; // The number of posts in the current year\n $url = get_year_link($result->year); // The archive link URL for the current year\n $text = '<li>' . $result->year . ' ' . $count . '</li>'; // The archive link text for the current year\n $years[] = get_archives_link($url, $text, 'html'); // Create the archive link for the current year\n\n endforeach;\nendif;\n\n/** Output the custom archive list */\necho join(\"\\n\", $years);\n</code></pre>\n\n<h1>Edit</h1>\n\n<p>Based on your comment, I've amended my answer above slightly.</p>\n\n<p>The reason that you were only able to output one year is because you were only explicity echoing the last year after the <code>foreach</code> loop. What the code does is add each year to the <code>$years</code> array, and then outputs all of them using the final line - echo join(\"\\n\", $years);</p>\n"
},
{
"answer_id": 283290,
"author": "Ian Sowinski",
"author_id": 129839,
"author_profile": "https://wordpress.stackexchange.com/users/129839",
"pm_score": 2,
"selected": false,
"text": "<p>Just had simmilar problem and because I don't feel comfortable with performing DB queries in rendered php sites, I made this function, witch uses wp_get_archives() and regex. It returns array with year as the key and number of posts as the value.</p>\n\n<h1>The middle way:</h1>\n\n<pre><code>function load_years() {\n $args = array(\n 'type' => 'yearly',\n 'show_post_count' => true\n );\n ob_start();\n wp_get_archives($args);\n $item = ob_get_contents(); \n ob_end_clean(); \n $pattern = '/\\'>(\\d\\d\\d\\d)<.*nbsp;\\((\\d*)/';\n preg_match_all($pattern, $item, $matches, PREG_OFFSET_CAPTURE);\n $years_array = array();\n foreach ($matches[1] as $key => $value) {\n $year = $matches[1][$key][0];\n $posts = $matches[2][$key][0];\n $years_array[$year] = $posts;\n }\n return $years_array;\n}\n</code></pre>\n"
}
] |
2015/02/20
|
[
"https://wordpress.stackexchange.com/questions/178816",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/59749/"
] |
I'm using the following code to list all years from my blog, I guess we can call it an archive.
```
<?php
$years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts ORDER BY post_date DESC");
foreach($years as $year) : ?>
<?php echo $year ?>
<?php endforeach; ?>
```
What I'd like to achieve though is to also display, in front of each year, the number of posts (count) that each year has. Example:
```
2015 (5 posts)
2014 (3 posts)
2011 (10 posts)
```
I found a hint somewhere and tried to implement it, but didn't work. Here's what I was trying:
```
<?php
$years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts ORDER BY post_date DESC");
$count = $years->post_count;
foreach($years as $year) : ?>
<?php echo $year ?> (<?php echo $count ?> posts)
<?php endforeach; ?>
```
Any ideas?
Thank you.
**EDIT @David**
```
<?php
/** Grab the years that contain published posts, and a count of how many */
$query = $wpdb->prepare('
SELECT YEAR(%1$s.post_date) AS `year`, count(%1$s.ID) as `posts`
FROM %1$s
WHERE %1$s.post_type IN ("post")
AND %1$s.post_status IN ("publish")
GROUP BY YEAR(%1$s.post_date)
ORDER BY %1$s.post_date DESC',
$wpdb->posts
);
$results = $wpdb->get_results($query);
/** Create the '$years' array, a list of all yearly archives */
$years = array();
if(!empty($results)) : foreach($results as $result) :
$url = get_year_link($result->year); // The archive link URL for the current year
$text = $result->year; // The archive link text for the current year
$count = $result->posts; // The number of posts in the current year
$years[] = get_archives_link($url, $text, 'html', '', $count); // Create the archive link for the current year
endforeach;
endif;
?>
<a href="<?php echo $url; ?>"><li><?php echo $text ?> <span class="lower">(<?php echo $count ?>)</span></li></a>
```
|
The Easy Way
============
This is by far and away the easiest approach to this, but unless you are willing to be a little bit flexible with how you present your archive it's not for you.
The easy solution is achieved using the [`wp_get_archives()`](http://codex.wordpress.org/Function_Reference/wp_get_archives) function. Unfortunately though there is no filter available to manipulate the output, so you'll be left with a list like this. The count will not be part of the link -
>
> 2015 (5)
>
> 2014 (3)
>
> 2011 (10)
>
>
>
And here is the code -
```
$args = array(
'type' => 'yearly',
'show_post_count' => true
);
wp_get_archives($args);
```
The Hard Way
============
So if you decide the easy way isn't for you that only leave the hard way. Essentially we are replicating the functionality of `wp_get_archives()`, but you can format the output exactly as you wish.
The code below makes use of a custom query, not dissimilar from your own (except that we grab the count of posts as well as the years), as well as the functions [`get_year_link()`](http://codex.wordpress.org/Function_Reference/get_year_link) and [`get_archives_link()`](http://codex.wordpress.org/Function_Reference/get_archives_link).
The output will leave you with a list formatted as you posted in the update to your question. The count will be part of the link -
>
> 2015 (5)
>
> 2014 (3)
>
> 2011 (10)
>
>
>
And here is the code -
```
/** Grab the years that contain published posts, and a count of how many */
$query = $wpdb->prepare('
SELECT YEAR(%1$s.post_date) AS `year`, count(%1$s.ID) as `posts`
FROM %1$s
WHERE %1$s.post_type IN ("post")
AND %1$s.post_status IN ("publish")
GROUP BY YEAR(%1$s.post_date)
ORDER BY %1$s.post_date',
$wpdb->posts
);
$results = $wpdb->get_results($query);
/** Create the '$years' array, a list of all yearly archives */
$years = array();
if(!empty($results)) : foreach($results as $result) :
$count = '<span class="lower">(' . $result->posts . ')</span>'; // The number of posts in the current year
$url = get_year_link($result->year); // The archive link URL for the current year
$text = '<li>' . $result->year . ' ' . $count . '</li>'; // The archive link text for the current year
$years[] = get_archives_link($url, $text, 'html'); // Create the archive link for the current year
endforeach;
endif;
/** Output the custom archive list */
echo join("\n", $years);
```
Edit
====
Based on your comment, I've amended my answer above slightly.
The reason that you were only able to output one year is because you were only explicity echoing the last year after the `foreach` loop. What the code does is add each year to the `$years` array, and then outputs all of them using the final line - echo join("\n", $years);
|
178,858 |
<p>I've been trying to rebuild one of my websites story archives in Drupal. I have a personal website I wouldn't mind putting in Wordpress, but I want an easy way to create structured documents. That is to say I wanr a parent Story page, that has links and hierarchy for the Chapters under it. Is this doable in Wordpress?</p>
|
[
{
"answer_id": 178941,
"author": "David Gard",
"author_id": 10097,
"author_profile": "https://wordpress.stackexchange.com/users/10097",
"pm_score": 2,
"selected": false,
"text": "<h1>The Easy Way</h1>\n\n<p>This is by far and away the easiest approach to this, but unless you are willing to be a little bit flexible with how you present your archive it's not for you.</p>\n\n<p>The easy solution is achieved using the <a href=\"http://codex.wordpress.org/Function_Reference/wp_get_archives\" rel=\"nofollow\"><code>wp_get_archives()</code></a> function. Unfortunately though there is no filter available to manipulate the output, so you'll be left with a list like this. The count will not be part of the link -</p>\n\n<blockquote>\n <p>2015 (5)<br>\n 2014 (3)<br>\n 2011 (10)</p>\n</blockquote>\n\n<p>And here is the code -</p>\n\n<pre><code>$args = array(\n 'type' => 'yearly',\n 'show_post_count' => true\n);\nwp_get_archives($args);\n</code></pre>\n\n<h1>The Hard Way</h1>\n\n<p>So if you decide the easy way isn't for you that only leave the hard way. Essentially we are replicating the functionality of <code>wp_get_archives()</code>, but you can format the output exactly as you wish.</p>\n\n<p>The code below makes use of a custom query, not dissimilar from your own (except that we grab the count of posts as well as the years), as well as the functions <a href=\"http://codex.wordpress.org/Function_Reference/get_year_link\" rel=\"nofollow\"><code>get_year_link()</code></a> and <a href=\"http://codex.wordpress.org/Function_Reference/get_archives_link\" rel=\"nofollow\"><code>get_archives_link()</code></a>.</p>\n\n<p>The output will leave you with a list formatted as you posted in the update to your question. The count will be part of the link -</p>\n\n<blockquote>\n <p>2015 (5)<br>\n 2014 (3)<br>\n 2011 (10)</p>\n</blockquote>\n\n<p>And here is the code -</p>\n\n<pre><code>/** Grab the years that contain published posts, and a count of how many */\n$query = $wpdb->prepare('\n SELECT YEAR(%1$s.post_date) AS `year`, count(%1$s.ID) as `posts`\n FROM %1$s\n WHERE %1$s.post_type IN (\"post\")\n AND %1$s.post_status IN (\"publish\")\n GROUP BY YEAR(%1$s.post_date)\n ORDER BY %1$s.post_date',\n $wpdb->posts\n );\n$results = $wpdb->get_results($query); \n\n/** Create the '$years' array, a list of all yearly archives */\n$years = array();\nif(!empty($results)) : foreach($results as $result) :\n\n $count = '<span class=\"lower\">(' . $result->posts . ')</span>'; // The number of posts in the current year\n $url = get_year_link($result->year); // The archive link URL for the current year\n $text = '<li>' . $result->year . ' ' . $count . '</li>'; // The archive link text for the current year\n $years[] = get_archives_link($url, $text, 'html'); // Create the archive link for the current year\n\n endforeach;\nendif;\n\n/** Output the custom archive list */\necho join(\"\\n\", $years);\n</code></pre>\n\n<h1>Edit</h1>\n\n<p>Based on your comment, I've amended my answer above slightly.</p>\n\n<p>The reason that you were only able to output one year is because you were only explicity echoing the last year after the <code>foreach</code> loop. What the code does is add each year to the <code>$years</code> array, and then outputs all of them using the final line - echo join(\"\\n\", $years);</p>\n"
},
{
"answer_id": 283290,
"author": "Ian Sowinski",
"author_id": 129839,
"author_profile": "https://wordpress.stackexchange.com/users/129839",
"pm_score": 2,
"selected": false,
"text": "<p>Just had simmilar problem and because I don't feel comfortable with performing DB queries in rendered php sites, I made this function, witch uses wp_get_archives() and regex. It returns array with year as the key and number of posts as the value.</p>\n\n<h1>The middle way:</h1>\n\n<pre><code>function load_years() {\n $args = array(\n 'type' => 'yearly',\n 'show_post_count' => true\n );\n ob_start();\n wp_get_archives($args);\n $item = ob_get_contents(); \n ob_end_clean(); \n $pattern = '/\\'>(\\d\\d\\d\\d)<.*nbsp;\\((\\d*)/';\n preg_match_all($pattern, $item, $matches, PREG_OFFSET_CAPTURE);\n $years_array = array();\n foreach ($matches[1] as $key => $value) {\n $year = $matches[1][$key][0];\n $posts = $matches[2][$key][0];\n $years_array[$year] = $posts;\n }\n return $years_array;\n}\n</code></pre>\n"
}
] |
2015/02/20
|
[
"https://wordpress.stackexchange.com/questions/178858",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/43799/"
] |
I've been trying to rebuild one of my websites story archives in Drupal. I have a personal website I wouldn't mind putting in Wordpress, but I want an easy way to create structured documents. That is to say I wanr a parent Story page, that has links and hierarchy for the Chapters under it. Is this doable in Wordpress?
|
The Easy Way
============
This is by far and away the easiest approach to this, but unless you are willing to be a little bit flexible with how you present your archive it's not for you.
The easy solution is achieved using the [`wp_get_archives()`](http://codex.wordpress.org/Function_Reference/wp_get_archives) function. Unfortunately though there is no filter available to manipulate the output, so you'll be left with a list like this. The count will not be part of the link -
>
> 2015 (5)
>
> 2014 (3)
>
> 2011 (10)
>
>
>
And here is the code -
```
$args = array(
'type' => 'yearly',
'show_post_count' => true
);
wp_get_archives($args);
```
The Hard Way
============
So if you decide the easy way isn't for you that only leave the hard way. Essentially we are replicating the functionality of `wp_get_archives()`, but you can format the output exactly as you wish.
The code below makes use of a custom query, not dissimilar from your own (except that we grab the count of posts as well as the years), as well as the functions [`get_year_link()`](http://codex.wordpress.org/Function_Reference/get_year_link) and [`get_archives_link()`](http://codex.wordpress.org/Function_Reference/get_archives_link).
The output will leave you with a list formatted as you posted in the update to your question. The count will be part of the link -
>
> 2015 (5)
>
> 2014 (3)
>
> 2011 (10)
>
>
>
And here is the code -
```
/** Grab the years that contain published posts, and a count of how many */
$query = $wpdb->prepare('
SELECT YEAR(%1$s.post_date) AS `year`, count(%1$s.ID) as `posts`
FROM %1$s
WHERE %1$s.post_type IN ("post")
AND %1$s.post_status IN ("publish")
GROUP BY YEAR(%1$s.post_date)
ORDER BY %1$s.post_date',
$wpdb->posts
);
$results = $wpdb->get_results($query);
/** Create the '$years' array, a list of all yearly archives */
$years = array();
if(!empty($results)) : foreach($results as $result) :
$count = '<span class="lower">(' . $result->posts . ')</span>'; // The number of posts in the current year
$url = get_year_link($result->year); // The archive link URL for the current year
$text = '<li>' . $result->year . ' ' . $count . '</li>'; // The archive link text for the current year
$years[] = get_archives_link($url, $text, 'html'); // Create the archive link for the current year
endforeach;
endif;
/** Output the custom archive list */
echo join("\n", $years);
```
Edit
====
Based on your comment, I've amended my answer above slightly.
The reason that you were only able to output one year is because you were only explicity echoing the last year after the `foreach` loop. What the code does is add each year to the `$years` array, and then outputs all of them using the final line - echo join("\n", $years);
|
178,892 |
<p>I have a custom tag-search feature, which allows people to search multiple tags to return relevant posts. Say they want to see posts that are tagged both 'Wordpress' and 'Tutorials'. I'm using the <code>template_include</code> filter, like so:</p>
<pre><code>public static function template_redirect( $template ) {
if( isset($_GET['tag-search']) )
{
$template = locate_template( array(
'search.php',
'archive.php',
'index.php'
));
}
return $template;
}
</code></pre>
<p>the <code>tag-search</code> variable holds the name of the taxonomy, I check if it is set, thus indicating a search is being performed. </p>
<p>At this point <code>template</code> resolves to search.php, like it should. So that's good.</p>
<p>In the <code>pre_get_posts</code> action I add a <code>tax_query</code> to modify the returned posts to just the selected tags, and I set <code>is_search</code> to true, and <code>is_home</code> to false. Here is my <code>pre_get_posts</code> action:</p>
<pre><code>public static function pre_get_posts($query) {
if( !isset($_GET['tag-search']) || !isset($_GET['terms']) ) return $query;
if( strtolower( $_GET['method'] ) == 'and' )
{
$query->set( 'tax_query', array(
array(
'taxonomy' => $_GET['tag-search'],
'field' => 'slug',
'terms' => explode(',', $_GET['terms']),
'operator' => 'AND'
)
) );
}
else
{
$query->set( 'tax_query', array(
array(
'taxonomy' => $_GET['tag-search'],
'field' => 'slug',
'terms' => explode(',', $_GET['terms'])
)
) );
}
$query->is_search = true;
$query->is_home = false;
return $query;
}
</code></pre>
<p>However, when I perform the search, the body class is 'home', and all of the <code>is_home</code> and <code>is_front_page</code> conditionals are <strong>true</strong>, which they shouldn't be, cause I just specifically stated I want this to be a search template right?</p>
<p>I know this can be done - when I add <code>&s</code> to the query string it works as it should - though it's a bit ugly that way. Any insights?</p>
|
[
{
"answer_id": 179242,
"author": "chifliiiii",
"author_id": 4130,
"author_profile": "https://wordpress.stackexchange.com/users/4130",
"pm_score": 0,
"selected": false,
"text": "<p>Try the following:</p>\n\n<pre><code>public static function pre_get_posts($query) {\n if( !isset($_GET['tag-search']) || !isset($_GET['terms']) ) return $query;\n if ( ! is_admin() && $query->is_main_query() ) {\n if( strtolower( $_GET['method'] ) == 'and' )\n {\n $query->set( 'tax_query', array(\n array(\n 'taxonomy' => $_GET['tag-search'],\n 'field' => 'slug',\n 'terms' => explode(',', $_GET['terms']),\n 'operator' => 'AND'\n )\n ) );\n }\n else\n {\n $query->set( 'tax_query', array(\n array(\n 'taxonomy' => $_GET['tag-search'],\n 'field' => 'slug',\n 'terms' => explode(',', $_GET['terms'])\n )\n ) );\n }\n $query->set('s', '' );\n $query->is_search = true;\n $query->is_home = false;\n }\n return $query;\n}\n</code></pre>\n\n<p>I added some extra checks and the 's' in a less ugly way</p>\n"
},
{
"answer_id": 179249,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 4,
"selected": true,
"text": "<p>Your problem is that you are not resetting all the needed query variables, like <code>WP_Query::$is_page</code>, <code>WP_Query::$is_single</code> and <code>WP_Query::$is_archive</code>.</p>\n\n<p>Also note that <code>'pre_get_posts'</code> is fired for all queries, the main and the secondaries, so you should check that you are working on the main query.</p>\n\n<p>Finally, when you get data from <code>$_GET</code>you should sanitize it before to use it, a good way is to use <a href=\"http://php.net/manual/en/function.filter-input.php\" rel=\"nofollow\"><code>filter_input()</code></a> or <a href=\"http://php.net/manual/en/function.filter-input.php\" rel=\"nofollow\"><code>filter_input_array()</code></a>.</p>\n\n<p>Your method should appear something like this:</p>\n\n<pre><code>public static function pre_get_posts($query)\n{\n $data = filter_input_array(INPUT_GET, array(\n 'tag-search' => FILTER_SANITIZE_STRING,\n 'terms' => FILTER_SANITIZE_STRING,\n 'method' => FILTER_SANITIZE_STRING,\n ));\n if( $query->is_main_query() && !empty($data['tag-search']) && !empty($data['terms']) ) {\n $query->init(); // this resets ALL vars\n $query->is_search = true;\n // set tax query array\n $tax_query = array(\n 'taxonomy' => $data['tag-search'],\n 'field' => 'slug',\n 'terms' => explode(',', $data['terms']),\n );\n // is AND method?\n if( strtolower( $data['method'] ) === 'and' ) {\n $tax_query['operator'] = 'AND';\n }\n // set tax query\n $query->set( 'tax_query', array($tax_query) );\n }\n}\n</code></pre>\n\n<p>Doing so you do <strong>not</strong> need to filter the template (so you can remove your <code>template_redirect()</code> method): <code>search.php</code> will be loaded by WordPress because it will correctly recognize the query as a search.</p>\n\n<hr>\n\n<p>PS: <code>'pre_get_post'</code> is an <strong>action</strong>, not a filter, so you <strong>don't</strong> need to return the query neither if you modify it.</p>\n"
}
] |
2015/02/21
|
[
"https://wordpress.stackexchange.com/questions/178892",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16368/"
] |
I have a custom tag-search feature, which allows people to search multiple tags to return relevant posts. Say they want to see posts that are tagged both 'Wordpress' and 'Tutorials'. I'm using the `template_include` filter, like so:
```
public static function template_redirect( $template ) {
if( isset($_GET['tag-search']) )
{
$template = locate_template( array(
'search.php',
'archive.php',
'index.php'
));
}
return $template;
}
```
the `tag-search` variable holds the name of the taxonomy, I check if it is set, thus indicating a search is being performed.
At this point `template` resolves to search.php, like it should. So that's good.
In the `pre_get_posts` action I add a `tax_query` to modify the returned posts to just the selected tags, and I set `is_search` to true, and `is_home` to false. Here is my `pre_get_posts` action:
```
public static function pre_get_posts($query) {
if( !isset($_GET['tag-search']) || !isset($_GET['terms']) ) return $query;
if( strtolower( $_GET['method'] ) == 'and' )
{
$query->set( 'tax_query', array(
array(
'taxonomy' => $_GET['tag-search'],
'field' => 'slug',
'terms' => explode(',', $_GET['terms']),
'operator' => 'AND'
)
) );
}
else
{
$query->set( 'tax_query', array(
array(
'taxonomy' => $_GET['tag-search'],
'field' => 'slug',
'terms' => explode(',', $_GET['terms'])
)
) );
}
$query->is_search = true;
$query->is_home = false;
return $query;
}
```
However, when I perform the search, the body class is 'home', and all of the `is_home` and `is_front_page` conditionals are **true**, which they shouldn't be, cause I just specifically stated I want this to be a search template right?
I know this can be done - when I add `&s` to the query string it works as it should - though it's a bit ugly that way. Any insights?
|
Your problem is that you are not resetting all the needed query variables, like `WP_Query::$is_page`, `WP_Query::$is_single` and `WP_Query::$is_archive`.
Also note that `'pre_get_posts'` is fired for all queries, the main and the secondaries, so you should check that you are working on the main query.
Finally, when you get data from `$_GET`you should sanitize it before to use it, a good way is to use [`filter_input()`](http://php.net/manual/en/function.filter-input.php) or [`filter_input_array()`](http://php.net/manual/en/function.filter-input.php).
Your method should appear something like this:
```
public static function pre_get_posts($query)
{
$data = filter_input_array(INPUT_GET, array(
'tag-search' => FILTER_SANITIZE_STRING,
'terms' => FILTER_SANITIZE_STRING,
'method' => FILTER_SANITIZE_STRING,
));
if( $query->is_main_query() && !empty($data['tag-search']) && !empty($data['terms']) ) {
$query->init(); // this resets ALL vars
$query->is_search = true;
// set tax query array
$tax_query = array(
'taxonomy' => $data['tag-search'],
'field' => 'slug',
'terms' => explode(',', $data['terms']),
);
// is AND method?
if( strtolower( $data['method'] ) === 'and' ) {
$tax_query['operator'] = 'AND';
}
// set tax query
$query->set( 'tax_query', array($tax_query) );
}
}
```
Doing so you do **not** need to filter the template (so you can remove your `template_redirect()` method): `search.php` will be loaded by WordPress because it will correctly recognize the query as a search.
---
PS: `'pre_get_post'` is an **action**, not a filter, so you **don't** need to return the query neither if you modify it.
|
178,911 |
<p>I have created this widget function to show a subscription form but from here i am not able to get the the values of input fields when someone submit it. Please help to get post values of the form.</p>
<pre><code>function widget($args, $instance) {
extract( $args );
// these are the widget options
$title = apply_filters('widget_title', $instance['title']);
echo $before_widget;
echo '<div>';
// Check if title is set
if ( $title ) {
echo $before_title . $title . $after_title;
}
?>
<form>
<p><label for="db_sub_name">Name</label> <input type="text" name="db_sub_name" id="db_sub_name" value="" placeholder="Enter your Name"></p>
<p><label for="db_sub_name">Email</label> <input type="text" name="db_sub_email" id="db_sub_email" value="" placeholder="Enter your Email"></p>
<p ><input style="float:right;" type="submit" /></p>
</form>
<?php
echo '</div>';
echo $after_widget;
}
</code></pre>
<p>Thanks</p>
|
[
{
"answer_id": 178950,
"author": "Greg Piwowarski",
"author_id": 67944,
"author_profile": "https://wordpress.stackexchange.com/users/67944",
"pm_score": 0,
"selected": false,
"text": "<p>Can't you use a plugin for that? There is a nice mailchimp plugin available with a widget and submission form, <a href=\"https://wordpress.org/plugins/mailchimp-for-wp/\" rel=\"nofollow\">Mailchimp For WP</a>.</p>\n\n<p>It populates your mailchimp account and that is an awesome tool for marketing emails...</p>\n"
},
{
"answer_id": 178951,
"author": "skribe",
"author_id": 67491,
"author_profile": "https://wordpress.stackexchange.com/users/67491",
"pm_score": 1,
"selected": false,
"text": "<p>Your form needs to have <code>method=\"post\"</code> and <code>action=\"someScript.php\"</code> defined. It will send the post variables to wherever you deifine in your <code>action=\"\"</code> </p>\n\n<pre><code><form method=\"post\" action=\"someScript.php\" >\n <p>\n <label for=\"db_sub_name\">Name</label>\n <input type=\"text\" name=\"db_sub_name\" id=\"db_sub_name\" value=\"\" placeholder=\"Enter your Name\">\n </p>\n <p>\n <label for=\"db_sub_name\">Email</label>\n <input type=\"text\" name=\"db_sub_email\" id=\"db_sub_email\" value=\"\" placeholder=\"Enter your Email\">\n </p>\n <p>\n <input style=\"float:right;\" type=\"submit\" />\n </p>\n</form>\n</code></pre>\n"
}
] |
2015/02/21
|
[
"https://wordpress.stackexchange.com/questions/178911",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67926/"
] |
I have created this widget function to show a subscription form but from here i am not able to get the the values of input fields when someone submit it. Please help to get post values of the form.
```
function widget($args, $instance) {
extract( $args );
// these are the widget options
$title = apply_filters('widget_title', $instance['title']);
echo $before_widget;
echo '<div>';
// Check if title is set
if ( $title ) {
echo $before_title . $title . $after_title;
}
?>
<form>
<p><label for="db_sub_name">Name</label> <input type="text" name="db_sub_name" id="db_sub_name" value="" placeholder="Enter your Name"></p>
<p><label for="db_sub_name">Email</label> <input type="text" name="db_sub_email" id="db_sub_email" value="" placeholder="Enter your Email"></p>
<p ><input style="float:right;" type="submit" /></p>
</form>
<?php
echo '</div>';
echo $after_widget;
}
```
Thanks
|
Your form needs to have `method="post"` and `action="someScript.php"` defined. It will send the post variables to wherever you deifine in your `action=""`
```
<form method="post" action="someScript.php" >
<p>
<label for="db_sub_name">Name</label>
<input type="text" name="db_sub_name" id="db_sub_name" value="" placeholder="Enter your Name">
</p>
<p>
<label for="db_sub_name">Email</label>
<input type="text" name="db_sub_email" id="db_sub_email" value="" placeholder="Enter your Email">
</p>
<p>
<input style="float:right;" type="submit" />
</p>
</form>
```
|
178,940 |
<p>Trying to show featured posts on home using catID,but it is being duplicated. Is there any way to prevent it from duplicating:</p>
<pre><code><?php
query_posts("posts_per_page=1&cat=1");
if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_post_thumbnail(); ?>
<p><?php the_excerpt(); ?></p>
<p><a href="<?php the_permalink(); ?>">continue reading</a></p>
<?php endwhile; ?> <?php wp_reset_query(); ?>
</code></pre>
|
[
{
"answer_id": 178924,
"author": "gurudeb",
"author_id": 12106,
"author_profile": "https://wordpress.stackexchange.com/users/12106",
"pm_score": 1,
"selected": false,
"text": "<p>Have look at add_image_size and add to your theme's functions.php file:</p>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/add_image_size\" rel=\"nofollow\">http://codex.wordpress.org/Function_Reference/add_image_size</a></p>\n"
},
{
"answer_id": 178948,
"author": "Greg Piwowarski",
"author_id": 67944,
"author_profile": "https://wordpress.stackexchange.com/users/67944",
"pm_score": 0,
"selected": false,
"text": "<p>Just like <strong>gurudeb</strong> said but remember that you will have to either replicate thumbnails or re upload the images so that the thumbnails in your defined size can be created</p>\n"
}
] |
2015/02/21
|
[
"https://wordpress.stackexchange.com/questions/178940",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/59698/"
] |
Trying to show featured posts on home using catID,but it is being duplicated. Is there any way to prevent it from duplicating:
```
<?php
query_posts("posts_per_page=1&cat=1");
if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_post_thumbnail(); ?>
<p><?php the_excerpt(); ?></p>
<p><a href="<?php the_permalink(); ?>">continue reading</a></p>
<?php endwhile; ?> <?php wp_reset_query(); ?>
```
|
Have look at add\_image\_size and add to your theme's functions.php file:
<http://codex.wordpress.org/Function_Reference/add_image_size>
|
179,011 |
<p>I am creating a custom theme with some widgets. In the theme, to make it easier for my client to update, I am using SiteOrigin's Page Builder plugin, which uses widgets to display content. I am creating an events list widget which will work with a custom post type. I want the widget to display a map of the area, but ONLY if it ISN'T in my sidebar (the sidebar is the only place <em>I</em> have declared widgets. If it is in my sidebar, it won't load the map.</p>
<p>I can't seem to find any solutions after a cursory look on Google. Most suggest using CSS to hide / show elements. I was hoping there was something in WP 4.1 that would check if a widget was inside a particular sidebar. Could anyone help?</p>
|
[
{
"answer_id": 179017,
"author": "skribe",
"author_id": 67491,
"author_profile": "https://wordpress.stackexchange.com/users/67491",
"pm_score": 0,
"selected": false,
"text": "<p>WordPress has a function for that already. <code>is_active_widget</code> As the codex points out you must use the function after the widgets have all loaded. Then test the conditions with an if statement and if the map widget is not loaded you can run the rest of your script to load the map in your template.</p>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/is_active_widget\" rel=\"nofollow\">http://codex.wordpress.org/Function_Reference/is_active_widget</a></p>\n"
},
{
"answer_id": 228998,
"author": "Owais Alam",
"author_id": 91939,
"author_profile": "https://wordpress.stackexchange.com/users/91939",
"pm_score": 1,
"selected": false,
"text": "<p>You should make the check inside the widget class, unless you don't have a choice. The example in the codex is pretty much what you're looking for:</p>\n\n<pre><code>class cbs_map_widget extends WP_Widget{\n\n function cbs_map_widget(){\n $this->WP_Widget('cbsmaps', __('Widget Name'), array('classname' => 'cbsmaps', 'description' => __('whatever')));\n ... \n add_action('wp_enqueue_scripts', array(&$this, 'js'));\n }\n\n function js(){\n\n if ( is_active_widget(false, false, $this->id_base, true) ) {\n // enqueue your scripts;\n } \n\n }\n\n\n ...\n\n}\n</code></pre>\n\n<p>The <code>$widget_id</code> parameter is useful when you need to include your scripts only for a specific widget instance. For example when you have two <code>cbs_map_widget</code> widgets and want to include custom javascript for each of them.</p>\n\n<p>The <code>$callback</code> argument is useful when you need to do the check outside the widget class (like you did above), but try to avoid it if you can do your check inside the class.</p>\n\n<p>The other arguments are pretty much self explanatory (id_base is basically a <code>\"widget class indentifier\"</code>, and the <code>$skip_inactive</code> is whether to check inactive widgets as well - should be true because I don't think you want to do that)...</p>\n\n<p>Again, you don't need this unless you specifically want to check if a certain widget instance is active. Personally I use this method because I can access the instance options too:</p>\n\n<pre><code>...\n function js(){\n\n // we need to process all instances because this function gets to run only once\n $widget_settings = get_option($this->option_name);\n\n foreach((array)$widget_settings as $instance => $options){\n\n // identify instance\n $id = \"{$this->id_base}-{$instance}\";\n\n // check if it's our instance\n if(!is_active_widget(false, $id, $this->id_base)) continue; // not active\n\n // instance is active\n // access the widget instance options here, you may need them to do your checks\n if($options['yourwidgetoption']) {\n // do stuff \n } \n }\n\n }\n ... \n</code></pre>\n"
}
] |
2015/02/22
|
[
"https://wordpress.stackexchange.com/questions/179011",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/36204/"
] |
I am creating a custom theme with some widgets. In the theme, to make it easier for my client to update, I am using SiteOrigin's Page Builder plugin, which uses widgets to display content. I am creating an events list widget which will work with a custom post type. I want the widget to display a map of the area, but ONLY if it ISN'T in my sidebar (the sidebar is the only place *I* have declared widgets. If it is in my sidebar, it won't load the map.
I can't seem to find any solutions after a cursory look on Google. Most suggest using CSS to hide / show elements. I was hoping there was something in WP 4.1 that would check if a widget was inside a particular sidebar. Could anyone help?
|
You should make the check inside the widget class, unless you don't have a choice. The example in the codex is pretty much what you're looking for:
```
class cbs_map_widget extends WP_Widget{
function cbs_map_widget(){
$this->WP_Widget('cbsmaps', __('Widget Name'), array('classname' => 'cbsmaps', 'description' => __('whatever')));
...
add_action('wp_enqueue_scripts', array(&$this, 'js'));
}
function js(){
if ( is_active_widget(false, false, $this->id_base, true) ) {
// enqueue your scripts;
}
}
...
}
```
The `$widget_id` parameter is useful when you need to include your scripts only for a specific widget instance. For example when you have two `cbs_map_widget` widgets and want to include custom javascript for each of them.
The `$callback` argument is useful when you need to do the check outside the widget class (like you did above), but try to avoid it if you can do your check inside the class.
The other arguments are pretty much self explanatory (id\_base is basically a `"widget class indentifier"`, and the `$skip_inactive` is whether to check inactive widgets as well - should be true because I don't think you want to do that)...
Again, you don't need this unless you specifically want to check if a certain widget instance is active. Personally I use this method because I can access the instance options too:
```
...
function js(){
// we need to process all instances because this function gets to run only once
$widget_settings = get_option($this->option_name);
foreach((array)$widget_settings as $instance => $options){
// identify instance
$id = "{$this->id_base}-{$instance}";
// check if it's our instance
if(!is_active_widget(false, $id, $this->id_base)) continue; // not active
// instance is active
// access the widget instance options here, you may need them to do your checks
if($options['yourwidgetoption']) {
// do stuff
}
}
}
...
```
|
179,054 |
<p>I'm trying to get a menu items created from wordpress admin panel.</p>
<p>To do this I followed the instructions codex:
<a href="http://codex.wordpress.org/Function_Reference/wp_get_nav_menu_items" rel="nofollow">http://codex.wordpress.org/Function_Reference/wp_get_nav_menu_items</a></p>
<pre><code>// Get the nav menu based on $menu_name (same as 'theme_location' or 'menu' arg to wp_nav_menu)
// This code based on wp_nav_menu's code to get Menu ID from menu slug
$menu_name = 'custom_menu_slug';
if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) {
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menu_items = wp_get_nav_menu_items($menu->term_id);
$menu_list = '<ul id="menu-' . $menu_name . '">';
foreach ( (array) $menu_items as $key => $menu_item ) {
$title = $menu_item->title;
$url = $menu_item->url;
$menu_list .= '<li><a href="' . $url . '">' . $title . '</a></li>';
}
$menu_list .= '</ul>';
} else {
$menu_list = '<ul><li>Menu "' . $menu_name . '" not defined.</li></ul>';
}
// $menu_list now ready to output
echo $menu_list;
</code></pre>
<p>But I get always the error: Menu "cs-1-language" not defined.</p>
<p>I tried with the name and the slug and different menus but I always find that error.</p>
<p>Does anyone know what I'm doing wrong or if there is another way to list the items of a menu?</p>
<p>Thanks! </p>
|
[
{
"answer_id": 179017,
"author": "skribe",
"author_id": 67491,
"author_profile": "https://wordpress.stackexchange.com/users/67491",
"pm_score": 0,
"selected": false,
"text": "<p>WordPress has a function for that already. <code>is_active_widget</code> As the codex points out you must use the function after the widgets have all loaded. Then test the conditions with an if statement and if the map widget is not loaded you can run the rest of your script to load the map in your template.</p>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/is_active_widget\" rel=\"nofollow\">http://codex.wordpress.org/Function_Reference/is_active_widget</a></p>\n"
},
{
"answer_id": 228998,
"author": "Owais Alam",
"author_id": 91939,
"author_profile": "https://wordpress.stackexchange.com/users/91939",
"pm_score": 1,
"selected": false,
"text": "<p>You should make the check inside the widget class, unless you don't have a choice. The example in the codex is pretty much what you're looking for:</p>\n\n<pre><code>class cbs_map_widget extends WP_Widget{\n\n function cbs_map_widget(){\n $this->WP_Widget('cbsmaps', __('Widget Name'), array('classname' => 'cbsmaps', 'description' => __('whatever')));\n ... \n add_action('wp_enqueue_scripts', array(&$this, 'js'));\n }\n\n function js(){\n\n if ( is_active_widget(false, false, $this->id_base, true) ) {\n // enqueue your scripts;\n } \n\n }\n\n\n ...\n\n}\n</code></pre>\n\n<p>The <code>$widget_id</code> parameter is useful when you need to include your scripts only for a specific widget instance. For example when you have two <code>cbs_map_widget</code> widgets and want to include custom javascript for each of them.</p>\n\n<p>The <code>$callback</code> argument is useful when you need to do the check outside the widget class (like you did above), but try to avoid it if you can do your check inside the class.</p>\n\n<p>The other arguments are pretty much self explanatory (id_base is basically a <code>\"widget class indentifier\"</code>, and the <code>$skip_inactive</code> is whether to check inactive widgets as well - should be true because I don't think you want to do that)...</p>\n\n<p>Again, you don't need this unless you specifically want to check if a certain widget instance is active. Personally I use this method because I can access the instance options too:</p>\n\n<pre><code>...\n function js(){\n\n // we need to process all instances because this function gets to run only once\n $widget_settings = get_option($this->option_name);\n\n foreach((array)$widget_settings as $instance => $options){\n\n // identify instance\n $id = \"{$this->id_base}-{$instance}\";\n\n // check if it's our instance\n if(!is_active_widget(false, $id, $this->id_base)) continue; // not active\n\n // instance is active\n // access the widget instance options here, you may need them to do your checks\n if($options['yourwidgetoption']) {\n // do stuff \n } \n }\n\n }\n ... \n</code></pre>\n"
}
] |
2015/02/23
|
[
"https://wordpress.stackexchange.com/questions/179054",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68004/"
] |
I'm trying to get a menu items created from wordpress admin panel.
To do this I followed the instructions codex:
<http://codex.wordpress.org/Function_Reference/wp_get_nav_menu_items>
```
// Get the nav menu based on $menu_name (same as 'theme_location' or 'menu' arg to wp_nav_menu)
// This code based on wp_nav_menu's code to get Menu ID from menu slug
$menu_name = 'custom_menu_slug';
if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) {
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menu_items = wp_get_nav_menu_items($menu->term_id);
$menu_list = '<ul id="menu-' . $menu_name . '">';
foreach ( (array) $menu_items as $key => $menu_item ) {
$title = $menu_item->title;
$url = $menu_item->url;
$menu_list .= '<li><a href="' . $url . '">' . $title . '</a></li>';
}
$menu_list .= '</ul>';
} else {
$menu_list = '<ul><li>Menu "' . $menu_name . '" not defined.</li></ul>';
}
// $menu_list now ready to output
echo $menu_list;
```
But I get always the error: Menu "cs-1-language" not defined.
I tried with the name and the slug and different menus but I always find that error.
Does anyone know what I'm doing wrong or if there is another way to list the items of a menu?
Thanks!
|
You should make the check inside the widget class, unless you don't have a choice. The example in the codex is pretty much what you're looking for:
```
class cbs_map_widget extends WP_Widget{
function cbs_map_widget(){
$this->WP_Widget('cbsmaps', __('Widget Name'), array('classname' => 'cbsmaps', 'description' => __('whatever')));
...
add_action('wp_enqueue_scripts', array(&$this, 'js'));
}
function js(){
if ( is_active_widget(false, false, $this->id_base, true) ) {
// enqueue your scripts;
}
}
...
}
```
The `$widget_id` parameter is useful when you need to include your scripts only for a specific widget instance. For example when you have two `cbs_map_widget` widgets and want to include custom javascript for each of them.
The `$callback` argument is useful when you need to do the check outside the widget class (like you did above), but try to avoid it if you can do your check inside the class.
The other arguments are pretty much self explanatory (id\_base is basically a `"widget class indentifier"`, and the `$skip_inactive` is whether to check inactive widgets as well - should be true because I don't think you want to do that)...
Again, you don't need this unless you specifically want to check if a certain widget instance is active. Personally I use this method because I can access the instance options too:
```
...
function js(){
// we need to process all instances because this function gets to run only once
$widget_settings = get_option($this->option_name);
foreach((array)$widget_settings as $instance => $options){
// identify instance
$id = "{$this->id_base}-{$instance}";
// check if it's our instance
if(!is_active_widget(false, $id, $this->id_base)) continue; // not active
// instance is active
// access the widget instance options here, you may need them to do your checks
if($options['yourwidgetoption']) {
// do stuff
}
}
}
...
```
|
179,070 |
<p>I am trying to use <code>wp_redirect()</code> to redirect the user after successfully submitting a signup form on the page.</p>
<p>It's not working and shows the following error:</p>
<blockquote>
<p>Warning: Cannot modify header information - headers already sent by
(output started at
/Applications/MAMP/htdocs/theme/wp-content/themes/test/header.php:10)
in /Applications/MAMP/htdocs/theme/wp-includes/pluggable.php on line
1178</p>
</blockquote>
<p>I understand there has been already output before, that's why it's not working, but I have no clue how to make this work.</p>
<p>The signup form gets rendered by a function, and is submitted by another function, inside my functions.php. </p>
<pre><code>if ( isset( $_POST['subscribe'] ) ) {
// Submits the form and should then redirect
wp_redirect("/thank-you/");
exit;
}
</code></pre>
<p>Then both these functions are used where I want to show the signup form.</p>
<p>I'm afraid that's not the best thing to do. I should be creating some action that does that, but I have no idea how to implement that. Most of the tutorials I found show the results directly on the same page and don't require an additional redirect. Maybe that's why they are working with functions inside the functions.php</p>
|
[
{
"answer_id": 179071,
"author": "Abhisek Malakar",
"author_id": 62784,
"author_profile": "https://wordpress.stackexchange.com/users/62784",
"pm_score": 2,
"selected": false,
"text": "<pre><code>add_action('template_redirect', function(){\nif(isset($_POST['subscriptio'])){// make this condition such that it only matches when a registraiotn form get submitted\n/**\n * do your stuff here\n */\nwp_redirect();//....\n}\n});\n</code></pre>\n"
},
{
"answer_id": 179076,
"author": "mynamAvinash",
"author_id": 68015,
"author_profile": "https://wordpress.stackexchange.com/users/68015",
"pm_score": 4,
"selected": false,
"text": "<p>You have to use <code>wp_redirect()</code>\nbefore <code>get_header()</code>\nThen it will not show header error.</p>\n"
},
{
"answer_id": 179077,
"author": "Snowball",
"author_id": 68011,
"author_profile": "https://wordpress.stackexchange.com/users/68011",
"pm_score": 5,
"selected": true,
"text": "<p>Found the answer <a href=\"https://wordpress.stackexchange.com/questions/76991/wp-redirect-not-working-after-submitting-form/76993#76993\">(via)</a></p>\n<p>Instead of using the function directly, I added an action to "wp_loaded", that makes sure that it gets loaded before any headers are sent.</p>\n<pre><code><?php\nadd_action ('wp_loaded', 'my_custom_redirect');\nfunction my_custom_redirect() {\n if ( isset( $_POST['subscribe'] ) ) {\n $redirect = 'http://example.com/redirect-example-url.html';\n wp_redirect($redirect);\n exit;\n }\n} \n?>\n</code></pre>\n"
},
{
"answer_id": 359059,
"author": "Mohammad Zaer",
"author_id": 179573,
"author_profile": "https://wordpress.stackexchange.com/users/179573",
"pm_score": 2,
"selected": false,
"text": "<p>you can also do this</p>\n\n<p>Instead of the below line</p>\n\n<p>wp_redirect(\"$url\");</p>\n\n<p>write</p>\n\n<pre><code>echo(\"<script>location.href = '\".$url.\"'</script>\");\n</code></pre>\n\n<p>or</p>\n\n<pre><code><?php <script><?php echo(\"location.href = '\".$url.\"';\");?></script>?>\n</code></pre>\n\n<p>It'll definitely solve your problem.</p>\n"
},
{
"answer_id": 385198,
"author": "Karue Benson Karue",
"author_id": 153444,
"author_profile": "https://wordpress.stackexchange.com/users/153444",
"pm_score": 1,
"selected": false,
"text": "<p>If you are creating a plugin, you can call <code>ob_start();</code> at the beginning of the plugin code or <code>ob_start();</code> at the top of the functions.php file before code begins</p>\n<p><a href=\"https://i.stack.imgur.com/GWhFX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GWhFX.png\" alt=\"enter image description here\" /></a></p>\n"
}
] |
2015/02/23
|
[
"https://wordpress.stackexchange.com/questions/179070",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68011/"
] |
I am trying to use `wp_redirect()` to redirect the user after successfully submitting a signup form on the page.
It's not working and shows the following error:
>
> Warning: Cannot modify header information - headers already sent by
> (output started at
> /Applications/MAMP/htdocs/theme/wp-content/themes/test/header.php:10)
> in /Applications/MAMP/htdocs/theme/wp-includes/pluggable.php on line
> 1178
>
>
>
I understand there has been already output before, that's why it's not working, but I have no clue how to make this work.
The signup form gets rendered by a function, and is submitted by another function, inside my functions.php.
```
if ( isset( $_POST['subscribe'] ) ) {
// Submits the form and should then redirect
wp_redirect("/thank-you/");
exit;
}
```
Then both these functions are used where I want to show the signup form.
I'm afraid that's not the best thing to do. I should be creating some action that does that, but I have no idea how to implement that. Most of the tutorials I found show the results directly on the same page and don't require an additional redirect. Maybe that's why they are working with functions inside the functions.php
|
Found the answer [(via)](https://wordpress.stackexchange.com/questions/76991/wp-redirect-not-working-after-submitting-form/76993#76993)
Instead of using the function directly, I added an action to "wp\_loaded", that makes sure that it gets loaded before any headers are sent.
```
<?php
add_action ('wp_loaded', 'my_custom_redirect');
function my_custom_redirect() {
if ( isset( $_POST['subscribe'] ) ) {
$redirect = 'http://example.com/redirect-example-url.html';
wp_redirect($redirect);
exit;
}
}
?>
```
|
179,078 |
<p>I have multiple local installations of WordPress and want to have a single Must Use Plugins directory for all my local sites.</p>
<p>Is there anything I can add to wp-config for instance that will let me have a single folder which can be used for all my sites? Or perhaps another approach?</p>
<p>For instance:</p>
<p>/root/sites/site1/...
/root/sites/site2/...
/root/sites/site3/...</p>
<p>all use:</p>
<p>/root/mu-plugins/</p>
<p>Thanks</p>
|
[
{
"answer_id": 179079,
"author": "Stephen Harris",
"author_id": 9364,
"author_profile": "https://wordpress.stackexchange.com/users/9364",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, you can set the <code>WPMU_PLUGIN_DIR</code> constant in the config file of each of the sites (and <code>WPMU_PLUGIN_URL</code> for the url).</p>\n\n<p>By default it is defined as:</p>\n\n<pre><code>WP_CONTENT_DIR . '/mu-plugins'\n</code></pre>\n"
},
{
"answer_id": 179081,
"author": "Przemek Maczewski",
"author_id": 68013,
"author_profile": "https://wordpress.stackexchange.com/users/68013",
"pm_score": 1,
"selected": false,
"text": "<p>Try to create a symbolic link within wp-content for each site:</p>\n\n<pre><code>ln -s /root/mu-plugins mu-plugins\n</code></pre>\n"
}
] |
2015/02/23
|
[
"https://wordpress.stackexchange.com/questions/179078",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38077/"
] |
I have multiple local installations of WordPress and want to have a single Must Use Plugins directory for all my local sites.
Is there anything I can add to wp-config for instance that will let me have a single folder which can be used for all my sites? Or perhaps another approach?
For instance:
/root/sites/site1/...
/root/sites/site2/...
/root/sites/site3/...
all use:
/root/mu-plugins/
Thanks
|
Yes, you can set the `WPMU_PLUGIN_DIR` constant in the config file of each of the sites (and `WPMU_PLUGIN_URL` for the url).
By default it is defined as:
```
WP_CONTENT_DIR . '/mu-plugins'
```
|
179,090 |
<p>I try to add panel to my customizer but code below doesn't work (panel don't show in customizer container). My code:</p>
<pre><code>add_action( 'customize_register', 'customizer_test' );
function customizer_test($wp_customize) {
$wp_customize->add_panel( 'panel_id', array(
'priority' => 10,
'capability' => 'edit_theme_options',
'title' => __('Theme Options', 'mytheme'),
'description' => __('Several settings pertaining my theme', 'mytheme'),
) );
//sections
$wp_customize->add_section( 'header_settings', array(
'priority' => 10,
'capability' => 'edit_theme_options',
'title' => __('Header Settings', 'mytheme'),
'description' => __('Header elements configuration', 'mytheme'),
'panel' => 'panel_id',
) );
$wp_customize->add_section( 'footer_settings', array(
'priority' => 10,
'capability' => 'edit_theme_options',
'title' => __('Footer Settings', 'mytheme'),
'description' => __('Footer elements configuration', 'mytheme'),
'panel' => 'panel_id',
) );
}
</code></pre>
|
[
{
"answer_id": 232084,
"author": "Calvin Koepke",
"author_id": 80821,
"author_profile": "https://wordpress.stackexchange.com/users/80821",
"pm_score": 2,
"selected": false,
"text": "<p>First, use a different id for your panel than <code>panel_id</code>.</p>\n\n<p>Your sections will not show up without associated controls and settings, and panels will not show up without associated sections.</p>\n\n<p>Try adding controls to each section and that should fix your issue.</p>\n"
},
{
"answer_id": 257778,
"author": "thangavel .R",
"author_id": 114106,
"author_profile": "https://wordpress.stackexchange.com/users/114106",
"pm_score": 3,
"selected": false,
"text": "<p>You want to <strong>add_setting</strong> and <strong>add_control</strong> to your panel to work.</p>\n\n<p>For example:</p>\n\n<pre><code>function panel($wp_customize){\n\n$wp_customize->add_panel('some_panel',array(\n 'title'=>'Panel1',\n 'description'=> 'This is panel Description',\n 'priority'=> 10,\n));\n\n\n$wp_customize->add_section('section',array(\n 'title'=>'section',\n 'priority'=>10,\n 'panel'=>'some_panel',\n));\n\n\n$wp_customize->add_setting('setting_demo',array(\n 'defaule'=>'a',\n));\n\n\n$wp_customize->add_control('contrl_demo',array(\n 'label'=>'Text',\n 'type'=>'text',\n 'section'=>'section',\n 'settings'=>'setting_demo',\n));} add_action('customize_register','panel');\n</code></pre>\n"
},
{
"answer_id": 372135,
"author": "Chris Shabani Muswamba",
"author_id": 192491,
"author_profile": "https://wordpress.stackexchange.com/users/192491",
"pm_score": 0,
"selected": false,
"text": "<p>This piece of code work for me</p>\n<pre><code><? php\n \n/**\n * Add panel | custom section and settings\n */\nfunction firstest_news_theme_customize_register( $wp_customize ) {\n // add panel\n // Add Theme Options Panel.\n $wp_customize->add_panel( 'theme_option_panel',\n array(\n 'title' => esc_html__( 'Theme Options', 'wp-firstest-news-theme' ),\n 'priority' => 20,\n 'capability' => 'edit_theme_options',\n )\n );\n \n // Global Section Start.*/\n \n $wp_customize->add_section( 'social_option_section_settings',\n array(\n 'title' => esc_html__( 'Social Profile Options', 'wp_firstest_news_theme' ),\n 'priority' => 120,\n 'capability' => 'edit_theme_options',\n 'panel' => 'theme_option_panel', //Refence to panel above\n )\n );\n \n /*Social Profile*/\n $wp_customize->add_setting( 'social_profile',\n array(\n 'default' => $default['social_profile'],\n 'capability' => 'edit_theme_options'\n // 'sanitize_callback' => 'wp_firstest_news_theme_sanitize_checkbox',\n )\n );\n $wp_customize->add_control( 'social_profile',\n array(\n 'label' => esc_html__( 'Global Social Profile ( Nav Right )', 'wp-firstest-news-theme' ),\n 'section' => 'social_option_section_settings',\n 'type' => 'checkbox',\n \n )\n );\n \n // Global section start **************************\n $wp_customize->add_section('theme-option', array(\n 'title' => __('Edit Carousel', 'wp-firstest-news-theme'),\n 'description' => sprintf(__('Options for showcase', 'wp-firstest-news-theme')),\n 'priority' => 130,\n 'capability' => 'edit_theme_options',\n 'panel' => 'theme_option_panel' \n ));\n \n // Add image slider\n $wp_customize->add_setting('slider_1_image', array(\n 'default' => get_bloginfo('template_directory') . '/img/shocase1.jpg', 'wp-firstest-news-theme',\n 'type' => 'theme_mod'\n ));\n \n // Add control\n $wp_customize->add_control(new WP_Customize_Image_Control($wp_customize, 'slider_1_image', array(\n 'label' =>esc_html( __('Slider Image 1', 'wp-firstest-news-theme')),\n 'section' => 'theme-option',\n 'setting' => 'slider_1_image',\n 'priority' => 1\n )));\n \n // Add settings slider 1 heading\n $wp_customize->add_setting('showcase_1_heading', array(\n 'default' => _x('Another example headline.', 'wp-firstest-news-theme'),\n 'type' => 'theme_mod'\n ));\n \n // Add control\n $wp_customize->add_control('showcase_1_heading', array(\n 'label' => esc_html(__('heading', 'wp-firstest-news-theme')),\n 'section' => 'theme-option',\n 'priority' => 2\n ));\n }\n add_action( 'customize_register', 'firstest_news_theme_customize_register' );\n \n ?>\n</code></pre>\n"
}
] |
2015/02/23
|
[
"https://wordpress.stackexchange.com/questions/179090",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47607/"
] |
I try to add panel to my customizer but code below doesn't work (panel don't show in customizer container). My code:
```
add_action( 'customize_register', 'customizer_test' );
function customizer_test($wp_customize) {
$wp_customize->add_panel( 'panel_id', array(
'priority' => 10,
'capability' => 'edit_theme_options',
'title' => __('Theme Options', 'mytheme'),
'description' => __('Several settings pertaining my theme', 'mytheme'),
) );
//sections
$wp_customize->add_section( 'header_settings', array(
'priority' => 10,
'capability' => 'edit_theme_options',
'title' => __('Header Settings', 'mytheme'),
'description' => __('Header elements configuration', 'mytheme'),
'panel' => 'panel_id',
) );
$wp_customize->add_section( 'footer_settings', array(
'priority' => 10,
'capability' => 'edit_theme_options',
'title' => __('Footer Settings', 'mytheme'),
'description' => __('Footer elements configuration', 'mytheme'),
'panel' => 'panel_id',
) );
}
```
|
You want to **add\_setting** and **add\_control** to your panel to work.
For example:
```
function panel($wp_customize){
$wp_customize->add_panel('some_panel',array(
'title'=>'Panel1',
'description'=> 'This is panel Description',
'priority'=> 10,
));
$wp_customize->add_section('section',array(
'title'=>'section',
'priority'=>10,
'panel'=>'some_panel',
));
$wp_customize->add_setting('setting_demo',array(
'defaule'=>'a',
));
$wp_customize->add_control('contrl_demo',array(
'label'=>'Text',
'type'=>'text',
'section'=>'section',
'settings'=>'setting_demo',
));} add_action('customize_register','panel');
```
|
179,097 |
<p>I have custom post type named <em>soto_property</em> in which I have added three <em>wp_editor</em> as post meta, using this code -</p>
<pre><code> wp_editor( htmlspecialchars_decode($valueeee1),
'propertyEditor1',
$settings = array('textarea_name'=>'detail',
'editor_class'=>'propertyEditor')
);
wp_editor( htmlspecialchars_decode($valueeee2),
'propertyEditor2',
$settings = array('textarea_name'=>'features',
'editor_class'=>'propertyEditor')
);
wp_editor( htmlspecialchars_decode($valueeee3),
'propertyEditor3',
$settings = array('textarea_name'=>'text_to_pdf',
'editor_class'=>'propertyEditor')
);
</code></pre>
<p>Now I have installed <code>qtranslate</code> plugin to make my site Multilingual. This plugin automaticaly add Language tab in its default content editor. I want to add these languages tabs in my custom editor also, so it can save content in defined languages.</p>
<p>How can I do this.? Please help me.</p>
|
[
{
"answer_id": 179100,
"author": "Karolína Vyskočilová",
"author_id": 64771,
"author_profile": "https://wordpress.stackexchange.com/users/64771",
"pm_score": 2,
"selected": false,
"text": "<p>it looks as already answered <a href=\"https://wordpress.stackexchange.com/questions/97889/qtranslate-for-custom-post-type\">here on stackexchange</a> (really detailed way), as first you can try: </p>\n\n<pre><code>add_filter('soto_property','qtrans_convertURL');\n</code></pre>\n\n<p>Anyway, have a look here on <a href=\"https://wordpress.org/plugins/qtranslate-slug/\" rel=\"nofollow noreferrer\">qtranslate slug plugin</a>, usually it save tons of troubles. And small note - if I were you, I would better use <a href=\"https://wordpress.org/plugins/mqtranslate/\" rel=\"nofollow noreferrer\">mqTranslate</a> (which is based on qTranslate, but it's compatible with last version of WP)</p>\n"
},
{
"answer_id": 179878,
"author": "dazunE",
"author_id": 31027,
"author_profile": "https://wordpress.stackexchange.com/users/31027",
"pm_score": 1,
"selected": false,
"text": "<p>I have done custom post type with multiple content editors ready to translate, I have used <a href=\"https://github.com/rilwis/meta-box\" rel=\"nofollow\">This Metabox Plugin</a> to add the meta boxes, this plugin allows you to create multiple meta boxes according to the theme requirements, to achieve your requirements, 1st install this plugin <a href=\"https://wordpress.org/plugins/meta-box/\" rel=\"nofollow\">Here is the link</a> \nThen add code as follows in your functions.php or separate file then include to functions.php</p>\n\n<pre><code>global $meta_boxes;\n$meta_boxes = array();\n\n$meta_boxes[] = array(\n\n 'id' => 'standard',\n 'title' => __( 'Simple Editors', 'your-languge-key' ),\n 'pages' => array( 'your-post-type' ),\n 'context' => 'normal',\n 'priority' => 'high',\n 'autosave' => true,\n 'fields' => array(\n array(\n 'name' => __( 'Simple Editor', 'your-languge-key' ),\n 'id' => \"{$prefix}home-bottom-content\",\n 'type' => 'wysiwyg',\n // Set the 'raw' parameter to TRUE to prevent data being passed through wpautop() on save\n 'raw' => true,\n 'std' => __( 'WYSIWYG default value', 'your-languge-key' ),\n\n // Editor settings, see wp_editor() function: look4wp.com/wp_editor\n 'options' => array(\n 'textarea_rows' => 4, \n 'teeny' => true,\n 'media_buttons' => false, // mediabuttons to editor\n ),\n ),\n ),\n\n);\n/**\n * Register meta boxes\n *\n * @return void\n */\nfunction rw_register_meta_boxes()\n{\n global $meta_boxes;\n\n // Make sure there's no errors when the plugin is deactivated or during upgrade\n if ( class_exists( 'RW_Meta_Box' ) ) {\n foreach ( $meta_boxes as $meta_box ) {\n if ( isset( $meta_box['only_on'] ) && ! rw_maybe_include( $meta_box['only_on'] ) ) {\n continue;\n }\n\n new RW_Meta_Box( $meta_box );\n }\n }\n}\n\nadd_action( 'admin_init', 'rw_register_meta_boxes' );\n\n/**\n * Check if meta boxes is included\n *\n * @return bool\n */\nfunction rw_maybe_include( $conditions ) {\n // Include in back-end only\n if ( ! defined( 'WP_ADMIN' ) || ! WP_ADMIN ) {\n return false;\n }\n\n // Always include for ajax\n if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {\n return true;\n }\n\n if ( isset( $_GET['post'] ) ) {\n $post_id = intval( $_GET['post'] );\n }\n elseif ( isset( $_POST['post_ID'] ) ) {\n $post_id = intval( $_POST['post_ID'] );\n }\n else {\n $post_id = false;\n }\n\n $post_id = (int) $post_id;\n $post = get_post( $post_id );\n\n foreach ( $conditions as $cond => $v ) {\n // Catch non-arrays too\n if ( ! is_array( $v ) ) {\n $v = array( $v );\n }\n\n switch ( $cond ) {\n case 'id':\n if ( in_array( $post_id, $v ) ) {\n return true;\n }\n break;\n case 'parent':\n $post_parent = $post->post_parent;\n if ( in_array( $post_parent, $v ) ) {\n return true;\n }\n break;\n case 'slug':\n $post_slug = $post->post_name;\n if ( in_array( $post_slug, $v ) ) {\n return true;\n }\n break;\n case 'category': //post must be saved or published first\n $categories = get_the_category( $post->ID );\n $catslugs = array();\n foreach ( $categories as $category )\n {\n array_push( $catslugs, $category->slug );\n }\n if ( array_intersect( $catslugs, $v ) )\n {\n return true;\n }\n break;\n case 'template':\n $template = get_post_meta( $post_id, '_wp_page_template', true );\n if ( in_array( $template, $v ) )\n {\n return true;\n }\n break;\n }\n }\n\n // If no condition matched\n return false;\n}\n</code></pre>\n\n<p>Here I have added only one editor, you can add number of editors by reusing editor filed. Hope this is solve your issue. good luck !</p>\n"
},
{
"answer_id": 190486,
"author": "shashank",
"author_id": 67983,
"author_profile": "https://wordpress.stackexchange.com/users/67983",
"pm_score": 0,
"selected": false,
"text": "<p>Solved!</p>\n\n<p>I have used qranslate-x plugin which makes my custom wp_editor translatable on my custom post type page.</p>\n"
}
] |
2015/02/23
|
[
"https://wordpress.stackexchange.com/questions/179097",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67983/"
] |
I have custom post type named *soto\_property* in which I have added three *wp\_editor* as post meta, using this code -
```
wp_editor( htmlspecialchars_decode($valueeee1),
'propertyEditor1',
$settings = array('textarea_name'=>'detail',
'editor_class'=>'propertyEditor')
);
wp_editor( htmlspecialchars_decode($valueeee2),
'propertyEditor2',
$settings = array('textarea_name'=>'features',
'editor_class'=>'propertyEditor')
);
wp_editor( htmlspecialchars_decode($valueeee3),
'propertyEditor3',
$settings = array('textarea_name'=>'text_to_pdf',
'editor_class'=>'propertyEditor')
);
```
Now I have installed `qtranslate` plugin to make my site Multilingual. This plugin automaticaly add Language tab in its default content editor. I want to add these languages tabs in my custom editor also, so it can save content in defined languages.
How can I do this.? Please help me.
|
it looks as already answered [here on stackexchange](https://wordpress.stackexchange.com/questions/97889/qtranslate-for-custom-post-type) (really detailed way), as first you can try:
```
add_filter('soto_property','qtrans_convertURL');
```
Anyway, have a look here on [qtranslate slug plugin](https://wordpress.org/plugins/qtranslate-slug/), usually it save tons of troubles. And small note - if I were you, I would better use [mqTranslate](https://wordpress.org/plugins/mqtranslate/) (which is based on qTranslate, but it's compatible with last version of WP)
|
179,137 |
<p>I would like to remove the following two script and one style tags. They appear to be added by the Yoast SEO plugin, but looking through their plugin files yields nothing promising. Does anyone know where these are enqueued or another way to remove them? </p>
<pre><code><!-- / Yoast WordPress SEO plugin. -->
<script type="text/javascript" src="http://barrjoneslegal.com/wp-includes/js/jquery/jquery.js?ver=1.11.1"></script>
<script type="text/javascript" src="http://barrjoneslegal.com/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.2.1"></script>
<style type="text/css">.recentcomments a{display:inline !important;padding:0 !important;margin:0 !important;}</style>
</code></pre>
<p>(For the inevitable "why" comment, there's no reason to load these as I don't have any other scripts on the front-end site requiring them.)</p>
<p>Thanks</p>
|
[
{
"answer_id": 179146,
"author": "Przemek Maczewski",
"author_id": 68013,
"author_profile": "https://wordpress.stackexchange.com/users/68013",
"pm_score": 3,
"selected": true,
"text": "<p>How this line (9th) is created within your theme code?</p>\n\n<pre><code><script type=\"text/javascript\" src=\"/wp-content/themes/blankslate/js/jquery-1.11.1.min.js\"></script>\n</code></pre>\n\n<p>If it is hard-coded in header.php, then I would recommend to remove it. <a href=\"http://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\">Scripts should be enqueued</a> instead of hard-coding them. </p>\n\n<p>Next, you can de-register jquery.migrate script with the following code added to functions.php:</p>\n\n<pre><code>/**\n * Remove jQuery migrate script\n */\nadd_filter( 'wp_default_scripts', 'barrjoneslegal_remove_jquery_migrate' );\nfunction barrjoneslegal_remove_jquery_migrate( &$scripts ) {\n if ( ! is_admin() ) :\n $scripts->remove( 'jquery' );\n $scripts->add( 'jquery', false, array( 'jquery-core' ), false );\n endif;\n}\n</code></pre>\n\n<p>Now you have the minimal amount of scripts on the front end. You need jQuery itself, because it is used by the following script (by the way, it should be enqueued as well):</p>\n\n<pre><code><script type=\"text/javascript\" src=\"/wp-content/themes/blankslate/js/site.js\"></script>\n</code></pre>\n"
},
{
"answer_id": 316521,
"author": "B. Roubert",
"author_id": 135171,
"author_profile": "https://wordpress.stackexchange.com/users/135171",
"pm_score": 0,
"selected": false,
"text": "<p>The underneath line isn't relative to Yoast but WP Bakery (formerly Visual Composer):</p>\n\n<pre><code><style type=\"text/css\">.recentcomments a{display:inline !important;padding:0 !important;margin:0 !important;}</style>\n</code></pre>\n\n<p>you can put this into the functions.php of your child theme in order to remove it from the head of your HTML page:</p>\n\n<pre><code>/* Deactivate adding of extra inline CSS in <head> by WP Bakery for comment widget purposes */\n\nadd_filter( 'show_recent_comments_widget_style', '__return_false' );\n</code></pre>\n"
}
] |
2015/02/23
|
[
"https://wordpress.stackexchange.com/questions/179137",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67629/"
] |
I would like to remove the following two script and one style tags. They appear to be added by the Yoast SEO plugin, but looking through their plugin files yields nothing promising. Does anyone know where these are enqueued or another way to remove them?
```
<!-- / Yoast WordPress SEO plugin. -->
<script type="text/javascript" src="http://barrjoneslegal.com/wp-includes/js/jquery/jquery.js?ver=1.11.1"></script>
<script type="text/javascript" src="http://barrjoneslegal.com/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.2.1"></script>
<style type="text/css">.recentcomments a{display:inline !important;padding:0 !important;margin:0 !important;}</style>
```
(For the inevitable "why" comment, there's no reason to load these as I don't have any other scripts on the front-end site requiring them.)
Thanks
|
How this line (9th) is created within your theme code?
```
<script type="text/javascript" src="/wp-content/themes/blankslate/js/jquery-1.11.1.min.js"></script>
```
If it is hard-coded in header.php, then I would recommend to remove it. [Scripts should be enqueued](http://codex.wordpress.org/Function_Reference/wp_enqueue_script) instead of hard-coding them.
Next, you can de-register jquery.migrate script with the following code added to functions.php:
```
/**
* Remove jQuery migrate script
*/
add_filter( 'wp_default_scripts', 'barrjoneslegal_remove_jquery_migrate' );
function barrjoneslegal_remove_jquery_migrate( &$scripts ) {
if ( ! is_admin() ) :
$scripts->remove( 'jquery' );
$scripts->add( 'jquery', false, array( 'jquery-core' ), false );
endif;
}
```
Now you have the minimal amount of scripts on the front end. You need jQuery itself, because it is used by the following script (by the way, it should be enqueued as well):
```
<script type="text/javascript" src="/wp-content/themes/blankslate/js/site.js"></script>
```
|
179,140 |
<p>I'm getting the following error in my <code>debug.log</code>:</p>
<pre><code>PHP Notice: Trying to get property of non-object in /my-wesbite/wp-content/themes/express/header.php on line 36
</code></pre>
<p>This is line 36 of <code>header.php</code> in my theme:</p>
<pre><code><body id="page-<?php echo $post->post_name;?>" <?php body_class(); ?> data-site-url="<?php echo site_url(); ?>">
</code></pre>
<p><code>wp_head()</code> is called before line 36. </p>
<p>I have looked at the output source of every page of the website and <code>$post->post_name</code>, <code>body_class()</code>, and <code>site_url()</code> all <code>echo</code> properly.</p>
<p>My assumption is the error is related to <code>$post->post_name</code>, because it is talking about an object's property. Am I needing to declare <code>global $post</code> first or something else?</p>
<p>Looking at <code>debug.log</code> I can't tell if this error fires on every page or just on certain ones.</p>
<p>As a sidenote, I'm planning on adjusting the <code>id</code> to account for taxonomies as well, but I can get that sorted out once I figure out what is causing this error. </p>
<p>Thank you for any help you can offer.</p>
|
[
{
"answer_id": 179156,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 0,
"selected": false,
"text": "<p>Keep in mind this will only work if you're on a single page or post, because when you're displaying the output of a loop, you don't yet have a post until you've started the loop (or, you might have the first post in the loop, but either way that's not what you'd want to set a body ID for).</p>\n\n<p>I'd recommend wrapping this ID with two conditionals:</p>\n\n<pre><code><?php if(is_single() || is_page()){ ?> id=\"page-<?php echo $post->post_name;?>\" <?php } ?>\n</code></pre>\n\n<p>You'll probably find that this then just works. But if you want to be absolutely sure, you could try setting up your postdata first, either with global $post or by running the_post(). Without testing it I'm not entirely sure, but I would suspect the conditionals could solve your problem as the error is probably coming from pages where it doesn't all happen automatically for you (i.e. archive pages, search results, etc.)</p>\n\n<p>Let me know if that fixes it!</p>\n"
},
{
"answer_id": 179171,
"author": "cenk",
"author_id": 31606,
"author_profile": "https://wordpress.stackexchange.com/users/31606",
"pm_score": 1,
"selected": false,
"text": "<h1>A better method for what you are trying to achieve</h1>\n\n<p>This answer is not about the php error you are getting. You need these classes for styling your website right?</p>\n\n<p>Put the following code in your functions.php</p>\n\n<pre><code>// A better body class\nfunction condensed_body_class($classes) {\n global $post;\n\n // add a class for the name of the page - later might want to remove the auto generated pageid class which isn't very useful\n if( is_page()) {\n $pn = $post->post_name;\n $classes[] = \"page_\".$pn;\n }\n\n if( !is_page() ) { \n $pn = $post->post_name;\n $classes[] = \"post_\".$pn;\n }\n\n if ( $post && $post->post_parent ) {\n // add a class for the parent page name\n $post_parent = get_post($post->post_parent);\n $parentSlug = $post_parent->post_name;\n\n if ( is_page() && $post->post_parent ) {\n $classes[] = \"parent_\".$parentSlug;\n }\n\n }\n\n // add class for the name of the custom template used (if any)\n $temp = get_page_template();\n if ( $temp != null ) {\n $path = pathinfo($temp);\n $tmp = $path['filename'] . \".\" . $path['extension'];\n $tn= str_replace(\".php\", \"\", $tmp);\n $classes[] = \"template_\".$tn;\n }\n return $classes;\n}\n\n\n/* a better body class */\nadd_filter( 'body_class', 'condensed_body_class' );\n</code></pre>\n\n<p>And where you need the body class, put this:</p>\n\n<pre><code><body <?php body_class(); ?>>\n</code></pre>\n\n<p>You will see that so many useful class information will be printed.</p>\n\n<p>Good Luck!</p>\n"
}
] |
2015/02/23
|
[
"https://wordpress.stackexchange.com/questions/179140",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14190/"
] |
I'm getting the following error in my `debug.log`:
```
PHP Notice: Trying to get property of non-object in /my-wesbite/wp-content/themes/express/header.php on line 36
```
This is line 36 of `header.php` in my theme:
```
<body id="page-<?php echo $post->post_name;?>" <?php body_class(); ?> data-site-url="<?php echo site_url(); ?>">
```
`wp_head()` is called before line 36.
I have looked at the output source of every page of the website and `$post->post_name`, `body_class()`, and `site_url()` all `echo` properly.
My assumption is the error is related to `$post->post_name`, because it is talking about an object's property. Am I needing to declare `global $post` first or something else?
Looking at `debug.log` I can't tell if this error fires on every page or just on certain ones.
As a sidenote, I'm planning on adjusting the `id` to account for taxonomies as well, but I can get that sorted out once I figure out what is causing this error.
Thank you for any help you can offer.
|
A better method for what you are trying to achieve
==================================================
This answer is not about the php error you are getting. You need these classes for styling your website right?
Put the following code in your functions.php
```
// A better body class
function condensed_body_class($classes) {
global $post;
// add a class for the name of the page - later might want to remove the auto generated pageid class which isn't very useful
if( is_page()) {
$pn = $post->post_name;
$classes[] = "page_".$pn;
}
if( !is_page() ) {
$pn = $post->post_name;
$classes[] = "post_".$pn;
}
if ( $post && $post->post_parent ) {
// add a class for the parent page name
$post_parent = get_post($post->post_parent);
$parentSlug = $post_parent->post_name;
if ( is_page() && $post->post_parent ) {
$classes[] = "parent_".$parentSlug;
}
}
// add class for the name of the custom template used (if any)
$temp = get_page_template();
if ( $temp != null ) {
$path = pathinfo($temp);
$tmp = $path['filename'] . "." . $path['extension'];
$tn= str_replace(".php", "", $tmp);
$classes[] = "template_".$tn;
}
return $classes;
}
/* a better body class */
add_filter( 'body_class', 'condensed_body_class' );
```
And where you need the body class, put this:
```
<body <?php body_class(); ?>>
```
You will see that so many useful class information will be printed.
Good Luck!
|
179,145 |
<p>I need to add a plugin to a theme and enable it automatically once the theme is activated. Would also like to change its settings if possible. This is the plugin I am trying to include: <a href="https://wordpress.org/plugins/subheading/" rel="nofollow">https://wordpress.org/plugins/subheading/</a></p>
<p>I tried adding the plugin inside the theme plugin folder but it does not show up on WP plugins page. What am I doing wrong?</p>
|
[
{
"answer_id": 179147,
"author": "Joey Yax",
"author_id": 6148,
"author_profile": "https://wordpress.stackexchange.com/users/6148",
"pm_score": 2,
"selected": false,
"text": "<p>There's no method to bundle a plugin with a theme install. Your best bet would be to check if a plugin is installed using <code>is_plugin_active</code> in your functions.php. If not, display a notice in the admin area directing them to download/install it.</p>\n"
},
{
"answer_id": 179148,
"author": "kaiser",
"author_id": 385,
"author_profile": "https://wordpress.stackexchange.com/users/385",
"pm_score": 4,
"selected": true,
"text": "<h2>The user decides</h2>\n\n<p>To answer your last question first:</p>\n\n<blockquote>\n <p>I tried adding the plugin inside the theme plugin folder [...] What am I doing wrong?</p>\n</blockquote>\n\n<p>You are trying to bundle functionality into a theme. That is the wrong thing in the first place. Themes offer presentation - Plugins offers functionality.</p>\n\n<p>Aside from that, functionality should be the users choice. And your theme should work with and without the plugin. You also save the user from loosing his settings when he switches the theme. Just note that your theme <strong>\"supports subheading plugin\"</strong>. The installation and activation is up to the user.</p>\n\n<h2>How to?</h2>\n\n<p>To achieve that, you can just wrap plugin functionality in a filter or hook and check if the plugin is active using <a href=\"http://codex.wordpress.org/Function_Reference/is_plugin_active\"><code>is_plugin_active()</code></a>:</p>\n\n<pre><code>// functions.php\nadd_action( 'subheading', 'subheading_callback' );\nfunction subheading_callback()\n{\n if ( ! is_plugin_active( 'plugin-folder-name/plugin-file.php' ) )\n {\n remove_action( current_action(), __FUNCTION__ );\n return;\n }\n\n // Call subheading-plugin function to output subheading here\n // From the subheading plugin:\n // $before = '', $after = '', $display = true, $id = false\n the_subheading( '<h3>', '</h3>', true, get_the_ID() );\n}\n</code></pre>\n\n<p>Then in your template file, just add the hook to output the subheading.</p>\n\n<pre><code>// for e.g. single.php - in the loop\ndo_action( 'subheading' );\n</code></pre>\n\n<p>Aside from that, there is the <a href=\"http://tgmpluginactivation.com/\">\"TGM Plugin Activation\"</a> script which you can use in your theme. It allows you to tell the user upon activation that s/he needs the plugins X, Y and Z which you can set up with default settings (IIRC).</p>\n"
}
] |
2015/02/23
|
[
"https://wordpress.stackexchange.com/questions/179145",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63443/"
] |
I need to add a plugin to a theme and enable it automatically once the theme is activated. Would also like to change its settings if possible. This is the plugin I am trying to include: <https://wordpress.org/plugins/subheading/>
I tried adding the plugin inside the theme plugin folder but it does not show up on WP plugins page. What am I doing wrong?
|
The user decides
----------------
To answer your last question first:
>
> I tried adding the plugin inside the theme plugin folder [...] What am I doing wrong?
>
>
>
You are trying to bundle functionality into a theme. That is the wrong thing in the first place. Themes offer presentation - Plugins offers functionality.
Aside from that, functionality should be the users choice. And your theme should work with and without the plugin. You also save the user from loosing his settings when he switches the theme. Just note that your theme **"supports subheading plugin"**. The installation and activation is up to the user.
How to?
-------
To achieve that, you can just wrap plugin functionality in a filter or hook and check if the plugin is active using [`is_plugin_active()`](http://codex.wordpress.org/Function_Reference/is_plugin_active):
```
// functions.php
add_action( 'subheading', 'subheading_callback' );
function subheading_callback()
{
if ( ! is_plugin_active( 'plugin-folder-name/plugin-file.php' ) )
{
remove_action( current_action(), __FUNCTION__ );
return;
}
// Call subheading-plugin function to output subheading here
// From the subheading plugin:
// $before = '', $after = '', $display = true, $id = false
the_subheading( '<h3>', '</h3>', true, get_the_ID() );
}
```
Then in your template file, just add the hook to output the subheading.
```
// for e.g. single.php - in the loop
do_action( 'subheading' );
```
Aside from that, there is the ["TGM Plugin Activation"](http://tgmpluginactivation.com/) script which you can use in your theme. It allows you to tell the user upon activation that s/he needs the plugins X, Y and Z which you can set up with default settings (IIRC).
|
179,150 |
<p>Is there a way to get the block of code below to extract a list of given user information as it creates the page for the new user. It creates new page for new user as supposed but I'd like it to alos extract and display some information from the user profile.</p>
<pre><code>function my_create_page($user_id){
$the_user = get_userdata($user_id);
$new_user_name = $the_user->user_login;
$my_post = array();
$my_post['post_title'] = $new_user_name;
$my_post['post_type'] = 'page';
$my_post['post_content'] = '';
$my_post['post_status'] = 'publish';
$my_post['post_theme'] = 'user-profile';
wp_insert_post( $my_post );
}
add_action('user_register', 'my_create_page');
</code></pre>
|
[
{
"answer_id": 179151,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 1,
"selected": false,
"text": "<p>If I understand your question correctly, you should be able to grab the information you're after from $the_user.</p>\n\n<p>If you use:</p>\n\n<pre><code>$my_post['post_content'] = print_r($the_user,true);\n</code></pre>\n\n<p>you should be able to see all the available user information in the page. Once you know exactly what you want, you can echo it out nicely with something like:</p>\n\n<pre><code>$my_post['post_content'] = \"Username: \".$the_user->user_login.\"<br />Roles:\".$the_user->roles;\n</code></pre>\n\n<p>If that's not quite what you were after let me know!</p>\n"
},
{
"answer_id": 183125,
"author": "3pepe3",
"author_id": 64864,
"author_profile": "https://wordpress.stackexchange.com/users/64864",
"pm_score": 0,
"selected": false,
"text": "<p>The solution to your problem can be accomplished with a page template, but first we need to fix your previews code</p>\n\n<pre><code><?php\n/**/\nfunction add_user_page($user_id){\n $user = get_userdata($user_id);\n $role_with_page = \"subscriber\";\n if( reset($user->roles) != $role_with_page ) return; //Exit if user role doesn't allows ownership of page\n $post_type = 'page'; /// I would prefer a custom post type like 'user_upages'\n global $wpdb;\n $where = get_posts_by_author_sql( $post_type, true, $user_id );\n if( $wpdb->get_var( \"SELECT COUNT(*) FROM $wpdb->posts $where\" ) >= 1 ) return; // Exit if the user already have a page\n $title = $user->user_login;\n $template = 'user-profile.php'; // if the post type where a CPT you could create just the file single-$posttype.php\n $user_page = array(\n 'post_title' => $title,\n 'post_type' => $post_type,\n 'post_content' => '', // leave empty the post content so the user can edit this just in case than you will enable this option...\n 'post_author' => $user_id,\n 'post_status' => 'publish',\n 'post_theme' => 'user-profile', // ???? Are you talkin about page_template ?\n 'page_template' => $template\n );\n if( $post_id = wp_insert_post( $user_page ) ){\n if( $post_type == 'page' ) update_post_meta( $post_id, '_wp_page_template', $template );\n __update_post_meta( $post_id, 'foobar', 'some value' ); // Save all the data you need as post_meta\n __update_post_meta( $post_id, 'user_owner', $user_id ); // This is just in case you dont want to give ownership (post_author) to the user\n update_user_meta( $user_id, 'user_owns_unique_page', $post_id ); // Store the page owned by this user\n update_user_meta( $user_id, 'some_random_stuff', rand( 0,10 ) ); // Store the page owned by this user\n }\n //do_action('acf/save_post' , $post_id); /* Uncomment this if you use ACF (than you should) ;) */\n return $post_id;\n}\nadd_action( 'user_register', 'add_user_page' );\nadd_action( 'set_user_role', 'add_user_page' );\n\n?>\n</code></pre>\n\n<p>You should leave the post_content as it is because this is static data that will not retrieve the user data.\nIf you really want to update the post_content then you would just add a shortcode (you should write the shortcode in your functions.php).\nEx.</p>\n\n<pre><code>'post_content' => \"[show_user_data id='{$user_id}']\",\n</code></pre>\n\n<p>Then if you want to use the page_template then your user-profile.php should like something like :</p>\n\n<pre><code><?php\n/*\n * Template Name: User profile page\n * Description: A Page Template for users.\n */\n\nget_header();\n\nwhile ( have_posts() ) :\n the_post();\n $user_id = get_the_author_meta( \"ID\" ); // or get_post_meta( get_the_ID(), 'user_owner', true );\n $user = get_userdata( $user_id );\n $user_name = $user->first_name.\" \".$user->last_name;\n $some_random_stuff = get_user_meta( $user_id, 'some_random_stuff', $single ); \n $foobar = get_post_meta( get_the_ID() , 'foobar', true );\n ?>\n <ul>\n <li><?php echo $user_name ?></li>\n <li><?php echo $some_random_stuff ?></li>\n <li><?php echo $foobar ?></li>\n <li><?php the_content(); ?></li>\n </ul>\n <?php\nendwhile;\nget_footer();\n?>\n</code></pre>\n\n<p>You can read this : \n<a href=\"https://codex.wordpress.org/Page_Templates\" rel=\"nofollow\">https://codex.wordpress.org/Page_Templates</a></p>\n\n<p>Hope this helps.</p>\n"
}
] |
2015/02/23
|
[
"https://wordpress.stackexchange.com/questions/179150",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/4401/"
] |
Is there a way to get the block of code below to extract a list of given user information as it creates the page for the new user. It creates new page for new user as supposed but I'd like it to alos extract and display some information from the user profile.
```
function my_create_page($user_id){
$the_user = get_userdata($user_id);
$new_user_name = $the_user->user_login;
$my_post = array();
$my_post['post_title'] = $new_user_name;
$my_post['post_type'] = 'page';
$my_post['post_content'] = '';
$my_post['post_status'] = 'publish';
$my_post['post_theme'] = 'user-profile';
wp_insert_post( $my_post );
}
add_action('user_register', 'my_create_page');
```
|
If I understand your question correctly, you should be able to grab the information you're after from $the\_user.
If you use:
```
$my_post['post_content'] = print_r($the_user,true);
```
you should be able to see all the available user information in the page. Once you know exactly what you want, you can echo it out nicely with something like:
```
$my_post['post_content'] = "Username: ".$the_user->user_login."<br />Roles:".$the_user->roles;
```
If that's not quite what you were after let me know!
|
179,155 |
<p>I'm attempting to use <code>get_users</code> to select users with only a certain meta value. In this case the meta key is <code>extraInfo</code> but the the values are in a serialized array. Can I pull users out like this? This is what I've been trying with no luck:</p>
<pre><code>$meta_key = 'extraInfo[zip]';
$meta_value = $zip;
$query = get_users('meta_key='.$meta_key.'&meta_value='.$meta_value);
</code></pre>
|
[
{
"answer_id": 179200,
"author": "Abhisek Malakar",
"author_id": 62784,
"author_profile": "https://wordpress.stackexchange.com/users/62784",
"pm_score": 0,
"selected": false,
"text": "<pre><code> <?php\n /**\n * are you sure that your meta value is ok\n */\n $meta_key = 'extraInfo[zip]';\n $meta_value = $zip;\n $query = get_users(\n array(\n 'meta_key' => $meta_key,\n 'meta_value' => $meta_value\n ));\n</code></pre>\n"
},
{
"answer_id": 179253,
"author": "WordPress Mike",
"author_id": 33921,
"author_profile": "https://wordpress.stackexchange.com/users/33921",
"pm_score": 1,
"selected": false,
"text": "<p>The answer is, this can't be done with any efficiency. The best thing to do is pull the data out of the serialized array and save each as their own key/value pair in the <code>wp_usermeta</code> table. My key was <code>extraInfo</code> and the values I needed were serialized in the value. This is the script I've used to create new keys and values from the data automatically. The echoing was just used for some on screen feedback and isn't necessary. If you have a lot of users, you might want to use <code>number</code> and <code>offest</code> in the <code>get_users</code> query. Hope this helps someone.</p>\n\n<pre><code><?php\n\n$users = get_users( 'number=10' );\nforeach ( $users as $user ) {\n $extras = unserialize(get_the_author_meta( \"extraInfo\", $user->ID ));\n foreach ($extras as $key=> $value) {\n echo '<p>' . $key . ': ' . $value . '</p>';\n update_user_meta( $user->ID, $key, $value);\n }\n echo '<p>' . esc_html( $user->user_email ) . '</p>';\n echo '<hr>';\n}\n\n?>\n</code></pre>\n"
}
] |
2015/02/23
|
[
"https://wordpress.stackexchange.com/questions/179155",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33921/"
] |
I'm attempting to use `get_users` to select users with only a certain meta value. In this case the meta key is `extraInfo` but the the values are in a serialized array. Can I pull users out like this? This is what I've been trying with no luck:
```
$meta_key = 'extraInfo[zip]';
$meta_value = $zip;
$query = get_users('meta_key='.$meta_key.'&meta_value='.$meta_value);
```
|
The answer is, this can't be done with any efficiency. The best thing to do is pull the data out of the serialized array and save each as their own key/value pair in the `wp_usermeta` table. My key was `extraInfo` and the values I needed were serialized in the value. This is the script I've used to create new keys and values from the data automatically. The echoing was just used for some on screen feedback and isn't necessary. If you have a lot of users, you might want to use `number` and `offest` in the `get_users` query. Hope this helps someone.
```
<?php
$users = get_users( 'number=10' );
foreach ( $users as $user ) {
$extras = unserialize(get_the_author_meta( "extraInfo", $user->ID ));
foreach ($extras as $key=> $value) {
echo '<p>' . $key . ': ' . $value . '</p>';
update_user_meta( $user->ID, $key, $value);
}
echo '<p>' . esc_html( $user->user_email ) . '</p>';
echo '<hr>';
}
?>
```
|
179,162 |
<p>I am experiencing some odd behavior, that apparently happens "out of the box" with WordPress.</p>
<p>If I upload a file through the media manager called: <code>services.jpg;</code> then go try to create a page with the permalink <code>http://example.com/services/;</code> The slug <code>services-2</code> is given instead, because the attachment is already using that slug.</p>
<p>Visiting <code>http://example.com/services/</code> loads the attachment page.</p>
<p>I have not enabled any plugins or added anything into functions.php to modify the rewrites for attachments.</p>
<p>Has anyone run into this before? Know where to start to disable this functionality?</p>
|
[
{
"answer_id": 179165,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 1,
"selected": false,
"text": "<p>Tom's comment is correct, in that this is normal behaviour and there is not much you can do to stop it.</p>\n\n<p>But you can change slugs after things are uploaded/created. While you shouldn't do this if the links are known/publicised/listed on search engines, if you're just trying to fix this problem occasionally after an upload then you can edit the slug of the attachment (to be something like <code>services-attachment</code>), and then edit the slug of the page to be <code>services</code>.</p>\n\n<p>To do this, go to Media, click Edit under the attachment you want to edit (or if on grid view, click the attachment then click Edit more details), then at the top you'll see the permalink.. clicking Edit here will let you change the slug.</p>\n\n<p>Then repeat the same process for the page itself.</p>\n"
},
{
"answer_id": 179211,
"author": "Przemek Maczewski",
"author_id": 68013,
"author_profile": "https://wordpress.stackexchange.com/users/68013",
"pm_score": 2,
"selected": false,
"text": "<p>You may hook wp_unique_post_slug() and append some string to the original slug if the post is an attachment type. The original slug based on post title will remain free.</p>\n\n<p>UPDATED after Rachel Baker's comment: original slug suffix is some random string. It does not guarantee uniqueness but may be enough for simple use cases.</p>\n\n<pre><code>add_filter( 'wp_unique_post_slug', 'wpse17916_unique_post_slug', 10, 6 );\nfunction wpse17916_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ) {\n if ( 'attachment' == $post_type )\n $slug = $original_slug . uniqid( '-' );\n return $slug;\n}\n</code></pre>\n"
},
{
"answer_id": 179270,
"author": "Matt Keys",
"author_id": 32799,
"author_profile": "https://wordpress.stackexchange.com/users/32799",
"pm_score": 4,
"selected": true,
"text": "<p>Thank you for the response everyone. I played around with macemmek's solution and I think it led me to an even better solution:</p>\n\n<pre><code>add_filter( 'wp_unique_post_slug_is_bad_attachment_slug', '__return_true' );\n</code></pre>\n\n<p>That is all that is needed. This will automatically 'skip' the default assigned slug on any attachment. So an attachment that might normally get the slug \"services\" will now get the slug \"services-2\".</p>\n"
},
{
"answer_id": 239882,
"author": "DigitalDesignDj",
"author_id": 13856,
"author_profile": "https://wordpress.stackexchange.com/users/13856",
"pm_score": 0,
"selected": false,
"text": "<p>I think what you need to do here is use a redirect to prevent people from seeing the media items. It's a good fit with the other solutions presented here. Prepend something to the media item slugs, the write a redirect to 'get rid' of the media pages.</p>\n"
}
] |
2015/02/24
|
[
"https://wordpress.stackexchange.com/questions/179162",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32799/"
] |
I am experiencing some odd behavior, that apparently happens "out of the box" with WordPress.
If I upload a file through the media manager called: `services.jpg;` then go try to create a page with the permalink `http://example.com/services/;` The slug `services-2` is given instead, because the attachment is already using that slug.
Visiting `http://example.com/services/` loads the attachment page.
I have not enabled any plugins or added anything into functions.php to modify the rewrites for attachments.
Has anyone run into this before? Know where to start to disable this functionality?
|
Thank you for the response everyone. I played around with macemmek's solution and I think it led me to an even better solution:
```
add_filter( 'wp_unique_post_slug_is_bad_attachment_slug', '__return_true' );
```
That is all that is needed. This will automatically 'skip' the default assigned slug on any attachment. So an attachment that might normally get the slug "services" will now get the slug "services-2".
|
179,167 |
<p>So, this is how WordPress is saving my CPT meta:</p>
<pre><code> array(8) {
["product_id"]=> array(1) { [0]=> string(10) "abcdefg987" }
["end_date"]=> array(1) { [0]=> string(10) "02-02-2015" }
}
</code></pre>
<p>But I want it to be like this: </p>
<pre><code> array(8) {
["product_id"]=> "abcdefg987" ,
["end_date"]=> "02-02-2015"
}
</code></pre>
<p>So, is it possible ?</p>
<hr>
<p>Here is some of my code:<br>
<strong>to save:</strong><br>
<code>update_post_meta($post_id, "end_date", $_POST["end_date"]);</code><br>
<strong>The meta box:</strong> </p>
<pre><code>global $post;
$custom = get_post_custom($post->ID);
$end_date = $custom["end_date"][0]; // <- this was an old hack to this problem
<p><label>End Date:</label><br />
<input name="end_date" value="<?php echo $end_date; ?>"></input></p>
</code></pre>
<hr>
<p><strong>What I really want to do ?</strong><br>
What I need is to get the Post (custom) with the 'end_date' greater than today. So, I have a meta_query, but doesn't work, cause also shows me the posts with 'end_date' < today, so I thought is because it get its values in the array, and not just the values, here is the code:</p>
<pre><code>$args = array(
'post_type' => 'myEventCPT',
'meta_query' => array(
array( 'meta_key' => 'end_date',
'value' => date("m-d-Y"), // Set today's date
'compare' => '>=',
//'type' => 'DATE'
)
)
);
$my_event_post = get_posts( $args );
</code></pre>
|
[
{
"answer_id": 179193,
"author": "Abhisek Malakar",
"author_id": 62784,
"author_profile": "https://wordpress.stackexchange.com/users/62784",
"pm_score": 0,
"selected": false,
"text": "<p>THe only possible way is this if your html input name is</p>\n\n<p>name=\"end_date[]\"...</p>\n\n<p>SO can you please check it once more</p>\n"
},
{
"answer_id": 179231,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 1,
"selected": false,
"text": "<p>Your issue is not with storage, it is with retrieval. <code>get_post_custom()</code> is inconvenient and rarely used in practice.</p>\n\n<p><a href=\"http://queryposts.com/function/get_post_meta/\" rel=\"nofollow\"><code>get_post_meta()</code></a> is more common in practice. Note it has explicit argument to retrieve a single value, rather than array of values for a key (which WP can do too).</p>\n"
},
{
"answer_id": 179284,
"author": "Francisco Corrales Morales",
"author_id": 45567,
"author_profile": "https://wordpress.stackexchange.com/users/45567",
"pm_score": 0,
"selected": false,
"text": "<p>ok, I fixed (with the help of everybody, from Reddit, and StackExchange),\nI had several issues.<br>\nThis is my working code:</p>\n\n<pre><code>$args = array(\n 'numberposts' => 1,\n 'post_type' => 'my-cpt',\n 'order' => 'ASC' ,\n 'meta_query' => array(\n 'relation' => 'AND',\n array( 'key' => 'end_date',\n 'value' => date(\"Y-m-d\"), //today\n 'compare' => '>=', \n 'type' => 'DATE'\n ),\n array( 'key' => 'product_id',\n 'value' => $product['id'],\n 'compare' => '=',\n 'type' => 'CHAR'\n ), \n ),\n); \n</code></pre>\n"
}
] |
2015/02/24
|
[
"https://wordpress.stackexchange.com/questions/179167",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45567/"
] |
So, this is how WordPress is saving my CPT meta:
```
array(8) {
["product_id"]=> array(1) { [0]=> string(10) "abcdefg987" }
["end_date"]=> array(1) { [0]=> string(10) "02-02-2015" }
}
```
But I want it to be like this:
```
array(8) {
["product_id"]=> "abcdefg987" ,
["end_date"]=> "02-02-2015"
}
```
So, is it possible ?
---
Here is some of my code:
**to save:**
`update_post_meta($post_id, "end_date", $_POST["end_date"]);`
**The meta box:**
```
global $post;
$custom = get_post_custom($post->ID);
$end_date = $custom["end_date"][0]; // <- this was an old hack to this problem
<p><label>End Date:</label><br />
<input name="end_date" value="<?php echo $end_date; ?>"></input></p>
```
---
**What I really want to do ?**
What I need is to get the Post (custom) with the 'end\_date' greater than today. So, I have a meta\_query, but doesn't work, cause also shows me the posts with 'end\_date' < today, so I thought is because it get its values in the array, and not just the values, here is the code:
```
$args = array(
'post_type' => 'myEventCPT',
'meta_query' => array(
array( 'meta_key' => 'end_date',
'value' => date("m-d-Y"), // Set today's date
'compare' => '>=',
//'type' => 'DATE'
)
)
);
$my_event_post = get_posts( $args );
```
|
Your issue is not with storage, it is with retrieval. `get_post_custom()` is inconvenient and rarely used in practice.
[`get_post_meta()`](http://queryposts.com/function/get_post_meta/) is more common in practice. Note it has explicit argument to retrieve a single value, rather than array of values for a key (which WP can do too).
|
179,187 |
<p>I am working on a custom carousel (Wordpress + Bootstrap). The carousel is working without problems. However, I would like to hide Bootstrap carousel indicators and arrows if there is only one post.</p>
<p>I was able to hide the carousel arrows by using this code:</p>
<pre><code><?php if ($counter > 1) { ?>
<a class="left carousel-control" href="#testimonials" role="button" data-slide="prev"><span class="glyphicon glyphicon-chevron-left"></span></a>
<a class="right carousel-control" href="#testimonials" role="button" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span></a>
<?php } ?>
</code></pre>
<p>However, I am not able to access the $counter variable where the carousel indicators are located. I tried using a while inside a while but the page breaks.</p>
<p>Here's the code in question:</p>
<pre><code> <ol class="carousel-indicators">
<?php $indicatorCount = 0; while ( $loop->have_posts() ) : $loop->the_post(); ?>
<li data-target="#testimonials" data-slide-to="<?=$indicatorCount?>" class="<?php echo ($indicatorCount==0) ? "active" : "" ?>"></li>
<?php echo $indicatorCount; ?>
<?php ++$indicatorCount; endwhile; ?>
</ol> <!-- /.carousel-indicators -->
</code></pre>
<p>And here's my full code (just for reference)</p>
<pre><code> <?php
$args = array(
'post_type' => 'post', 'posts_per_page' => -1, 'orderby' => 'menu_order', 'order' => 'ASC',
);
$loop = new WP_Query( $args );
?>
<?php if( $loop->have_posts() ): ?>
<div id="testimonials" class="carousel sp slide carousel-fade" data-ride="carousel" >
<ol class="carousel-indicators">
<?php $indicatorCount = 0; while ( $loop->have_posts() ) : $loop->the_post(); ?>
<li data-target="#testimonials" data-slide-to="<?=$indicatorCount?>" class="<?php echo ($indicatorCount==0) ? "active" : "" ?>"></li>
<?php echo $indicatorCount; ?>
<?php ++$indicatorCount; endwhile; ?>
</ol> <!-- /.carousel-indicators -->
<div class="carousel-inner">
<?php $counter = 0; while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="item <?php echo ($counter==0) ? "active" : "" ?>">
<div class="row">
<div class="col-md-4">
<img class="img-responsive" src="http://placehold.it/360x200" />
</div>
<div class="col-md-8">
<h3><?php the_title(); ?></h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
</div>
</div> <!-- /.row -->
</div> <!-- /.item -->
<?php $counter++; endwhile; ?>
<?php if ($counter > 1) { ?>
<a class="left carousel-control" href="#testimonials" role="button" data-slide="prev"><span class="glyphicon glyphicon-chevron-left"></span></a>
<a class="right carousel-control" href="#testimonials" role="button" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span></a>
<?php } ?>
</div> <!-- /.carousel-inner -->
</div> <!-- #testimonials .carousel -->
<?php endif; ?>
</code></pre>
<p>Any ideas on how I could hide the carousel indicators block if there's only one post?</p>
<p>Thanks a lot for your input and help!</p>
<p>UPDATE: Here's the code with the provided answer!</p>
<pre><code> <?php
$args = array(
'post_type' => 'post', 'posts_per_page' => -1, 'orderby' => 'menu_order', 'order' => 'ASC',
);
$loop = new WP_Query( $args );
?>
<?php if( $loop->have_posts() ): ?>
<div id="testimonials" class="carousel sp slide carousel-fade" data-ride="carousel" >
<?php if($loop->post_count > 1) { ?>
<ol class="carousel-indicators">
<?php $indicatorCount = 0; while ( $loop->have_posts() ) : $loop->the_post(); ?>
<li data-target="#testimonials" data-slide-to="<?=$indicatorCount?>" class="<?php echo ($indicatorCount==0) ? "active" : "" ?>"></li>
<?php ++$indicatorCount; endwhile; ?>
</ol> <!-- /.carousel-indicators -->
<?php } ?>
<div class="carousel-inner">
<?php $counter = 0; while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="item <?php echo ($counter==0) ? "active" : "" ?>">
<div class="row">
<div class="col-md-4">
<img class="img-responsive" src="http://placehold.it/360x200" />
</div>
<div class="col-md-8">
<h3><?php the_title(); ?></h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
</div>
</div> <!-- /.row -->
</div> <!-- /.item -->
<?php $counter++; endwhile; ?>
<?php if($loop->post_count > 1) { ?>
<a class="left carousel-control" href="#testimonials" role="button" data-slide="prev"><span class="glyphicon glyphicon-chevron-left"></span></a>
<a class="right carousel-control" href="#testimonials" role="button" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span></a>
<?php } ?>
</div> <!-- /.carousel-inner -->
</div> <!-- #testimonials .carousel -->
<?php endif; ?>
</code></pre>
|
[
{
"answer_id": 179188,
"author": "Abhisek Malakar",
"author_id": 62784,
"author_profile": "https://wordpress.stackexchange.com/users/62784",
"pm_score": 2,
"selected": true,
"text": "<p>You can use the condition </p>\n\n<pre><code><?php\n if($loop->post_count > 1){\n /**\n * so show the carousel counter\n */\n\n }\n?>\n</code></pre>\n"
},
{
"answer_id": 179191,
"author": "Kobus Beets",
"author_id": 63672,
"author_profile": "https://wordpress.stackexchange.com/users/63672",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a solution I also used in the past. This allowed me to use the slides in other places on the page as well as in tiled galleries or thumbnails and so on. </p>\n\n<pre><code><?php \n$indicators = array();\n$slides = array();\n\n$counter = 0;\nwhile ( $loop->have_posts() ) : $counter++;\n array_push($indicators, '<li data-target=\"#testimonials\" data-slide-to=\"'.$counter.'\" class=\"'.(($counter == 0) ? \"active\" : \"\").'\"></li>');\n array_push($slides, $loop->the_post());\nendwhile; \n\n//show the slide indicators\nif(count($indicators) > 1) { ?>\n <ol class=\"carousel-indicators\">\n <?php foreach($indicators as $indicator):\n echo $indicator;\n endforeach; ?>\n </ol>\n<?php } \n\n//show the left and right controls\nif(count($indicators) > 1) { ?>\n <a class=\"left carousel-control\" href=\"#testimonials\" role=\"button\" data-slide=\"prev\"><span class=\"glyphicon glyphicon-chevron-left\"></span></a>\n <a class=\"right carousel-control\" href=\"#testimonials\" role=\"button\" data-slide=\"next\"><span class=\"glyphicon glyphicon-chevron-right\"></span></a>\n<?php } \n\n//show the slides\nif(count($slides) > 0):\n foreach($slides as $slide):\n //the way I used to print the slides\n endforeach;\nendif; ?>\n</code></pre>\n"
}
] |
2015/02/24
|
[
"https://wordpress.stackexchange.com/questions/179187",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/21245/"
] |
I am working on a custom carousel (Wordpress + Bootstrap). The carousel is working without problems. However, I would like to hide Bootstrap carousel indicators and arrows if there is only one post.
I was able to hide the carousel arrows by using this code:
```
<?php if ($counter > 1) { ?>
<a class="left carousel-control" href="#testimonials" role="button" data-slide="prev"><span class="glyphicon glyphicon-chevron-left"></span></a>
<a class="right carousel-control" href="#testimonials" role="button" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span></a>
<?php } ?>
```
However, I am not able to access the $counter variable where the carousel indicators are located. I tried using a while inside a while but the page breaks.
Here's the code in question:
```
<ol class="carousel-indicators">
<?php $indicatorCount = 0; while ( $loop->have_posts() ) : $loop->the_post(); ?>
<li data-target="#testimonials" data-slide-to="<?=$indicatorCount?>" class="<?php echo ($indicatorCount==0) ? "active" : "" ?>"></li>
<?php echo $indicatorCount; ?>
<?php ++$indicatorCount; endwhile; ?>
</ol> <!-- /.carousel-indicators -->
```
And here's my full code (just for reference)
```
<?php
$args = array(
'post_type' => 'post', 'posts_per_page' => -1, 'orderby' => 'menu_order', 'order' => 'ASC',
);
$loop = new WP_Query( $args );
?>
<?php if( $loop->have_posts() ): ?>
<div id="testimonials" class="carousel sp slide carousel-fade" data-ride="carousel" >
<ol class="carousel-indicators">
<?php $indicatorCount = 0; while ( $loop->have_posts() ) : $loop->the_post(); ?>
<li data-target="#testimonials" data-slide-to="<?=$indicatorCount?>" class="<?php echo ($indicatorCount==0) ? "active" : "" ?>"></li>
<?php echo $indicatorCount; ?>
<?php ++$indicatorCount; endwhile; ?>
</ol> <!-- /.carousel-indicators -->
<div class="carousel-inner">
<?php $counter = 0; while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="item <?php echo ($counter==0) ? "active" : "" ?>">
<div class="row">
<div class="col-md-4">
<img class="img-responsive" src="http://placehold.it/360x200" />
</div>
<div class="col-md-8">
<h3><?php the_title(); ?></h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
</div>
</div> <!-- /.row -->
</div> <!-- /.item -->
<?php $counter++; endwhile; ?>
<?php if ($counter > 1) { ?>
<a class="left carousel-control" href="#testimonials" role="button" data-slide="prev"><span class="glyphicon glyphicon-chevron-left"></span></a>
<a class="right carousel-control" href="#testimonials" role="button" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span></a>
<?php } ?>
</div> <!-- /.carousel-inner -->
</div> <!-- #testimonials .carousel -->
<?php endif; ?>
```
Any ideas on how I could hide the carousel indicators block if there's only one post?
Thanks a lot for your input and help!
UPDATE: Here's the code with the provided answer!
```
<?php
$args = array(
'post_type' => 'post', 'posts_per_page' => -1, 'orderby' => 'menu_order', 'order' => 'ASC',
);
$loop = new WP_Query( $args );
?>
<?php if( $loop->have_posts() ): ?>
<div id="testimonials" class="carousel sp slide carousel-fade" data-ride="carousel" >
<?php if($loop->post_count > 1) { ?>
<ol class="carousel-indicators">
<?php $indicatorCount = 0; while ( $loop->have_posts() ) : $loop->the_post(); ?>
<li data-target="#testimonials" data-slide-to="<?=$indicatorCount?>" class="<?php echo ($indicatorCount==0) ? "active" : "" ?>"></li>
<?php ++$indicatorCount; endwhile; ?>
</ol> <!-- /.carousel-indicators -->
<?php } ?>
<div class="carousel-inner">
<?php $counter = 0; while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="item <?php echo ($counter==0) ? "active" : "" ?>">
<div class="row">
<div class="col-md-4">
<img class="img-responsive" src="http://placehold.it/360x200" />
</div>
<div class="col-md-8">
<h3><?php the_title(); ?></h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
</div>
</div> <!-- /.row -->
</div> <!-- /.item -->
<?php $counter++; endwhile; ?>
<?php if($loop->post_count > 1) { ?>
<a class="left carousel-control" href="#testimonials" role="button" data-slide="prev"><span class="glyphicon glyphicon-chevron-left"></span></a>
<a class="right carousel-control" href="#testimonials" role="button" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span></a>
<?php } ?>
</div> <!-- /.carousel-inner -->
</div> <!-- #testimonials .carousel -->
<?php endif; ?>
```
|
You can use the condition
```
<?php
if($loop->post_count > 1){
/**
* so show the carousel counter
*/
}
?>
```
|
179,208 |
<p>I have tried the following SQL query without any success. Can anybody that have a better understanding of SQL help?</p>
<p>Here is what I am trying to achieve:</p>
<ul>
<li>Get a list of all main events (ME) where the parent_id = 0.</li>
<li>Order the ME list based on the post date of the earliest child events which is obtained from a sub query.</li>
<li>Perform this query instead of the default WP query. </li>
</ul>
<p>I am not sure how to achieve the same results in the default WP_Query object. </p>
<p>The SQL Code:</p>
<pre><code>SELECT * FROM `wp_posts` AS ME LEFT JOIN
(
SELECT * FROM `wp_posts` AS SE
WHERE SE.`post_type`="event"
AND SE.`post_status` IN ("publish", "future")
AND SE.`post_parent` != 0
GROUP BY SE.`post_parent`
ORDER BY SE.`post_date` ASC
LIMIT 1
) AS SE2
ON ME.ID = SE2.post_parent
WHERE ME.post_parent = 0
AND ME.post_type="event"
AND ME.post_status IN("publish", "future")
ORDER BY SE2.post_date
</code></pre>
<p>The code where it will be used.</p>
<pre><code>function pre_get_posts($query) {
global $wpdb;
if(!is_admin() && $query->is_main_query()) {
//check if the post type matches this post type
if(is_post_type_archive('event')) {
//will this work?
$query->set('query', 'SELECT * FROM `wp_posts` AS ME LEFT JOIN (SELECT * FROM `wp_posts` AS SE WHERE SE.`post_type`="event" AND SE.`post_status` IN ("publish", "future") AND SE.`post_parent` != 0 GROUP BY SE.`post_parent` ORDER BY SE.`post_date` ASC LIMIT 1) AS SE2 ON ME.ID = SE2.post_parent WHERE ME.post_parent = 0 AND ME.post_type="event" AND ME.post_status IN("publish", "future") ORDER BY SE2.post_date');
}
}
}
</code></pre>
|
[
{
"answer_id": 179226,
"author": "Kobus Beets",
"author_id": 63672,
"author_profile": "https://wordpress.stackexchange.com/users/63672",
"pm_score": 1,
"selected": false,
"text": "<p>After hours of searching and testing I finally came to a solution. This code and SQL shows events with a parent id of 0 and is ordered by the dates of child events. </p>\n\n<p>Raw SQL cannot be used to replace the default way WP queries the database but there are always some kind of workaround that can be used. </p>\n\n<p>The PHP Code: </p>\n\n<pre><code><?php \nfunction pre_get_posts($query) { \n global $wpdb;\n if(!is_admin() && $query->is_main_query()) {\n if(is_post_type_archive('event')) {\n $my_query = $wpdb->prepare('SELECT * FROM %1$s AS A LEFT JOIN (SELECT * FROM (SELECT * FROM %1$s WHERE post_type=\"event\" AND post_date > \"'.date('Y-m-d').'\" ORDER BY post_date ASC) AS B WHERE B.post_type = \"event\" AND B.post_status IN (\"publish\", \"future\") AND B.post_parent != 0 GROUP BY B.post_parent ORDER BY B.post_date ASC) AS C ON A.ID=C.post_parent WHERE A.post_type = \"event\" AND A.post_status IN (\"publish\", \"future\") AND A.post_parent = 0 ORDER BY C.post_date ASC;', $wpdb->posts);\n $ids = $wpdb->get_col($my_query);\n\n $query->set('post__in', $ids);\n $query->set('order', 'ASC');\n $query->set('orderby', 'C.post_date');\n $query->set('posts_per_page', -1);\n $query->set('post_status', array('publish', 'future'));\n }\n }\n}\n?>\n</code></pre>\n\n<p>The Formatted SQL Query:</p>\n\n<pre><code>SELECT *\nFROM wp_posts AS A\nLEFT JOIN\n (\n SELECT *\n FROM (\n SELECT *\n FROM wp_posts\n WHERE post_type=\"event\"\n AND post_date > \"'.date('Y-m-d').'\"\n ORDER BY post_date ASC\n ) AS B\n WHERE B.post_type = \"event\"\n AND B.post_status IN (\"publish\", \"future\")\n AND B.post_parent != 0\n GROUP BY B.post_parent\n ORDER BY B.post_date ASC\n ) AS C\nON A.id=C.post_parent\nWHERE A.post_type = \"event\"\nAND A.post_status IN (\"publish\", \"future\")\nAND A.post_parent = 0\nORDER BY C.post_date ASC; \n</code></pre>\n\n<p>@kaiser - Thank you for the tips. I'm still learning to use this site so I will keep it in mind. </p>\n\n<p>If there are any simpler solutions to accomplish the same results, please share :)</p>\n"
},
{
"answer_id": 179475,
"author": "Kobus Beets",
"author_id": 63672,
"author_profile": "https://wordpress.stackexchange.com/users/63672",
"pm_score": 1,
"selected": true,
"text": "<p>The very thing I tried to accomplish appear not to be complex at all.</p>\n\n<p>SQL Code:</p>\n\n<pre><code>SELECT *\nFROM wp_posts\nWHERE post_type = \"event\"\nAND post_status IN (\"publish\", \"future\")\nAND post_date > \"2015-02-26\"\nAND post_parent != 0\nGROUP BY post_parent\nORDER BY post_date ASC;\n</code></pre>\n\n<p>There were two ways I could do this. I am using the second option for performance reasons.</p>\n\n<p>Option 1: The first option runs two queries. The first query is to get the ID's of \"future child\" events and the second is to only include the child records with the provided ID's.</p>\n\n<pre><code>add_action('pre_get_posts', 'modify_event_pre_get_posts');\nfunction modify_event_pre_get_posts($query) {\n global $wpdb;\n if(!is_admin() && $query->is_main_query()) {\n if(is_post_type_archive('event')) {\n $my_query = $wpdb->prepare('SELECT * FROM %1$s WHERE post_type = \"event\" AND post_status IN (\"publish\", \"future\") AND post_date > '.date('Y-m-d').' AND post_parent != 0 GROUP BY post_parent ORDER BY post_date ASC;', $wpdb->posts);\n $ids = $wpdb->get_col($my_query);\n\n $query->set('post__in', $ids);\n $query->set('order', 'ASC');\n $query->set('orderby', 'post_date');\n $query->set('posts_per_page', -1);\n $query->set('post_status', array('publish', 'future'));\n }\n }\n}\n</code></pre>\n\n<p>Option 2: The second option only runs one query. It changes the default WP database query to fetch the desired results from the database. Take note that I used two hooks here namely pre_get_posts, and posts_groupby.</p>\n\n<pre><code>add_action('pre_get_posts', 'modify_event_pre_get_posts');\nadd_filter('posts_groupby', 'modify_event_posts_groupby');\n\nfunction modify_event_posts_groupby($group_by) {\n global $wpdb;\n if(!is_admin() && is_main_query()) {\n if(is_post_type_archive('event')) {\n $group_by = \"{$wpdb->posts}.post_parent\";\n }\n }\n return $group_by;\n}\n\nfunction modify_event_pre_get_posts($query) {\n global $wpdb;\n if(!is_admin() && $query->is_main_query()) {\n if(is_post_type_archive('event')) {\n $query->set('post_status', array('publish', 'future'));\n $query->set('date_query', array('after' => date('Y-m-d')));\n $query->set('order', 'ASC');\n $query->set('orderby', 'post_date');\n $query->set('post_parent__not_in', array(0));\n }\n }\n}\n</code></pre>\n"
}
] |
2015/02/24
|
[
"https://wordpress.stackexchange.com/questions/179208",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63672/"
] |
I have tried the following SQL query without any success. Can anybody that have a better understanding of SQL help?
Here is what I am trying to achieve:
* Get a list of all main events (ME) where the parent\_id = 0.
* Order the ME list based on the post date of the earliest child events which is obtained from a sub query.
* Perform this query instead of the default WP query.
I am not sure how to achieve the same results in the default WP\_Query object.
The SQL Code:
```
SELECT * FROM `wp_posts` AS ME LEFT JOIN
(
SELECT * FROM `wp_posts` AS SE
WHERE SE.`post_type`="event"
AND SE.`post_status` IN ("publish", "future")
AND SE.`post_parent` != 0
GROUP BY SE.`post_parent`
ORDER BY SE.`post_date` ASC
LIMIT 1
) AS SE2
ON ME.ID = SE2.post_parent
WHERE ME.post_parent = 0
AND ME.post_type="event"
AND ME.post_status IN("publish", "future")
ORDER BY SE2.post_date
```
The code where it will be used.
```
function pre_get_posts($query) {
global $wpdb;
if(!is_admin() && $query->is_main_query()) {
//check if the post type matches this post type
if(is_post_type_archive('event')) {
//will this work?
$query->set('query', 'SELECT * FROM `wp_posts` AS ME LEFT JOIN (SELECT * FROM `wp_posts` AS SE WHERE SE.`post_type`="event" AND SE.`post_status` IN ("publish", "future") AND SE.`post_parent` != 0 GROUP BY SE.`post_parent` ORDER BY SE.`post_date` ASC LIMIT 1) AS SE2 ON ME.ID = SE2.post_parent WHERE ME.post_parent = 0 AND ME.post_type="event" AND ME.post_status IN("publish", "future") ORDER BY SE2.post_date');
}
}
}
```
|
The very thing I tried to accomplish appear not to be complex at all.
SQL Code:
```
SELECT *
FROM wp_posts
WHERE post_type = "event"
AND post_status IN ("publish", "future")
AND post_date > "2015-02-26"
AND post_parent != 0
GROUP BY post_parent
ORDER BY post_date ASC;
```
There were two ways I could do this. I am using the second option for performance reasons.
Option 1: The first option runs two queries. The first query is to get the ID's of "future child" events and the second is to only include the child records with the provided ID's.
```
add_action('pre_get_posts', 'modify_event_pre_get_posts');
function modify_event_pre_get_posts($query) {
global $wpdb;
if(!is_admin() && $query->is_main_query()) {
if(is_post_type_archive('event')) {
$my_query = $wpdb->prepare('SELECT * FROM %1$s WHERE post_type = "event" AND post_status IN ("publish", "future") AND post_date > '.date('Y-m-d').' AND post_parent != 0 GROUP BY post_parent ORDER BY post_date ASC;', $wpdb->posts);
$ids = $wpdb->get_col($my_query);
$query->set('post__in', $ids);
$query->set('order', 'ASC');
$query->set('orderby', 'post_date');
$query->set('posts_per_page', -1);
$query->set('post_status', array('publish', 'future'));
}
}
}
```
Option 2: The second option only runs one query. It changes the default WP database query to fetch the desired results from the database. Take note that I used two hooks here namely pre\_get\_posts, and posts\_groupby.
```
add_action('pre_get_posts', 'modify_event_pre_get_posts');
add_filter('posts_groupby', 'modify_event_posts_groupby');
function modify_event_posts_groupby($group_by) {
global $wpdb;
if(!is_admin() && is_main_query()) {
if(is_post_type_archive('event')) {
$group_by = "{$wpdb->posts}.post_parent";
}
}
return $group_by;
}
function modify_event_pre_get_posts($query) {
global $wpdb;
if(!is_admin() && $query->is_main_query()) {
if(is_post_type_archive('event')) {
$query->set('post_status', array('publish', 'future'));
$query->set('date_query', array('after' => date('Y-m-d')));
$query->set('order', 'ASC');
$query->set('orderby', 'post_date');
$query->set('post_parent__not_in', array(0));
}
}
}
```
|
179,209 |
<p>I tried to find filters or a hook to modify link returned by this function</p>
<p><a href="http://codex.wordpress.org/Function_Reference/get_post_type_archive_link" rel="nofollow"><code>get_post_type_archive_link()</code></a></p>
<p>I have gone through most of the documentation. I'm not sure it's not there or I'm not able to find it.</p>
<p>Any suggestions would be very appreciated.</p>
|
[
{
"answer_id": 179212,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 4,
"selected": true,
"text": "<p>The filter is <code>post_type_archive_link</code>, <a href=\"https://core.trac.wordpress.org/browser/tags/4.1.1/src/wp-includes/link-template.php#L1112\">defined (WP 4.1.1) on line 1112 of file wp-includes/link-template.php</a>:</p>\n\n<pre><code>apply_filters( 'post_type_archive_link', $link, $post_type );\n</code></pre>\n\n<p>And the use:</p>\n\n<pre><code>add_filter( 'post_type_archive_link', function( $link, $post_type ) {\n\n //Do something\n\n return $link;\n\n}, 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 179213,
"author": "kaiser",
"author_id": 385,
"author_profile": "https://wordpress.stackexchange.com/users/385",
"pm_score": 3,
"selected": false,
"text": "<p>Just look at the <a href=\"https://github.com/WordPress/WordPress/blob/4.0/wp-includes/link-template.php#L1083\">source of <code>get_post_type_archive_link()</code></a>:</p>\n\n<pre><code>return apply_filters( 'post_type_archive_link', $link, $post_type );\n</code></pre>\n\n<p>Sidenote: The function uses <code>home_url()</code>, which is a wrapper for <a href=\"https://github.com/WordPress/WordPress/blob/4.0/wp-includes/link-template.php#L2437\"><code>get_home_url()</code></a>, which offers another filter:</p>\n\n<pre><code>return apply_filters( 'home_url', $url, $path, $orig_scheme, $blog_id );\n</code></pre>\n\n<p>that runs earlier. With \"pretty permalinks\" enabled, it runs the following:</p>\n\n<pre><code>$link = home_url( user_trailingslashit( $struct, 'post_type_archive' ) );\n</code></pre>\n\n<p>and without:</p>\n\n<pre><code>$link = home_url( '?post_type=' . $post_type );\n</code></pre>\n"
},
{
"answer_id": 179214,
"author": "kraftner",
"author_id": 47733,
"author_profile": "https://wordpress.stackexchange.com/users/47733",
"pm_score": 3,
"selected": false,
"text": "<p>Welcome to WPSE Ittikorn!</p>\n\n<p>Sometimes it is the easiest to just look right at the source. There even is a link right at the bottom of the Codex page you linked:</p>\n\n<p><a href=\"https://core.trac.wordpress.org/browser/tags/4.1.1/src/wp-includes/link-template.php#L1112\">https://core.trac.wordpress.org/browser/tags/4.1.1/src/wp-includes/link-template.php#L1112</a></p>\n\n<p>There you can easily see that there actually is a filter called <code>post_type_archive_link</code></p>\n\n<p>So to give you an example:</p>\n\n<pre><code>add_filter( \"post_type_archive_link\", \"wpse_179209\", 10, 2 );\n\nfunction wpse_179209( $link, $post_type ){\n // Do whatever you want to the $link\n\n return $link;\n}\n</code></pre>\n"
}
] |
2015/02/24
|
[
"https://wordpress.stackexchange.com/questions/179209",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68069/"
] |
I tried to find filters or a hook to modify link returned by this function
[`get_post_type_archive_link()`](http://codex.wordpress.org/Function_Reference/get_post_type_archive_link)
I have gone through most of the documentation. I'm not sure it's not there or I'm not able to find it.
Any suggestions would be very appreciated.
|
The filter is `post_type_archive_link`, [defined (WP 4.1.1) on line 1112 of file wp-includes/link-template.php](https://core.trac.wordpress.org/browser/tags/4.1.1/src/wp-includes/link-template.php#L1112):
```
apply_filters( 'post_type_archive_link', $link, $post_type );
```
And the use:
```
add_filter( 'post_type_archive_link', function( $link, $post_type ) {
//Do something
return $link;
}, 10, 2 );
```
|
179,263 |
<p>I know that normal WP_Query's can have an <code>"orderby"</code> parameter of <code>"meta_value_num"</code>, but when I try to user <code>"orderby" => "meta_value_num"</code> on a WP_User_Query, it doesn't seem to work. Anyway I can obtain this functionality or is there something I'm missing?</p>
<p>Edit:</p>
<p>Here's what I've tried to retrieve results ordered by numeric meta values:</p>
<pre><code>$sorted_users = new WP_User_Query(array(
'orderby' => 'meta_value',
'meta_key' => 'satisfaction_rating',
'order' => $order,
'role' => 'subscriber',
'meta_query' => array(
array(
'key' => 'satisfaction_rating',
'type' => 'NUMERIC'
)
)
));
</code></pre>
<p>Still doesn't seem to work...</p>
|
[
{
"answer_id": 179265,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": true,
"text": "<p>This is untested, but I believe if you set <code>type</code> in your meta query to <code>numeric</code>, that will cast the values as numbers so orderby <code>meta_value</code> should work correctly.</p>\n"
},
{
"answer_id": 269540,
"author": "Lance Cleveland",
"author_id": 11553,
"author_profile": "https://wordpress.stackexchange.com/users/11553",
"pm_score": 0,
"selected": false,
"text": "<p>In WP_User_Query() you probably want to set orderly to 'meta_value_num' instead of 'meta_value' as well.</p>\n\n<p>This is working with WP 4.7+.</p>\n"
}
] |
2015/02/24
|
[
"https://wordpress.stackexchange.com/questions/179263",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37660/"
] |
I know that normal WP\_Query's can have an `"orderby"` parameter of `"meta_value_num"`, but when I try to user `"orderby" => "meta_value_num"` on a WP\_User\_Query, it doesn't seem to work. Anyway I can obtain this functionality or is there something I'm missing?
Edit:
Here's what I've tried to retrieve results ordered by numeric meta values:
```
$sorted_users = new WP_User_Query(array(
'orderby' => 'meta_value',
'meta_key' => 'satisfaction_rating',
'order' => $order,
'role' => 'subscriber',
'meta_query' => array(
array(
'key' => 'satisfaction_rating',
'type' => 'NUMERIC'
)
)
));
```
Still doesn't seem to work...
|
This is untested, but I believe if you set `type` in your meta query to `numeric`, that will cast the values as numbers so orderby `meta_value` should work correctly.
|
179,279 |
<p>Reading the <a href="https://make.wordpress.org/core/handbook/inline-documentation-standards/php-documentation-standards/" rel="nofollow">WordPress PHP Documentation Standards</a>, I can't see anywhere that mentions how to document a function call such as <code>add_action( 'foo', 'bar' );</code></p>
<p>Should I be documenting function calls and, if so, how?</p>
|
[
{
"answer_id": 179294,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 3,
"selected": true,
"text": "<p>You don't document function calls, but function definitions. Because the function could be called unlimited times, right? So it makes no sense to document functions when they are called. </p>\n\n<p>If you document the call, then probably because you do some things you want to remember later - or let other following developers know. But normally, I would say, that shouldn't happen - in a perfect world.</p>\n\n<p>Now the hook system is somewhat different from normal calls, which might be the reason for the confusion. But actually it isn't, the function <code>add_action()</code> itself is documented, so it is about the hook and the function used. Lets look at your example:</p>\n\n<pre><code>add_action( 'foo', 'bar' );\n</code></pre>\n\n<p>Where <code>foo</code> is the hook and <code>bar</code> is the function. For this you probably have to go at it like @birgire shows it in his answer.</p>\n\n<p>I'm assuming you know how to document the function, you linked the correct document. There you find two sections about documenting hooks too, which does apparently only apply to <code>do_action()</code> and <code>apply_filters()</code>.</p>\n\n<ul>\n<li><a href=\"https://make.wordpress.org/core/handbook/inline-documentation-standards/php-documentation-standards/#4-hooks-actions-and-filters\" rel=\"nofollow\">4. Hooks (Actions and Filters)</a>; example: </li>\n</ul>\n\n<pre>\n /**\n * Summary.\n *\n * Description.\n *\n * @since x.x.x\n *\n * @param type $var Description.\n * @param array $args {\n * Short description about this hash.\n *\n * @type type $var Description.\n * @type type $var Description.\n * }\n * @param type $var Description.\n */\n</pre>\n\n<ul>\n<li><a href=\"https://make.wordpress.org/core/handbook/inline-documentation-standards/php-documentation-standards/#4-1-duplicate-hooks\" rel=\"nofollow\">4.1 Duplicate Hooks</a>; example: </li>\n</ul>\n\n<pre>\n/** This action is documented in path/to/filename.php */\n</pre>\n\n<p>This is the official part.</p>\n\n<p>Personally like to add something like this:</p>\n\n<pre><code>/**\n * (Here is the official part)\n *\n * @hooked bar - 10\n */\ndo_action( 'foo' );\n</code></pre>\n\n<p>I do this on the finishing touches of a project, because I find it somewhat helpful and informational. I did not come up with that, but don't ask me where it is from, might be from WC. Additionally I'd like to note that it is probably not good practice. The schema here is</p>\n\n<pre><code>@hooked function_name - priority\n</code></pre>\n"
},
{
"answer_id": 179295,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": false,
"text": "<p>If there were a special WordPress core standard, for such function calls, one would expect it to be used in this file:</p>\n\n<pre><code>/wp-includes/default-filters.php\n</code></pre>\n\n<p>the <em>mother of hook setup calls</em>.</p>\n\n<p>Skimming through that file, we see that there is at most a single comment line per function call:</p>\n\n<pre><code>// Slugs\nadd_filter( 'pre_term_slug', 'sanitize_title' );\n</code></pre>\n\n<p>Some calls are grouped under a comment:</p>\n\n<pre><code>// Mime types\nadd_filter( 'pre_post_mime_type', 'sanitize_mime_type' );\nadd_filter( 'post_mime_type', 'sanitize_mime_type' );\n</code></pre>\n\n<p>or even like this:</p>\n\n<pre><code>// Format text area for display.\nforeach ( array( 'term_description' ) as $filter ) { \n add_filter( $filter, 'wptexturize' );\n add_filter( $filter, 'convert_chars' );\n add_filter( $filter, 'wpautop' );\n add_filter( $filter, 'shortcode_unautop');\n}\n</code></pre>\n\n<p>So I would suggest you to do what makes sense for your code and helps make it more readable.</p>\n\n<p>We can also enhance the readability with <em>descriptive</em> callbacks. For example:</p>\n\n<pre><code>// BAD:\nadd_filter( 'the_title', 'wpse_11' );\n\n// BETTER:\nadd_filter( 'the_title', 'wpse_remove_blacklisted_words' );\n</code></pre>\n"
}
] |
2015/02/24
|
[
"https://wordpress.stackexchange.com/questions/179279",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22599/"
] |
Reading the [WordPress PHP Documentation Standards](https://make.wordpress.org/core/handbook/inline-documentation-standards/php-documentation-standards/), I can't see anywhere that mentions how to document a function call such as `add_action( 'foo', 'bar' );`
Should I be documenting function calls and, if so, how?
|
You don't document function calls, but function definitions. Because the function could be called unlimited times, right? So it makes no sense to document functions when they are called.
If you document the call, then probably because you do some things you want to remember later - or let other following developers know. But normally, I would say, that shouldn't happen - in a perfect world.
Now the hook system is somewhat different from normal calls, which might be the reason for the confusion. But actually it isn't, the function `add_action()` itself is documented, so it is about the hook and the function used. Lets look at your example:
```
add_action( 'foo', 'bar' );
```
Where `foo` is the hook and `bar` is the function. For this you probably have to go at it like @birgire shows it in his answer.
I'm assuming you know how to document the function, you linked the correct document. There you find two sections about documenting hooks too, which does apparently only apply to `do_action()` and `apply_filters()`.
* [4. Hooks (Actions and Filters)](https://make.wordpress.org/core/handbook/inline-documentation-standards/php-documentation-standards/#4-hooks-actions-and-filters); example:
```
/**
* Summary.
*
* Description.
*
* @since x.x.x
*
* @param type $var Description.
* @param array $args {
* Short description about this hash.
*
* @type type $var Description.
* @type type $var Description.
* }
* @param type $var Description.
*/
```
* [4.1 Duplicate Hooks](https://make.wordpress.org/core/handbook/inline-documentation-standards/php-documentation-standards/#4-1-duplicate-hooks); example:
```
/** This action is documented in path/to/filename.php */
```
This is the official part.
Personally like to add something like this:
```
/**
* (Here is the official part)
*
* @hooked bar - 10
*/
do_action( 'foo' );
```
I do this on the finishing touches of a project, because I find it somewhat helpful and informational. I did not come up with that, but don't ask me where it is from, might be from WC. Additionally I'd like to note that it is probably not good practice. The schema here is
```
@hooked function_name - priority
```
|
179,285 |
<p>I have a table, where each post has a custom field with "region" and "city":</p>
<ul>
<li>01 > SP > São Paulo</li>
<li>02 > RJ > Rio de Janeiro</li>
<li>03 > SP > Campinas</li>
<li>04 > RJ > Niteroi</li>
</ul>
<p>This query is working perfect for showing all posts in "Region = SP":</p>
<pre><code>query_posts( array(
'post_type' => 'hotel',
'post_per_page' => '500',
'meta_key' => 'hotel-region',
'meta_value' => "sp")
);
</code></pre>
<ul>
<li>01 > SP > São Paulo</li>
<li>03 > SP > Campinas</li>
</ul>
<p>Now I need to order the query results for city A > Z. How can I change the code for this?</p>
|
[
{
"answer_id": 179290,
"author": "Przemek Maczewski",
"author_id": 68013,
"author_profile": "https://wordpress.stackexchange.com/users/68013",
"pm_score": 0,
"selected": false,
"text": "<p>You might try this but using query_posts() is strongly discouraged:</p>\n\n<pre><code>query_posts(\n array( \n 'post_type' => 'hotel',\n 'post_per_page' => '500',\n 'order' => 'ASC',\n 'meta_key' => 'hotel-city',\n 'orderby' => 'meta_value',\n 'meta_query' => array(\n array('key' => 'hotel-region',\n 'value' => 'sp' \n )\n )\n )\n);\n</code></pre>\n\n<p>As cybmeta pointed, <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">use WP_Query</a> instead.</p>\n"
},
{
"answer_id": 179291,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": true,
"text": "<p>Regions and cities fit perfectly in the concept of taxonomy: a way to group things (i.e. posts). And not so much in the concept of meta data. I strongly recommend to use custom taxonomies for that instead of custom meta fields. You will gain in performance and you will have a better data relationship management. Additionally, <a href=\"https://wordpress.stackexchange.com/questions/1753/when-should-you-use-wp-query-vs-query-posts-vs-get-posts\">you should stop using <code>query_posts</code> and use <code>WP_Query</code> instead</a>.</p>\n\n<p>That being said, if you still want to use meta fields, you can sort the query by meta value as as follow:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'hotel',\n 'post_per_page' => '500',\n //meta_key set for sorting only, for meta conditionals we will use meta_query parameter\n //Asumming the name of the meta field is hotel-city, replace with the correct name\n 'meta_key' => 'hotel-city',\n 'orderby' => 'meta_value',\n 'order' => 'ASC',\n 'meta_query' => array(\n array(\n 'key' => 'hotel-region',\n 'value' => 'sp'\n )\n )\n);\n\n$query = new WP_Query( $args );\n</code></pre>\n"
}
] |
2015/02/24
|
[
"https://wordpress.stackexchange.com/questions/179285",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44576/"
] |
I have a table, where each post has a custom field with "region" and "city":
* 01 > SP > São Paulo
* 02 > RJ > Rio de Janeiro
* 03 > SP > Campinas
* 04 > RJ > Niteroi
This query is working perfect for showing all posts in "Region = SP":
```
query_posts( array(
'post_type' => 'hotel',
'post_per_page' => '500',
'meta_key' => 'hotel-region',
'meta_value' => "sp")
);
```
* 01 > SP > São Paulo
* 03 > SP > Campinas
Now I need to order the query results for city A > Z. How can I change the code for this?
|
Regions and cities fit perfectly in the concept of taxonomy: a way to group things (i.e. posts). And not so much in the concept of meta data. I strongly recommend to use custom taxonomies for that instead of custom meta fields. You will gain in performance and you will have a better data relationship management. Additionally, [you should stop using `query_posts` and use `WP_Query` instead](https://wordpress.stackexchange.com/questions/1753/when-should-you-use-wp-query-vs-query-posts-vs-get-posts).
That being said, if you still want to use meta fields, you can sort the query by meta value as as follow:
```
$args = array(
'post_type' => 'hotel',
'post_per_page' => '500',
//meta_key set for sorting only, for meta conditionals we will use meta_query parameter
//Asumming the name of the meta field is hotel-city, replace with the correct name
'meta_key' => 'hotel-city',
'orderby' => 'meta_value',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'hotel-region',
'value' => 'sp'
)
)
);
$query = new WP_Query( $args );
```
|
179,330 |
<p>I am using the following code to hide the teaser and show content only after more tag in loop:</p>
<pre><code><?php
$after_more = explode(
'<!--more-->',
$post->post_content
);
if( $after_more[1] ) {
echo $after_more[1];
} else {
echo $after_more[0];
}
?>
</code></pre>
<p>Is there anyway to show only first 50 words instead of entire post content? I want to hide teaser and show 50 words after tag. </p>
|
[
{
"answer_id": 179324,
"author": "rootx",
"author_id": 68133,
"author_profile": "https://wordpress.stackexchange.com/users/68133",
"pm_score": -1,
"selected": false,
"text": "<p>Use site like wpthemedetector.com to detect which theme that site is using or visit that site and press ctrl+u to view its source code you will get a theme css file.In the top of the css file there would be comment about theme.</p>\n"
},
{
"answer_id": 179327,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>In general it is impossible, and probably pointless as well. It is not enough to know which theme is being used but you will also need to know its configuration and then what about different versions, local changes or even server settings (ok, this probably only in rare cases).</p>\n\n<p>The best way to know what theme is used on a specific site is to ask the owner of the site. If it saves you half development time then you might consider even paying for the info. </p>\n"
},
{
"answer_id": 271732,
"author": "Andrii Shekhirev",
"author_id": 122807,
"author_profile": "https://wordpress.stackexchange.com/users/122807",
"pm_score": 0,
"selected": false,
"text": "<p>As Mark and others pointed out, automatic theme detectors like <a href=\"http://satoristudio.net/what-wordpress-theme/\" rel=\"nofollow noreferrer\">SatoriThemeDetector</a> or <a href=\"http://whatwpthemeisthat.com/\" rel=\"nofollow noreferrer\">WhatWPThemeIsThat</a> will not help if the developer has removed all css file headings and altered the theme folder names. </p>\n\n<p>There's still something you can try in such situation, even though <strong>it's a moonshot of sorts (no guarantee of success) and requires some detective work</strong>: </p>\n\n<ul>\n<li>Open .css or .js files which are enqueued by the active theme, look\nfor pieces of code (or even comments) that are non-generic, and try\npasting some into Google. If the original theme is an open-source\ntheme (e.g. hosted on WordPress.org), there's a chance you will get\nsome links to its public repository.</li>\n<li>Look at the HTML code of the website's pages, specifically the names of css classes on common elements - some of them might still contain theme-specific prefixes</li>\n<li>Put together a list of all scripts and stylesheets enqueued by the theme: they might help you at least get an overall picture of the complexity of the theme being used and the additional libraries/plugins it's bundled with, which in turn can help narrow down the search criteria.</li>\n</ul>\n"
}
] |
2015/02/25
|
[
"https://wordpress.stackexchange.com/questions/179330",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13058/"
] |
I am using the following code to hide the teaser and show content only after more tag in loop:
```
<?php
$after_more = explode(
'<!--more-->',
$post->post_content
);
if( $after_more[1] ) {
echo $after_more[1];
} else {
echo $after_more[0];
}
?>
```
Is there anyway to show only first 50 words instead of entire post content? I want to hide teaser and show 50 words after tag.
|
In general it is impossible, and probably pointless as well. It is not enough to know which theme is being used but you will also need to know its configuration and then what about different versions, local changes or even server settings (ok, this probably only in rare cases).
The best way to know what theme is used on a specific site is to ask the owner of the site. If it saves you half development time then you might consider even paying for the info.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.