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
|
---|---|---|---|---|---|---|
215,802 |
<p>I'm looking for the location of a product's prices according to the option which the user selects in the product price. For example, <a href="http://sakala.ir/product/bundle-cashmere-3" rel="noreferrer">this WooCommerce shop</a> has a select which prices change according to the user selection.</p>
<p>I want to know where are prices for different options stored in DB.</p>
<p>Thanks</p>
|
[
{
"answer_id": 222468,
"author": "LoicTheAztec",
"author_id": 79855,
"author_profile": "https://wordpress.stackexchange.com/users/79855",
"pm_score": 4,
"selected": false,
"text": "<p>All the data like different <strong>prices</strong> of a product custom post type are store <em>(for each product)</em> in <strong>postmeta table</strong>. </p>\n\n<p>To find the <strong>post id</strong> of all products you have to use this query on <strong>posts table</strong>:<br></p>\n\n<pre><code>SELECT * FROM 'posts' WHERE 'post_type' = 'product'\n</code></pre>\n\n<p>For each <strong>product id</strong> (<code>post_id</code>), you can retrieve all related data with this query on <strong>postmeta table</strong>:</p>\n\n<pre><code>SELECT * FROM 'postmeta' WHERE 'post_id' = nnnn\n</code></pre>\n\n<p><em>(nnnn is the number id (<code>post_id</code>) of a product)</em><br><br>\nYou will get the list of all product properties <code>metakey</code> and <code>metavalues</code>. <br>\nFor related price <code>meta_key</code>(s) you have, for example:<br>\n- <code>_regular_price</code><br>\n- <code>_sale_price</code><br>\n- <code>_price</code><br>\n- …<br></p>\n\n<p>To get a particular value of a product meta_key, you can use the wordpress function:<br></p>\n\n<p><code>get_post_meta($post_id, '$meta_key');</code></p>\n"
},
{
"answer_id": 267162,
"author": "Marcel Lange",
"author_id": 119865,
"author_profile": "https://wordpress.stackexchange.com/users/119865",
"pm_score": 2,
"selected": false,
"text": "<p>As LoicTheAztec told, the product data lives in the posts and postmeta tables. Here is a query, I used to get the prices in my environment (WC Role Based Price installed)</p>\n\n<pre><code>SELECT\n wpp.ID,\n wppm.meta_key AS FIELD,\n wppm.meta_value AS VALUE,\n wppm.*\nFROM wp_posts AS wpp\n LEFT JOIN wp_postmeta AS wppm\n ON wpp.ID = wppm.post_id\nWHERE wpp.post_type = 'product'\n AND (wppm.meta_key = '_regular_price'\n OR wppm.meta_key = '_sale_price'\n OR wppm.meta_key = '_price' \n OR wppm.meta_key = '_product_attributes')\nORDER BY wpp.ID ASC, FIELD ASC, wppm.meta_id DESC;\n</code></pre>\n\n<p>Perhaps this is helpful. </p>\n"
},
{
"answer_id": 285609,
"author": "Umair Idrees",
"author_id": 130710,
"author_profile": "https://wordpress.stackexchange.com/users/130710",
"pm_score": 1,
"selected": false,
"text": "<p>Ηere are three meta_keys in <strong>postmeta</strong> table.</p>\n\n<pre><code>[ _sale_price, _regular_price, _price ]\n</code></pre>\n\n<p>First array contains value and second array contains WHERE condition. You can add more conditions.</p>\n\n<p>You can update values using the following code.</p>\n\n<pre><code>//update _price\n$wpdb->update( \n $wpdb->postmeta, \n array( 'meta_value' => $default_product_price ), \n array( 'meta_key' => '_price' )\n);\n//update _regular_price\n$wpdb->update( \n $wpdb->postmeta, \n array( 'meta_value' => $default_product_price ), \n array( 'meta_key' => '_regular_price' )\n);\n//update _price\n$wpdb->update( \n $wpdb->postmeta, \n array( 'meta_value' => $default_sale_price ), \n array( 'meta_key' => '_sale_price' )\n);\n</code></pre>\n"
},
{
"answer_id": 325353,
"author": "Albert S.",
"author_id": 142181,
"author_profile": "https://wordpress.stackexchange.com/users/142181",
"pm_score": 0,
"selected": false,
"text": "<p>This prints product title and it's price.</p>\n\n<pre><code> SELECT distinct p.id, p.post_title,pm.meta_key, pm.meta_value \n FROM {db_prefix}_postmeta pm \ninner join {db_prefix}_posts p on p.id= pm.post_id\nWHERE pm.meta_key = '_sale_price'\n</code></pre>\n"
}
] |
2016/01/27
|
[
"https://wordpress.stackexchange.com/questions/215802",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87566/"
] |
I'm looking for the location of a product's prices according to the option which the user selects in the product price. For example, [this WooCommerce shop](http://sakala.ir/product/bundle-cashmere-3) has a select which prices change according to the user selection.
I want to know where are prices for different options stored in DB.
Thanks
|
All the data like different **prices** of a product custom post type are store *(for each product)* in **postmeta table**.
To find the **post id** of all products you have to use this query on **posts table**:
```
SELECT * FROM 'posts' WHERE 'post_type' = 'product'
```
For each **product id** (`post_id`), you can retrieve all related data with this query on **postmeta table**:
```
SELECT * FROM 'postmeta' WHERE 'post_id' = nnnn
```
*(nnnn is the number id (`post_id`) of a product)*
You will get the list of all product properties `metakey` and `metavalues`.
For related price `meta_key`(s) you have, for example:
- `_regular_price`
- `_sale_price`
- `_price`
- …
To get a particular value of a product meta\_key, you can use the wordpress function:
`get_post_meta($post_id, '$meta_key');`
|
215,813 |
<p>I haven't done anything to my clients site but add some more text to a testimonials page, updated it & then went to go see the page and it's been all smashed together! It's using randomly placed tags instead. I'm starting to pull my hair out as I've tried everything I can think of:</p>
<ul>
<li>Updated wordpress to the most recent update</li>
<li>Updated all my plugins</li>
<li>Deactivated my plugins</li>
<li>Activated another theme (this is where the line breaks come back but I'm not sure why it's randomly acting like this?)</li>
<li><p>Checked my functions.php file for my theme and had removed these lines of code in hopes that it would be solved </p>
<pre><code> // http://tinymce.moxiecode.com/wiki.php/Configuration
function cbnet_tinymce_config( $init ) {
// Don't remove line breaks
$init['remove_linebreaks'] = false;
// Pass $init back to WordPress
return $init;
}
add_filter('tiny_mce_before_init', 'cbnet_tinymce_config');
// Convert newline characters to BR tags
$init['convert_newlines_to_brs'] = true;
// Do not remove redundant BR tags
$init['remove_redundant_brs'] = false;
</code></pre></li>
</ul>
<p>I have since disabled Tiny MCE just incase too</p>
<p>The page in question
<a href="https://i.stack.imgur.com/Xszo4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xszo4.jpg" alt="enter image description here"></a></p>
<p>I have absolutely no clue what is going on and I've never run into this before. Any help is appreciated, I'm loosing more hair by the minute. </p>
<h3>UPDATED</h3>
<p>I've looked to be sure my older custom theme has a page.php file. Inside it only contain a bit of code:</p>
<pre><code><?php get_header(); ?>
<div id="main">
<?php while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
</code></pre>
|
[
{
"answer_id": 215832,
"author": "vlood",
"author_id": 733,
"author_profile": "https://wordpress.stackexchange.com/users/733",
"pm_score": 0,
"selected": false,
"text": "<p>You should look at your page.php template file if the theme has it and if not - then look for index.php.</p>\n\n<p>Possible reasons are usage of filters for the content that strip all html tags or directly doing this to the output of get_the_content() function.</p>\n\n<p>Are you completely sure it's theme's fault and not any of the plugin you got active?</p>\n"
},
{
"answer_id": 216124,
"author": "kia4567",
"author_id": 25108,
"author_profile": "https://wordpress.stackexchange.com/users/25108",
"pm_score": 2,
"selected": true,
"text": "<p>After taking my older custom theme files over to my computer via FTP I was then able to really dive into what might the problem be. </p>\n\n<p>I put up a maintenance page on my website and worked on where the problem might be coming from, steps to find the culprit code were as follows:</p>\n\n<ul>\n<li>Deactivate all plugins and then check out the page in question (for me this was not the issue I was looking for)</li>\n<li>I then created a new page in my wordpress dashboard and added content, saved and check the page out - my page was still a run on sentence (meaning every page was being affected and not just the one I was trying to edit) </li>\n<li>I deactivated my custom theme and checked out my page in question with twentytwelve activated. Paragraph breaks were present. So it has to do with my theme. I then activated my theme again to diagnose.</li>\n<li>I then have to play around with my custom theme templates to be sure I hadn't taken or added a snippet in there that was affecting my pages. I did this by downloading a new wordpress and moved page.php and index.php to my website theme files. Of course there were some changes to the pages then but I STILL have a run on text on my page in question</li>\n<li>Last but not least, I decided to work on my themes functions.php file. First I deleted the file from the server through ftp (because we already have a backup on on our computer) and checked out my page in question. It works! So now, it's time to figure out where in my functions.pgp file the culprit is. I had deleted the top half of the file and uploaded it again, refreshed the page and found out that the code that was causing the issue lays at the bottom half. So from there it was going through each function on the bottom half of my functions.php file until I found the line. </li>\n</ul>\n\n<p>And here it is: <code>remove_filter ('the_content', 'wpautop');</code></p>\n\n<p>For some reason when I was first working on this theme (back in 2011) I had placed this line of code in my functions.php. <a href=\"https://codex.wordpress.org/Function_Reference/wpautop\" rel=\"nofollow\">Here is what it does</a>. It was basically stripping out any <code><br> & <p></code>! </p>\n\n<p>I have since learned while I'm creating my own themes to be sure I organize my files & make comments in my styles.css and function.php files.</p>\n\n<p>This may not be the exact same case for anyone else comign across this problem but the steps to diagnose an issue liek this may be helpful. </p>\n\n<p>Another testing step I was going to be doing if the update with the functions file didn't work was to rename my .htaccess file to see if there was something in there that might be blocking or disrupting my directory.</p>\n\n<p>I hope this ends up helping others!</p>\n\n<p>Important: Make sure you always have a backup of your database and your wordpress files. You can do this <a href=\"http://makeaweblog.com/backup-wordpress-files-and-database/\" rel=\"nofollow\">manually</a> or with a trusted wordpress backup plugin. I use BackupBuddy and it's worth every penny!</p>\n"
}
] |
2016/01/27
|
[
"https://wordpress.stackexchange.com/questions/215813",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25108/"
] |
I haven't done anything to my clients site but add some more text to a testimonials page, updated it & then went to go see the page and it's been all smashed together! It's using randomly placed tags instead. I'm starting to pull my hair out as I've tried everything I can think of:
* Updated wordpress to the most recent update
* Updated all my plugins
* Deactivated my plugins
* Activated another theme (this is where the line breaks come back but I'm not sure why it's randomly acting like this?)
* Checked my functions.php file for my theme and had removed these lines of code in hopes that it would be solved
```
// http://tinymce.moxiecode.com/wiki.php/Configuration
function cbnet_tinymce_config( $init ) {
// Don't remove line breaks
$init['remove_linebreaks'] = false;
// Pass $init back to WordPress
return $init;
}
add_filter('tiny_mce_before_init', 'cbnet_tinymce_config');
// Convert newline characters to BR tags
$init['convert_newlines_to_brs'] = true;
// Do not remove redundant BR tags
$init['remove_redundant_brs'] = false;
```
I have since disabled Tiny MCE just incase too
The page in question
[](https://i.stack.imgur.com/Xszo4.jpg)
I have absolutely no clue what is going on and I've never run into this before. Any help is appreciated, I'm loosing more hair by the minute.
### UPDATED
I've looked to be sure my older custom theme has a page.php file. Inside it only contain a bit of code:
```
<?php get_header(); ?>
<div id="main">
<?php while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
```
|
After taking my older custom theme files over to my computer via FTP I was then able to really dive into what might the problem be.
I put up a maintenance page on my website and worked on where the problem might be coming from, steps to find the culprit code were as follows:
* Deactivate all plugins and then check out the page in question (for me this was not the issue I was looking for)
* I then created a new page in my wordpress dashboard and added content, saved and check the page out - my page was still a run on sentence (meaning every page was being affected and not just the one I was trying to edit)
* I deactivated my custom theme and checked out my page in question with twentytwelve activated. Paragraph breaks were present. So it has to do with my theme. I then activated my theme again to diagnose.
* I then have to play around with my custom theme templates to be sure I hadn't taken or added a snippet in there that was affecting my pages. I did this by downloading a new wordpress and moved page.php and index.php to my website theme files. Of course there were some changes to the pages then but I STILL have a run on text on my page in question
* Last but not least, I decided to work on my themes functions.php file. First I deleted the file from the server through ftp (because we already have a backup on on our computer) and checked out my page in question. It works! So now, it's time to figure out where in my functions.pgp file the culprit is. I had deleted the top half of the file and uploaded it again, refreshed the page and found out that the code that was causing the issue lays at the bottom half. So from there it was going through each function on the bottom half of my functions.php file until I found the line.
And here it is: `remove_filter ('the_content', 'wpautop');`
For some reason when I was first working on this theme (back in 2011) I had placed this line of code in my functions.php. [Here is what it does](https://codex.wordpress.org/Function_Reference/wpautop). It was basically stripping out any `<br> & <p>`!
I have since learned while I'm creating my own themes to be sure I organize my files & make comments in my styles.css and function.php files.
This may not be the exact same case for anyone else comign across this problem but the steps to diagnose an issue liek this may be helpful.
Another testing step I was going to be doing if the update with the functions file didn't work was to rename my .htaccess file to see if there was something in there that might be blocking or disrupting my directory.
I hope this ends up helping others!
Important: Make sure you always have a backup of your database and your wordpress files. You can do this [manually](http://makeaweblog.com/backup-wordpress-files-and-database/) or with a trusted wordpress backup plugin. I use BackupBuddy and it's worth every penny!
|
215,822 |
<p>Should one filter the output of builtin WP functions such as <code>get_permalink()</code> and well-known WP plugins such as ACF (Advanced Custom Fields) such as <code>get_field()</code>?</p>
<p>For instance <code>get_permalink()</code> calls <code>home_url()</code> which calls <code>get_home_url()</code>, <strong>none of which do any filtering of the data</strong>. In a similar fashion work <code>the_content()</code>, <code>the_title()</code> and the rest of the familiar Loop-related functions.</p>
<p>Therefore, is the following sufficient? (<em>no <code>esc_attr()</code> for WP and ACF functions</em>)</p>
<pre><code><?php while ($wp_query->have_posts() && __return_true($wp_query->the_post()) ) : ?>
<a href="<?=get_the_permalink()?>">
<img src="<?=get_field('homepage_thumbnail')['sizes']['thumbnail']?>" />
</a>
<?php endwhile; ?>
</code></pre>
<p>Or should I be more careful with the data coming from the plugin? (<em>notice <code>esc_attr()</code> added to ACF image source, third line</em>)</p>
<pre><code><?php while ($wp_query->have_posts() && __return_true($wp_query->the_post()) ) : ?>
<a href="<?=get_the_permalink()?>">
<img src="<?=esc_attr(get_field('homepage_thumbnail')['sizes']['thumbnail']?>)" />
</a>
<?php endwhile; ?>
</code></pre>
<p>Or should I be super careful even with the stock WP functions? (<em>notice <code>esc_attr()</code> added to WP anchor href, second line</em>)</p>
<pre><code><?php while ($wp_query->have_posts() && __return_true($wp_query->the_post()) ) : ?>
<a href="<?=esc_attr(get_the_permalink())?>">
<img src="<?=esc_attr(get_field('homepage_thumbnail')['sizes']['thumbnail']?>)" />
</a>
<?php endwhile; ?>
</code></pre>
|
[
{
"answer_id": 215826,
"author": "RRikesh",
"author_id": 17305,
"author_profile": "https://wordpress.stackexchange.com/users/17305",
"pm_score": 2,
"selected": false,
"text": "<p>You should always escape your data, whatever its origin. For your example, the URLs should be escaped using <a href=\"https://codex.wordpress.org/Function_Reference/esc_url\" rel=\"nofollow\"><code>esc_url()</code></a>. </p>\n\n<p>WordPress has many functions which can be used. There's an article on <a href=\"https://codex.wordpress.org/Data_Validation\" rel=\"nofollow\">Data validation</a> on the Codex which lists the various functions available.</p>\n"
},
{
"answer_id": 215838,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": true,
"text": "<p>Escaping is used to produce valid HTML or other formats, and it depends on context. </p>\n\n<p>Escaping a url in something like <code><a href=\"<?php echo $url?>\"....</code> is needed in order to replace any \"&\" characters with & (although browsers will most likely fix it for you if you don't do it).</p>\n\n<p>Escaping a url in an input element like <code><input value=\"<?php echo $url?>\"...</code>do not require replacement of \"&\" but do require replacement of any quote character.</p>\n\n<p>So in general, since escaping is context sensitive you can assume that wordpress API will not escape it for you. What plugins do, is up to the plugin itself.</p>\n"
}
] |
2016/01/27
|
[
"https://wordpress.stackexchange.com/questions/215822",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34330/"
] |
Should one filter the output of builtin WP functions such as `get_permalink()` and well-known WP plugins such as ACF (Advanced Custom Fields) such as `get_field()`?
For instance `get_permalink()` calls `home_url()` which calls `get_home_url()`, **none of which do any filtering of the data**. In a similar fashion work `the_content()`, `the_title()` and the rest of the familiar Loop-related functions.
Therefore, is the following sufficient? (*no `esc_attr()` for WP and ACF functions*)
```
<?php while ($wp_query->have_posts() && __return_true($wp_query->the_post()) ) : ?>
<a href="<?=get_the_permalink()?>">
<img src="<?=get_field('homepage_thumbnail')['sizes']['thumbnail']?>" />
</a>
<?php endwhile; ?>
```
Or should I be more careful with the data coming from the plugin? (*notice `esc_attr()` added to ACF image source, third line*)
```
<?php while ($wp_query->have_posts() && __return_true($wp_query->the_post()) ) : ?>
<a href="<?=get_the_permalink()?>">
<img src="<?=esc_attr(get_field('homepage_thumbnail')['sizes']['thumbnail']?>)" />
</a>
<?php endwhile; ?>
```
Or should I be super careful even with the stock WP functions? (*notice `esc_attr()` added to WP anchor href, second line*)
```
<?php while ($wp_query->have_posts() && __return_true($wp_query->the_post()) ) : ?>
<a href="<?=esc_attr(get_the_permalink())?>">
<img src="<?=esc_attr(get_field('homepage_thumbnail')['sizes']['thumbnail']?>)" />
</a>
<?php endwhile; ?>
```
|
Escaping is used to produce valid HTML or other formats, and it depends on context.
Escaping a url in something like `<a href="<?php echo $url?>"....` is needed in order to replace any "&" characters with & (although browsers will most likely fix it for you if you don't do it).
Escaping a url in an input element like `<input value="<?php echo $url?>"...`do not require replacement of "&" but do require replacement of any quote character.
So in general, since escaping is context sensitive you can assume that wordpress API will not escape it for you. What plugins do, is up to the plugin itself.
|
215,841 |
<p>I'm running the following query trying to get the data and associated meta data of a huge number of posts:</p>
<pre><code>SELECT wp_posts.post_title, wp_posts.post_date,
wp_posts.ID, wp_postmeta.post_id, wp_postmeta.meta_key
FROM wp_postmeta
INNER JOIN wp_posts
ON wp_postmeta.post_id=wp_posts.id
WHERE wp_posts.post_status = 'publish'
LIMIT 5
</code></pre>
<p>And that returns the following:</p>
<pre><code>Array
(
[0] => stdClass Object
(
[post_title] => Hello world!
[post_date] => 2015-11-11 08:44:54
[ID] => 1
[post_id] => 1
[meta_key] => _edit_lock
)
[1] => stdClass Object
(
[post_title] => Home
[post_date] => 2015-11-11 08:44:54
[ID] => 2
[post_id] => 2
[meta_key] => _wp_page_template
)
[2] => stdClass Object
(
[post_title] => Home
[post_date] => 2015-11-11 08:44:54
[ID] => 2
[post_id] => 2
[meta_key] => _edit_last
)
...
</code></pre>
<p>But now I realise I need a much more complex query, as what I'd like is something like the following:</p>
<pre><code>Array
(
[0] => stdClass Object
(
[post_title] => Hello world!
[post_date] => 2015-11-11 08:44:54
[ID] => 1
[post_id] => 1
[meta] => array(
'_wp_page_template' => 'home.php',
'_edit_last' => 2015-11-11 08:44:54,
)
)
[1] => stdClass Object
(
[post_title] => Home
[post_date] => 2015-11-11 08:44:54
[ID] => 2
[post_id] => 2
[meta] => array(
'_wp_page_template' => 'home.php',
'_edit_last' => 2015-11-11 08:44:54,
)
)
[2] => stdClass Object
(
[post_title] => About us
[post_date] => 2015-11-11 08:44:54
[ID] => 3
[post_id] => 3
[meta] => array(
'_wp_page_template' => 'home.php',
'_edit_last' => 2015-11-11 08:44:54,
)
)
</code></pre>
|
[
{
"answer_id": 215833,
"author": "vlood",
"author_id": 733,
"author_profile": "https://wordpress.stackexchange.com/users/733",
"pm_score": 0,
"selected": false,
"text": "<p>If you have some application-layer security going on (a plugin or something) it could be dropping any requests it finds weird (like from localhost), thus ending with lack of response.</p>\n\n<p>It could be something completely different, but this is what comes to my mind first for your case.</p>\n"
},
{
"answer_id": 215835,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>Since wordpress's execution logic relies on parameters filled by the php-apache connector (mod_php) running a php command line is not guarantied to produce the same results or any at all, all depending on your local settings.</p>\n\n<p>In any case, you should not check if your server is functioning from the server itself as there other web servers and network layer that can fail and you will not check them that way.</p>\n"
}
] |
2016/01/27
|
[
"https://wordpress.stackexchange.com/questions/215841",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27866/"
] |
I'm running the following query trying to get the data and associated meta data of a huge number of posts:
```
SELECT wp_posts.post_title, wp_posts.post_date,
wp_posts.ID, wp_postmeta.post_id, wp_postmeta.meta_key
FROM wp_postmeta
INNER JOIN wp_posts
ON wp_postmeta.post_id=wp_posts.id
WHERE wp_posts.post_status = 'publish'
LIMIT 5
```
And that returns the following:
```
Array
(
[0] => stdClass Object
(
[post_title] => Hello world!
[post_date] => 2015-11-11 08:44:54
[ID] => 1
[post_id] => 1
[meta_key] => _edit_lock
)
[1] => stdClass Object
(
[post_title] => Home
[post_date] => 2015-11-11 08:44:54
[ID] => 2
[post_id] => 2
[meta_key] => _wp_page_template
)
[2] => stdClass Object
(
[post_title] => Home
[post_date] => 2015-11-11 08:44:54
[ID] => 2
[post_id] => 2
[meta_key] => _edit_last
)
...
```
But now I realise I need a much more complex query, as what I'd like is something like the following:
```
Array
(
[0] => stdClass Object
(
[post_title] => Hello world!
[post_date] => 2015-11-11 08:44:54
[ID] => 1
[post_id] => 1
[meta] => array(
'_wp_page_template' => 'home.php',
'_edit_last' => 2015-11-11 08:44:54,
)
)
[1] => stdClass Object
(
[post_title] => Home
[post_date] => 2015-11-11 08:44:54
[ID] => 2
[post_id] => 2
[meta] => array(
'_wp_page_template' => 'home.php',
'_edit_last' => 2015-11-11 08:44:54,
)
)
[2] => stdClass Object
(
[post_title] => About us
[post_date] => 2015-11-11 08:44:54
[ID] => 3
[post_id] => 3
[meta] => array(
'_wp_page_template' => 'home.php',
'_edit_last' => 2015-11-11 08:44:54,
)
)
```
|
Since wordpress's execution logic relies on parameters filled by the php-apache connector (mod\_php) running a php command line is not guarantied to produce the same results or any at all, all depending on your local settings.
In any case, you should not check if your server is functioning from the server itself as there other web servers and network layer that can fail and you will not check them that way.
|
215,847 |
<p>I'm trying to add some text after a product description in WooCommerce which uses the <code>$post->post_excerpt</code>. Currently I'm using the following code:</p>
<pre><code>add_action( 'woocommerce_single_product_summary', 'd4tw_show_dimensions', 20 );
function d4tw_show_dimensions() {
global $product;
$dimensions = $product->get_dimensions();
if ( ! empty( $dimensions ) ) {
echo '<span class="dimensions"> Length: ' . $dimensions . '</span>';
}
}
</code></pre>
<p>This gets the dimensions to show up after the product summary but it's on it's own line. How can I append the dimensions within the same paragraph to the post_excerpt?</p>
|
[
{
"answer_id": 215866,
"author": "Peyman Mohamadpour",
"author_id": 75020,
"author_profile": "https://wordpress.stackexchange.com/users/75020",
"pm_score": 1,
"selected": false,
"text": "<p>you may get the <code>excerpt</code> using:</p>\n\n<pre><code>$excerpt = get_the_excerpt();\n</code></pre>\n\n<p>and append or prepend it as you wish</p>\n"
},
{
"answer_id": 215947,
"author": "Mike Oberdick",
"author_id": 84806,
"author_profile": "https://wordpress.stackexchange.com/users/84806",
"pm_score": 0,
"selected": false,
"text": "<p>I ended up just setting the paragraph to display:inline-block which allowed the product dimensions to flow up onto that line.</p>\n"
}
] |
2016/01/27
|
[
"https://wordpress.stackexchange.com/questions/215847",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84806/"
] |
I'm trying to add some text after a product description in WooCommerce which uses the `$post->post_excerpt`. Currently I'm using the following code:
```
add_action( 'woocommerce_single_product_summary', 'd4tw_show_dimensions', 20 );
function d4tw_show_dimensions() {
global $product;
$dimensions = $product->get_dimensions();
if ( ! empty( $dimensions ) ) {
echo '<span class="dimensions"> Length: ' . $dimensions . '</span>';
}
}
```
This gets the dimensions to show up after the product summary but it's on it's own line. How can I append the dimensions within the same paragraph to the post\_excerpt?
|
you may get the `excerpt` using:
```
$excerpt = get_the_excerpt();
```
and append or prepend it as you wish
|
215,850 |
<p>I need to create a custom role that is only able to edit and publish his own page (page created by admin and afterwards assigned to the user with the custom role).</p>
<p>I have successfully created the new role, and the user under that role is able to edit his own page and publish it, but it still has too much "power" inside the panel. The role has access to comments, post creation, page creation, tools, and to the plugin Timeline Express. I've compared to the contributor panel, and the last item (the plugin Timeline Express) is not shown on this role.</p>
<p>I spent some time reading through WordPress documentation and web forums in order to achieve what I'm trying to do, but I'm still no closer than I was. I know there are plugins that would give me this functionality but I need a simple thing, and I believe there's no need to, "Buy a Ferrari to cross the street".</p>
<p>I'm doing these changes on child theme's <code>functions.php</code>: </p>
<pre><code>remove_role( 'Supervisor');
$result = add_role(
'Supervisor',
__( 'Supervisor' ),
array(
'read' => true,
'edit_pages' => true,
'publish_pages' => true,
'edit_published_pages' => true,
'create_pages' => false,
)
);
</code></pre>
<p>Could you please take a look and help me?</p>
|
[
{
"answer_id": 216081,
"author": "Vasim Shaikh",
"author_id": 87704,
"author_profile": "https://wordpress.stackexchange.com/users/87704",
"pm_score": -1,
"selected": false,
"text": "<p>Yes,i am not getting you very well this may helpful.</p>\n\n<p><a href=\"http://easywebdesigntutorials.com/creating-a-custom-user-role/\" rel=\"nofollow\">http://easywebdesigntutorials.com/creating-a-custom-user-role/</a></p>\n"
},
{
"answer_id": 217509,
"author": "Janica",
"author_id": 87588,
"author_profile": "https://wordpress.stackexchange.com/users/87588",
"pm_score": 0,
"selected": false,
"text": "<p>I've managed to solve this with a little bit of \"patching\" and thanks to the explanation on both these threads: <a href=\"https://wordpress.stackexchange.com/questions/142517/remove-ability-to-access-certain-admin-menus\">Remove ability to access certain admin menus</a> & <a href=\"https://wordpress.stackexchange.com/questions/9505/hide-admin-menus-per-role-in-wordpress\">Hide Admin menus per role in Wordpress</a></p>\n\n<p>I added to the restrict_menus function the items which access I needed forbidden, and hid in the remove_menus the list items I was able to.\nI've also enqueue an admin stylesheet to be launched when this role was active and with that hide the plugin items that were showing.</p>\n\n<p>this is my final code now:</p>\n\n<pre><code>//remove_role( 'Supervisor'); // developing purposes only\n\n$result = add_role( 'Supervisor', \n__('Supervisor' ),\n array( \n\n 'read' => true,\n 'create_posts' => false,\n 'create_pages' => false,\n 'moderate_comments' => false,\n 'edit_pages' => true, \n 'publish_pages' => true,\n 'edit_published_pages' => true,\n) \n);\n\nfunction restrict_menus(){\n\n$author = wp_get_current_user();\n if(isset($author->roles[0])){ \n $current_role = $author->roles[0];\n}else{\n$current_role = 'no_role';\n}\n\nif($current_role == 'Supervisor'){ \n\n$screen = get_current_screen();\n$base = $screen->id;\n\n\nif($base == 'edit-post' || $base == 'tools' || $base == 'edit-comments' || \n$base == 'page' && $action == 'add' || $base == 'te_announcements' && $action == 'add')\n{ \nwp_die('Não tem permissões para aceder a esta área');\n}\n}\n\n}\n\nadd_action( 'current_screen', 'restrict_menus' );\n\nfunction remove_menus()\n{\nglobal $menu;\n\n$author = wp_get_current_user();\nif(isset($author->roles[0])){ \n$current_role = $author->roles[0];\n}else{\n$current_role = 'no_role';\n}\n\nif($current_role == 'Supervisor')\n{\n$restricted = array(__('Comments'),\n __('Appearance'),\n __('Plugins'),\n __('Tools'),\n __('Settings'),\n __('Posts'),\n\n);\nend ($menu);\nwhile (prev($menu)){\n $value = explode(' ',$menu[key($menu)][0]);\n if(in_array($value[0] != NULL?$value[0]:\"\" , $restricted)){unset($menu[key($menu)]);}\n}// end while\n\n}// end if\n}\nadd_action('admin_menu', 'remove_menus');\n</code></pre>\n\n<p>If anybody has a better way, please tell me so.</p>\n"
}
] |
2016/01/27
|
[
"https://wordpress.stackexchange.com/questions/215850",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87588/"
] |
I need to create a custom role that is only able to edit and publish his own page (page created by admin and afterwards assigned to the user with the custom role).
I have successfully created the new role, and the user under that role is able to edit his own page and publish it, but it still has too much "power" inside the panel. The role has access to comments, post creation, page creation, tools, and to the plugin Timeline Express. I've compared to the contributor panel, and the last item (the plugin Timeline Express) is not shown on this role.
I spent some time reading through WordPress documentation and web forums in order to achieve what I'm trying to do, but I'm still no closer than I was. I know there are plugins that would give me this functionality but I need a simple thing, and I believe there's no need to, "Buy a Ferrari to cross the street".
I'm doing these changes on child theme's `functions.php`:
```
remove_role( 'Supervisor');
$result = add_role(
'Supervisor',
__( 'Supervisor' ),
array(
'read' => true,
'edit_pages' => true,
'publish_pages' => true,
'edit_published_pages' => true,
'create_pages' => false,
)
);
```
Could you please take a look and help me?
|
I've managed to solve this with a little bit of "patching" and thanks to the explanation on both these threads: [Remove ability to access certain admin menus](https://wordpress.stackexchange.com/questions/142517/remove-ability-to-access-certain-admin-menus) & [Hide Admin menus per role in Wordpress](https://wordpress.stackexchange.com/questions/9505/hide-admin-menus-per-role-in-wordpress)
I added to the restrict\_menus function the items which access I needed forbidden, and hid in the remove\_menus the list items I was able to.
I've also enqueue an admin stylesheet to be launched when this role was active and with that hide the plugin items that were showing.
this is my final code now:
```
//remove_role( 'Supervisor'); // developing purposes only
$result = add_role( 'Supervisor',
__('Supervisor' ),
array(
'read' => true,
'create_posts' => false,
'create_pages' => false,
'moderate_comments' => false,
'edit_pages' => true,
'publish_pages' => true,
'edit_published_pages' => true,
)
);
function restrict_menus(){
$author = wp_get_current_user();
if(isset($author->roles[0])){
$current_role = $author->roles[0];
}else{
$current_role = 'no_role';
}
if($current_role == 'Supervisor'){
$screen = get_current_screen();
$base = $screen->id;
if($base == 'edit-post' || $base == 'tools' || $base == 'edit-comments' ||
$base == 'page' && $action == 'add' || $base == 'te_announcements' && $action == 'add')
{
wp_die('Não tem permissões para aceder a esta área');
}
}
}
add_action( 'current_screen', 'restrict_menus' );
function remove_menus()
{
global $menu;
$author = wp_get_current_user();
if(isset($author->roles[0])){
$current_role = $author->roles[0];
}else{
$current_role = 'no_role';
}
if($current_role == 'Supervisor')
{
$restricted = array(__('Comments'),
__('Appearance'),
__('Plugins'),
__('Tools'),
__('Settings'),
__('Posts'),
);
end ($menu);
while (prev($menu)){
$value = explode(' ',$menu[key($menu)][0]);
if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
}// end while
}// end if
}
add_action('admin_menu', 'remove_menus');
```
If anybody has a better way, please tell me so.
|
215,871 |
<p>I was reading over some <a href="https://10up.github.io/Engineering-Best-Practices/php/">best practices from 10up</a> and they mention setting these two flags to false in a WP_Query ( depending on what you're querying ):</p>
<ul>
<li><code>'update_post_meta_cache' => false</code>: useful when post meta will not be utilized.</li>
<li><code>'update_post_term_cache' => false</code>: useful when taxonomy terms will not be utilized.</li>
</ul>
<p>I am <em>assuming</em> it utilizing something like <a href="https://codex.wordpress.org/Function_Reference/update_post_caches"><code>update_post_caches()</code></a> but I'm not even 100% sure what that means. Could somebody explain what these two flags mean in a <code>WP_Query</code> and how useful they are? The more information the better as I do not know a whole lot about how WordPress caches things but a well thought out answer regarding these two flags is also acceptable.</p>
|
[
{
"answer_id": 215876,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>The main point of interest here is the <code>update_post_caches</code> function. It is called after WP_Query got all the posts from the DB. Usually, the reason you want the posts in the first place is to display them which usually means to display the terms and something based on the metadata, therefor WP_Query will also by default query the DB for the meta and term data related to the returned posts and stores it the cache*. This information is not explicitly available in the data returned from WP_Query, but when you will call the relevant APIs to get the term and meta info of a specific post, it will already be available in memory and there will be no need to send a new query to the DB. </p>\n\n<p>This enables wordpress to reduce the overhead related to sending requests to the DB by sending only one request to get the information for all of the posts instead of sending a request per each post.</p>\n\n<p>Right now I can not find any non trivial example of when will you not want the cache to update, but a trivial one might be if you just want a list of the titles of all posts. For that you do not need term or meta data.</p>\n\n<p>*cache - Most important here is the memory based cache in which WP stores almot everything which it gets from the DB even without having any object caching plugin active. Obviously when you do have object caching the information will be stored there as well.</p>\n"
},
{
"answer_id": 215881,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 7,
"selected": true,
"text": "<h1>Object cache everywhere</h1>\n\n<p>WordPress tries to reduce the number of database queries as much as possible.</p>\n\n<p>For example, anytime you get a meta field or a taxonomy field, before querying the database, WordPress looks if that that was already queried and stored in cache, and returns it from there instead of querying the database.</p>\n\n<p>The \"cache job\" is done via <a href=\"https://codex.wordpress.org/Class_Reference/WP_Object_Cache\"><code>WP_Object_Cache</code> class and <code>wp_cache_*</code> functions</a> (that are wrapper to that class methods.)</p>\n\n<h1>Where cache lives</h1>\n\n<p>By default, the \"cache\" is nothing more than a PHP global variable. It means that it is in memory, but also means that it vanishes on every request.</p>\n\n<p>However, via dropins (<code>advanced-cache.php</code> and / or <code>object-cache.php</code>), it is possible to setup a custom way to handle this cache.</p>\n\n<p>Usually, this dropins are used to setup some sort of caching mechanism that \"survive\" the singular requests.</p>\n\n<p>For this reason, among WP people, these are know as \"persistent cache\" plugins (even if outside the bubble the words \"cache\" and \"persistent\" don't not make a lot of sense together). </p>\n\n<p>Popular choices nowadays are <a href=\"http://memcached.org/\">Memcached</a> or <a href=\"http://redis.io/\">Redis</a>.</p>\n\n<p>So using \"persistent cache\" plugins you can drastically reduce the number of database queries, because the cache is not updated on every request.</p>\n\n<h1>Some examples</h1>\n\n<pre><code>$foo = get_post_meta('foo', $post_id, true);\n// a lot of code in the middle\n$bar = get_post_meta('bar', $post_id, true);\n</code></pre>\n\n<p>The 2 lines of code above will trigger, at maximum, 1 database query.</p>\n\n<p>In fact, when you query a custom field, all the fields for that post are retrieved from database, cached via object cache, and subsequent requests pull data from cache and not from db.</p>\n\n<p>The same happen for taxonomy terms, WordPress pulls all the terms for a taxonomy once, then returns them from cache.</p>\n\n<p>Object cache is used very widely in WordPress. Not only for posts, meta values and taxonomies, but also for users, comments, theme data...</p>\n\n<h1>What <code>WP_Query</code> has to do with all of this?</h1>\n\n<p>When you query some posts via <code>WP_Query</code>, by default, WordPress not only pulls them from database (or from cache if they are cached) but also <strong>updates the cache for all custom fields and all taxonomies</strong> related to the posts pulled.</p>\n\n<p>So when you call, for example, <code>get_the_terms()</code> or <code>get_post_meta()</code> while looping posts got via <code>WP_Query</code>, you don't actually trigger any database query, but pull information from cache.</p>\n\n<h1>Nice, it isn't?</h1>\n\n<p>Well, yes, but it comes with a cost.</p>\n\n<p>The cache update \"magic\" that WordPress does when pull posts via <code>WP_Query</code> happen in <a href=\"https://developer.wordpress.org/reference/functions/update_meta_cache/\"><code>update_meta_cache</code></a> for meta and in <a href=\"https://developer.wordpress.org/reference/functions/update_object_term_cache/\"><code>update_object_term_cache</code></a> for taxonomies.</p>\n\n<p>If you look at the source code of those functions, you'll see that there WordPress performs just one db query in each function, but also does a lot of processing. For example, in <code>update_object_term_cache</code> there are <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/taxonomy.php#L3581\">7 nested <code>foreach</code></a>... if you have a lot of taxonomies, and the number of posts per page is high, this is not very performant. </p>\n\n<h1>About those <code>WP_Query</code> arguments, finally</h1>\n\n<p>What <code>'update_post_meta_cache'</code> and <code>'update_post_term_cache'</code> do when set to <code>false</code> is to prevent WordPress to update cache for custom fields and taxonomies, respectively.</p>\n\n<p>In that case, the first time a custom field or a taxonomy is queried a database query is triggered, and data are cached.</p>\n\n<h1>It worth the trouble?</h1>\n\n<p>As usual, the answer is <strong>it depends</strong>. Most of the times to set those values to <code>false</code>, is a good choice, because it prevents unnecessary processing and database queries if not needed, and cache is updated anyway the first time custom field / taxonomy terms are required.</p>\n\n<p>However, if you are going to call, even once, <code>get_post_meta()</code> during the loop and you are going to call <code>get_the_terms()</code> for all (or most) of the taxonomies supported by posts, then the cache updating is triggered anyway, and there might be no actual benefit on setting those query arguments to <code>false</code>.</p>\n"
}
] |
2016/01/27
|
[
"https://wordpress.stackexchange.com/questions/215871",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/7355/"
] |
I was reading over some [best practices from 10up](https://10up.github.io/Engineering-Best-Practices/php/) and they mention setting these two flags to false in a WP\_Query ( depending on what you're querying ):
* `'update_post_meta_cache' => false`: useful when post meta will not be utilized.
* `'update_post_term_cache' => false`: useful when taxonomy terms will not be utilized.
I am *assuming* it utilizing something like [`update_post_caches()`](https://codex.wordpress.org/Function_Reference/update_post_caches) but I'm not even 100% sure what that means. Could somebody explain what these two flags mean in a `WP_Query` and how useful they are? The more information the better as I do not know a whole lot about how WordPress caches things but a well thought out answer regarding these two flags is also acceptable.
|
Object cache everywhere
=======================
WordPress tries to reduce the number of database queries as much as possible.
For example, anytime you get a meta field or a taxonomy field, before querying the database, WordPress looks if that that was already queried and stored in cache, and returns it from there instead of querying the database.
The "cache job" is done via [`WP_Object_Cache` class and `wp_cache_*` functions](https://codex.wordpress.org/Class_Reference/WP_Object_Cache) (that are wrapper to that class methods.)
Where cache lives
=================
By default, the "cache" is nothing more than a PHP global variable. It means that it is in memory, but also means that it vanishes on every request.
However, via dropins (`advanced-cache.php` and / or `object-cache.php`), it is possible to setup a custom way to handle this cache.
Usually, this dropins are used to setup some sort of caching mechanism that "survive" the singular requests.
For this reason, among WP people, these are know as "persistent cache" plugins (even if outside the bubble the words "cache" and "persistent" don't not make a lot of sense together).
Popular choices nowadays are [Memcached](http://memcached.org/) or [Redis](http://redis.io/).
So using "persistent cache" plugins you can drastically reduce the number of database queries, because the cache is not updated on every request.
Some examples
=============
```
$foo = get_post_meta('foo', $post_id, true);
// a lot of code in the middle
$bar = get_post_meta('bar', $post_id, true);
```
The 2 lines of code above will trigger, at maximum, 1 database query.
In fact, when you query a custom field, all the fields for that post are retrieved from database, cached via object cache, and subsequent requests pull data from cache and not from db.
The same happen for taxonomy terms, WordPress pulls all the terms for a taxonomy once, then returns them from cache.
Object cache is used very widely in WordPress. Not only for posts, meta values and taxonomies, but also for users, comments, theme data...
What `WP_Query` has to do with all of this?
===========================================
When you query some posts via `WP_Query`, by default, WordPress not only pulls them from database (or from cache if they are cached) but also **updates the cache for all custom fields and all taxonomies** related to the posts pulled.
So when you call, for example, `get_the_terms()` or `get_post_meta()` while looping posts got via `WP_Query`, you don't actually trigger any database query, but pull information from cache.
Nice, it isn't?
===============
Well, yes, but it comes with a cost.
The cache update "magic" that WordPress does when pull posts via `WP_Query` happen in [`update_meta_cache`](https://developer.wordpress.org/reference/functions/update_meta_cache/) for meta and in [`update_object_term_cache`](https://developer.wordpress.org/reference/functions/update_object_term_cache/) for taxonomies.
If you look at the source code of those functions, you'll see that there WordPress performs just one db query in each function, but also does a lot of processing. For example, in `update_object_term_cache` there are [7 nested `foreach`](https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/taxonomy.php#L3581)... if you have a lot of taxonomies, and the number of posts per page is high, this is not very performant.
About those `WP_Query` arguments, finally
=========================================
What `'update_post_meta_cache'` and `'update_post_term_cache'` do when set to `false` is to prevent WordPress to update cache for custom fields and taxonomies, respectively.
In that case, the first time a custom field or a taxonomy is queried a database query is triggered, and data are cached.
It worth the trouble?
=====================
As usual, the answer is **it depends**. Most of the times to set those values to `false`, is a good choice, because it prevents unnecessary processing and database queries if not needed, and cache is updated anyway the first time custom field / taxonomy terms are required.
However, if you are going to call, even once, `get_post_meta()` during the loop and you are going to call `get_the_terms()` for all (or most) of the taxonomies supported by posts, then the cache updating is triggered anyway, and there might be no actual benefit on setting those query arguments to `false`.
|
215,885 |
<p>I have a number of custom post types as well as a custom taxonomy. I created an archive page for the taxonomy which lists each connected post, so all good there. What I would like to achieve is the following...</p>
<p>On my single template for that taxonomy (I've called it Topics), say if the topic was 'cancer', I would like a dropdown select menu or list of links to each custom post type WITH that taxonomy label. In other words, if I'm showing all the posts tagged with 'cancer' for every post type (which I currently have), that dropdown or link list at the top of the page would allow me to only show the tagged posts for each post type, as in the following:</p>
<pre>
<h1>Showing posts with topic: cancer</h1>
<p>Select a post type to view posts with this topic:</p>
<p><strong>Post type name 1</strong> (link)<br><strong>Post type name 2</strong> (link)<br><strong>Post type name 3</strong> (link)</p>
<p>(all posts tagged with cancer already display here...)</p>
</pre>
<p>Post type 1, when clicked, loads the single taxonomy page again but only lists the posts tagged with 'cancer' for that post type. This would apply to any of the few dozen tags for that custom taxonomy, so I can't hard-code the URL. It needs to be dynamic.</p>
<p>I hope this makes sense. I've searched for two days on this and so far have come up with nothing. Any help or direction would be appreciated. Unfortunately, the project I'm working on is gated and I can't share any links. I'm also using the Custom Post Type UI plugin (not by choice) and I know that plugin doesn't work well with taxonomies but I'm hoping my hands aren't tied here.</p>
<p>Cheers.</p>
|
[
{
"answer_id": 216402,
"author": "Aftab",
"author_id": 64614,
"author_profile": "https://wordpress.stackexchange.com/users/64614",
"pm_score": -1,
"selected": false,
"text": "<p>According to what I understand is : </p>\n\n<p>In your taxonomy.php</p>\n\n<p>Add this code :</p>\n\n<pre><code> $term = get_term_by( 'slug', get_query_var('term'), get_query_var('taxonomy') );\n echo '<h2>Showing posts with topic : ' . $term->name .'</h2>';\n</code></pre>\n\n<p>This will result in showing <strong>\"Showing post with topic : Cancer\"</strong></p>\n\n<p>Now for <strong>(all posts tagged with cancer already display here...)</strong></p>\n\n<p>You can run a get_posts() to get this :</p>\n\n<pre><code>$all_post = get_posts(array(\n 'post_type' => array( 'cpt1', 'cpt2', 'cpt3', 'post' ), // all cpt slug name\n 'numberposts' => -1, // number of post\n 'tax_query' => array(\n array(\n 'taxonomy' => get_query_var( 'taxonomy '), // current tax name\n 'field' => 'id',\n 'terms' => $term->term_id, // current tax_id\n )\n )\n);\n</code></pre>\n\n<p>By looping over them we can get all post details and we can display them.</p>\n"
},
{
"answer_id": 218937,
"author": "locomo",
"author_id": 42754,
"author_profile": "https://wordpress.stackexchange.com/users/42754",
"pm_score": 1,
"selected": false,
"text": "<p>If the URL to the 'cancer' taxonomy term in your example looked like this:</p>\n\n<pre><code>yourwebsite.com/topics/cancer/\n</code></pre>\n\n<p>then you could filter these results by post type with a URLs structured like this:</p>\n\n<pre><code>yourwebsite.com/topics/cancer/?post_type=question\n</code></pre>\n\n<p>Just put this in functions.php</p>\n\n<pre><code>add_filter( 'pre_get_posts', 'wp123_post_type_by_taxonomy' );\nfunction wp123_post_type_by_taxonomy( $query ) {\n if( is_tax( 'topics' ) && $query->is_main_query() ) {\n\n // get all post types:\n $post_types = get_post_types();\n\n // or add specific post types:\n // $post_types = array( 'post_type_1', 'post_type_2' );\n\n if ( !empty( $_GET['post_type'] ) && post_type_exists( $_GET['post_type'] ) ) {\n // show only results for this post type\n $query->set( 'post_type', $_GET['post_type'] );\n }\n\n }\n}\n</code></pre>\n"
}
] |
2016/01/27
|
[
"https://wordpress.stackexchange.com/questions/215885",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87604/"
] |
I have a number of custom post types as well as a custom taxonomy. I created an archive page for the taxonomy which lists each connected post, so all good there. What I would like to achieve is the following...
On my single template for that taxonomy (I've called it Topics), say if the topic was 'cancer', I would like a dropdown select menu or list of links to each custom post type WITH that taxonomy label. In other words, if I'm showing all the posts tagged with 'cancer' for every post type (which I currently have), that dropdown or link list at the top of the page would allow me to only show the tagged posts for each post type, as in the following:
```
Showing posts with topic: cancer
================================
Select a post type to view posts with this topic:
**Post type name 1** (link)
**Post type name 2** (link)
**Post type name 3** (link)
(all posts tagged with cancer already display here...)
```
Post type 1, when clicked, loads the single taxonomy page again but only lists the posts tagged with 'cancer' for that post type. This would apply to any of the few dozen tags for that custom taxonomy, so I can't hard-code the URL. It needs to be dynamic.
I hope this makes sense. I've searched for two days on this and so far have come up with nothing. Any help or direction would be appreciated. Unfortunately, the project I'm working on is gated and I can't share any links. I'm also using the Custom Post Type UI plugin (not by choice) and I know that plugin doesn't work well with taxonomies but I'm hoping my hands aren't tied here.
Cheers.
|
If the URL to the 'cancer' taxonomy term in your example looked like this:
```
yourwebsite.com/topics/cancer/
```
then you could filter these results by post type with a URLs structured like this:
```
yourwebsite.com/topics/cancer/?post_type=question
```
Just put this in functions.php
```
add_filter( 'pre_get_posts', 'wp123_post_type_by_taxonomy' );
function wp123_post_type_by_taxonomy( $query ) {
if( is_tax( 'topics' ) && $query->is_main_query() ) {
// get all post types:
$post_types = get_post_types();
// or add specific post types:
// $post_types = array( 'post_type_1', 'post_type_2' );
if ( !empty( $_GET['post_type'] ) && post_type_exists( $_GET['post_type'] ) ) {
// show only results for this post type
$query->set( 'post_type', $_GET['post_type'] );
}
}
}
```
|
215,937 |
<p>I am currently pulling in the post excerpt however there are 2 words at the start of it that I would rather not have in this particular place as there is a title already.</p>
<p>I have used wp_trim previously but this only takes words off the end, is there a way to do this for the first 2 words. These words are always the same if that helps? I'm not sure if I have get get the excerpt as a string then replace with nothing or if wp_trim can do this.</p>
<pre><code><?php $tagname = get_the_title (); ?>
<?php
$original_query = $wp_query;
$wp_query = null;
$args=array('posts_per_page'=>1,
'orderby' => 'rand',
'tag' => sluggify( $tagname));
$wp_query = new WP_Query( $args );
if ( have_posts() ) :
while (have_posts()) : the_post();
echo '<h2 class="entry-title">';
echo 'CASE STUDY';
echo '</h2>';
echo '<span>';
the_post_thumbnail();
echo '</span>';
echo '<strong>';
the_title();
echo '</strong>';
echo '<p>';
the_excerpt();
echo '</p>';
endwhile;
endif;
$wp_query = null;
$wp_query = $original_query;
wp_reset_postdata();?>
</code></pre>
<p>Amended code from suggested answer from @RRikesh:</p>
<pre><code><?php $tagname = get_the_title (); ?>
<?php
$original_query = $wp_query;
$wp_query = null;
$args=array('posts_per_page'=>1,
'orderby' => 'rand',
'tag' => sluggify( $tagname));
$wp_query = new WP_Query( $args );
if ( have_posts() ) :
while (have_posts()) : the_post();
$str = get_the_excerpt();
echo '<h2 class="entry-title">';
echo 'CASE STUDY';
echo '</h2>';
echo '<span>';
the_post_thumbnail();
echo '</span>';
echo '<strong>';
the_title();
echo '</strong>';
echo '<p>';
echo ltrim($str, "INSTRUCTION SYNOPSIS"); // Output: This is another Hello World.
echo '</p>';
endwhile;
endif;
$wp_query = null;
$wp_query = $original_query;
wp_reset_postdata();?>
</code></pre>
|
[
{
"answer_id": 215946,
"author": "Ben H",
"author_id": 64567,
"author_profile": "https://wordpress.stackexchange.com/users/64567",
"pm_score": 2,
"selected": true,
"text": "<p>I used substr to remove the first 21 characters from the string in the end. This was more consistent.</p>\n\n<pre><code>$str = get_the_excerpt();\n$str2 = substr($str, 21);\necho str2;\n</code></pre>\n"
},
{
"answer_id": 215950,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>A more reliable way would be to filter the excerpt and to explode the string into an array, remove the first two key/value pairs from the array and then return your string</p>\n\n<pre><code>add_filter( 'wp_trim_excerpt', function ( $text )\n{\n // Make sure we have a text\n if ( !$text )\n return $text;\n\n $text = ltrim( $text );\n $text_as_array = explode( ' ', $text );\n\n // Make sure we have at least X amount of words as an array\n if ( 10 > count( $text_as_array ) )\n return $text;\n\n $text_array_to_keep = array_slice( $text_as_array, 2 );\n $text_as_string = implode( ' ', $text_array_to_keep );\n $text = $text_as_string;\n\n return $text;\n}):\n</code></pre>\n"
},
{
"answer_id": 215977,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://php.net/manual/en/function.preg-replace.php\" rel=\"nofollow\">preg_replace</a> to the one-call rescue. <code>/\\w+/</code> will match words, while the third argument of <a href=\"http://php.net/manual/en/function.preg-replace.php\" rel=\"nofollow\"><code>preg_replace()</code></a> will specify the number of matches. Since you want to remove them then we just pass an empty string as the replacement.</p>\n\n<pre><code>$str = 'These are some words. But the first two will not remain.';\n\n// pattern, replacement, string, limit\n\necho preg_replace( '/\\w+/', '', $str, 2 );\n\n// output: some words. But the first 2 will not remain.\n</code></pre>\n\n<p>An alternative is to use <a href=\"http://php.net/manual/en/function.substr.php\" rel=\"nofollow\">substr</a> with <a href=\"http://php.net/manual/en/function.strpos.php\" rel=\"nofollow\">strpos</a>.</p>\n\n<pre><code>// reduce the extra whitespace\n\n$str = trim( \" This is some text and stuff. \" );\n\n// find the second space and pull everything after\n\necho trim( substr( $str, strpos( $str, ' ', strpos( $str, ' ' ) + 1 ) ) );\n\n// output: some text and stuff.\n</code></pre>\n"
}
] |
2016/01/28
|
[
"https://wordpress.stackexchange.com/questions/215937",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64567/"
] |
I am currently pulling in the post excerpt however there are 2 words at the start of it that I would rather not have in this particular place as there is a title already.
I have used wp\_trim previously but this only takes words off the end, is there a way to do this for the first 2 words. These words are always the same if that helps? I'm not sure if I have get get the excerpt as a string then replace with nothing or if wp\_trim can do this.
```
<?php $tagname = get_the_title (); ?>
<?php
$original_query = $wp_query;
$wp_query = null;
$args=array('posts_per_page'=>1,
'orderby' => 'rand',
'tag' => sluggify( $tagname));
$wp_query = new WP_Query( $args );
if ( have_posts() ) :
while (have_posts()) : the_post();
echo '<h2 class="entry-title">';
echo 'CASE STUDY';
echo '</h2>';
echo '<span>';
the_post_thumbnail();
echo '</span>';
echo '<strong>';
the_title();
echo '</strong>';
echo '<p>';
the_excerpt();
echo '</p>';
endwhile;
endif;
$wp_query = null;
$wp_query = $original_query;
wp_reset_postdata();?>
```
Amended code from suggested answer from @RRikesh:
```
<?php $tagname = get_the_title (); ?>
<?php
$original_query = $wp_query;
$wp_query = null;
$args=array('posts_per_page'=>1,
'orderby' => 'rand',
'tag' => sluggify( $tagname));
$wp_query = new WP_Query( $args );
if ( have_posts() ) :
while (have_posts()) : the_post();
$str = get_the_excerpt();
echo '<h2 class="entry-title">';
echo 'CASE STUDY';
echo '</h2>';
echo '<span>';
the_post_thumbnail();
echo '</span>';
echo '<strong>';
the_title();
echo '</strong>';
echo '<p>';
echo ltrim($str, "INSTRUCTION SYNOPSIS"); // Output: This is another Hello World.
echo '</p>';
endwhile;
endif;
$wp_query = null;
$wp_query = $original_query;
wp_reset_postdata();?>
```
|
I used substr to remove the first 21 characters from the string in the end. This was more consistent.
```
$str = get_the_excerpt();
$str2 = substr($str, 21);
echo str2;
```
|
215,948 |
<p>This is my site <a href="http://185.105.4.132/~orangeye/" rel="nofollow">http://185.105.4.132/~orangeye/</a></p>
<p>When I scroll down, a white space appears between my menu bar and slider.</p>
<p>how do I remove that?</p>
<p>This is what I have done to place the logo at the very top. After doing this, the white space started appearing. </p>
<pre><code>.edgtf-page-header {
margin-top: 30px;
padding-top:290px;
background-image: url('http://185.105.4.132/~orangeye/wp-content/uploads/2016/01/home-logo.png');
background-repeat: no-repeat;
background-position: center top;
position: relative;
display: block;
}
</code></pre>
|
[
{
"answer_id": 215946,
"author": "Ben H",
"author_id": 64567,
"author_profile": "https://wordpress.stackexchange.com/users/64567",
"pm_score": 2,
"selected": true,
"text": "<p>I used substr to remove the first 21 characters from the string in the end. This was more consistent.</p>\n\n<pre><code>$str = get_the_excerpt();\n$str2 = substr($str, 21);\necho str2;\n</code></pre>\n"
},
{
"answer_id": 215950,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>A more reliable way would be to filter the excerpt and to explode the string into an array, remove the first two key/value pairs from the array and then return your string</p>\n\n<pre><code>add_filter( 'wp_trim_excerpt', function ( $text )\n{\n // Make sure we have a text\n if ( !$text )\n return $text;\n\n $text = ltrim( $text );\n $text_as_array = explode( ' ', $text );\n\n // Make sure we have at least X amount of words as an array\n if ( 10 > count( $text_as_array ) )\n return $text;\n\n $text_array_to_keep = array_slice( $text_as_array, 2 );\n $text_as_string = implode( ' ', $text_array_to_keep );\n $text = $text_as_string;\n\n return $text;\n}):\n</code></pre>\n"
},
{
"answer_id": 215977,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://php.net/manual/en/function.preg-replace.php\" rel=\"nofollow\">preg_replace</a> to the one-call rescue. <code>/\\w+/</code> will match words, while the third argument of <a href=\"http://php.net/manual/en/function.preg-replace.php\" rel=\"nofollow\"><code>preg_replace()</code></a> will specify the number of matches. Since you want to remove them then we just pass an empty string as the replacement.</p>\n\n<pre><code>$str = 'These are some words. But the first two will not remain.';\n\n// pattern, replacement, string, limit\n\necho preg_replace( '/\\w+/', '', $str, 2 );\n\n// output: some words. But the first 2 will not remain.\n</code></pre>\n\n<p>An alternative is to use <a href=\"http://php.net/manual/en/function.substr.php\" rel=\"nofollow\">substr</a> with <a href=\"http://php.net/manual/en/function.strpos.php\" rel=\"nofollow\">strpos</a>.</p>\n\n<pre><code>// reduce the extra whitespace\n\n$str = trim( \" This is some text and stuff. \" );\n\n// find the second space and pull everything after\n\necho trim( substr( $str, strpos( $str, ' ', strpos( $str, ' ' ) + 1 ) ) );\n\n// output: some text and stuff.\n</code></pre>\n"
}
] |
2016/01/28
|
[
"https://wordpress.stackexchange.com/questions/215948",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81941/"
] |
This is my site <http://185.105.4.132/~orangeye/>
When I scroll down, a white space appears between my menu bar and slider.
how do I remove that?
This is what I have done to place the logo at the very top. After doing this, the white space started appearing.
```
.edgtf-page-header {
margin-top: 30px;
padding-top:290px;
background-image: url('http://185.105.4.132/~orangeye/wp-content/uploads/2016/01/home-logo.png');
background-repeat: no-repeat;
background-position: center top;
position: relative;
display: block;
}
```
|
I used substr to remove the first 21 characters from the string in the end. This was more consistent.
```
$str = get_the_excerpt();
$str2 = substr($str, 21);
echo str2;
```
|
215,971 |
<p>I need to put the PHP <code><?php global $' . $icon_var . '; echo $' . $icon_var . '; ?></code> inside the variable of a custom menu structure, but it gets commented: </p>
<pre><code><a href="http://slembas.esy.es/">
<!--?php global $icon_home; echo $icon_home; ?-->
<span>Page Name</span>
</a>
</code></pre>
<p>Explanation of the variables:</p>
<p><code>$icon_var</code> - gets value from a custom input <code>_menu_custom_item</code> where I write variable without <code>$</code> which contain SVG code to make menu items fancier with icons.</p>
<pre><code> function sidebar_menu() {
$menu_name = 'sidebar_pages';
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 = '<nav>' . "\n";
$menu_list .= "\t\t\t\t" . '<ul>' . "\n";
foreach ( (array) $menu_items as $key => $menu_item ) {
$icon_var = get_post_meta( $menu_item->ID, '_menu_item_custom', true );
$title = $menu_item->title;
$url = $menu_item->url;
$menu_list .= "\t\t\t\t\t" . '<li><a href="' . $url . '"><?php global $' . $icon_var . '; echo $' . $icon_var . '; ?><span>' . $title . '</span></a></li>' . "\n";
}
$menu_list .= "\t\t\t\t" . '</ul>' . "\n";
$menu_list .= "\t\t\t" . '</nav>' . "\n";
}
else {
// $menu_list = '<!-- no list defined -->';
}
echo $menu_list;
}
</code></pre>
<p>The desired output should look like:</p>
<pre><code><li>
<a href="/" class="icon" title="Главная">
<svg style="width:24px;height:24px" viewBox="0 0 24 24">
<path fill="#000000" d="M10,20V14H14V20H19V12H22L12,3L2,12H5V20H10Z"></path>
</svg>
<span>Главная</span>
</a>
</li>
</code></pre>
|
[
{
"answer_id": 215946,
"author": "Ben H",
"author_id": 64567,
"author_profile": "https://wordpress.stackexchange.com/users/64567",
"pm_score": 2,
"selected": true,
"text": "<p>I used substr to remove the first 21 characters from the string in the end. This was more consistent.</p>\n\n<pre><code>$str = get_the_excerpt();\n$str2 = substr($str, 21);\necho str2;\n</code></pre>\n"
},
{
"answer_id": 215950,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>A more reliable way would be to filter the excerpt and to explode the string into an array, remove the first two key/value pairs from the array and then return your string</p>\n\n<pre><code>add_filter( 'wp_trim_excerpt', function ( $text )\n{\n // Make sure we have a text\n if ( !$text )\n return $text;\n\n $text = ltrim( $text );\n $text_as_array = explode( ' ', $text );\n\n // Make sure we have at least X amount of words as an array\n if ( 10 > count( $text_as_array ) )\n return $text;\n\n $text_array_to_keep = array_slice( $text_as_array, 2 );\n $text_as_string = implode( ' ', $text_array_to_keep );\n $text = $text_as_string;\n\n return $text;\n}):\n</code></pre>\n"
},
{
"answer_id": 215977,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://php.net/manual/en/function.preg-replace.php\" rel=\"nofollow\">preg_replace</a> to the one-call rescue. <code>/\\w+/</code> will match words, while the third argument of <a href=\"http://php.net/manual/en/function.preg-replace.php\" rel=\"nofollow\"><code>preg_replace()</code></a> will specify the number of matches. Since you want to remove them then we just pass an empty string as the replacement.</p>\n\n<pre><code>$str = 'These are some words. But the first two will not remain.';\n\n// pattern, replacement, string, limit\n\necho preg_replace( '/\\w+/', '', $str, 2 );\n\n// output: some words. But the first 2 will not remain.\n</code></pre>\n\n<p>An alternative is to use <a href=\"http://php.net/manual/en/function.substr.php\" rel=\"nofollow\">substr</a> with <a href=\"http://php.net/manual/en/function.strpos.php\" rel=\"nofollow\">strpos</a>.</p>\n\n<pre><code>// reduce the extra whitespace\n\n$str = trim( \" This is some text and stuff. \" );\n\n// find the second space and pull everything after\n\necho trim( substr( $str, strpos( $str, ' ', strpos( $str, ' ' ) + 1 ) ) );\n\n// output: some text and stuff.\n</code></pre>\n"
}
] |
2016/01/28
|
[
"https://wordpress.stackexchange.com/questions/215971",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86763/"
] |
I need to put the PHP `<?php global $' . $icon_var . '; echo $' . $icon_var . '; ?>` inside the variable of a custom menu structure, but it gets commented:
```
<a href="http://slembas.esy.es/">
<!--?php global $icon_home; echo $icon_home; ?-->
<span>Page Name</span>
</a>
```
Explanation of the variables:
`$icon_var` - gets value from a custom input `_menu_custom_item` where I write variable without `$` which contain SVG code to make menu items fancier with icons.
```
function sidebar_menu() {
$menu_name = 'sidebar_pages';
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 = '<nav>' . "\n";
$menu_list .= "\t\t\t\t" . '<ul>' . "\n";
foreach ( (array) $menu_items as $key => $menu_item ) {
$icon_var = get_post_meta( $menu_item->ID, '_menu_item_custom', true );
$title = $menu_item->title;
$url = $menu_item->url;
$menu_list .= "\t\t\t\t\t" . '<li><a href="' . $url . '"><?php global $' . $icon_var . '; echo $' . $icon_var . '; ?><span>' . $title . '</span></a></li>' . "\n";
}
$menu_list .= "\t\t\t\t" . '</ul>' . "\n";
$menu_list .= "\t\t\t" . '</nav>' . "\n";
}
else {
// $menu_list = '<!-- no list defined -->';
}
echo $menu_list;
}
```
The desired output should look like:
```
<li>
<a href="/" class="icon" title="Главная">
<svg style="width:24px;height:24px" viewBox="0 0 24 24">
<path fill="#000000" d="M10,20V14H14V20H19V12H22L12,3L2,12H5V20H10Z"></path>
</svg>
<span>Главная</span>
</a>
</li>
```
|
I used substr to remove the first 21 characters from the string in the end. This was more consistent.
```
$str = get_the_excerpt();
$str2 = substr($str, 21);
echo str2;
```
|
215,987 |
<p>I've come quite far, but can't manage to get this to work.</p>
<p>I'd like to remove the base slug from my Custom Post Type <code>review</code> and my Custom Taxonomy <code>brand</code>.</p>
<p>The final result should be a URL like this: <code>https://example.org/apple/iphone7</code>.</p>
<p>Right now I got this: <code>https://example.org/review/apple/iphone7</code>.</p>
<p>I've read quite a lot and I know about the consequences and possible conflicts and that WordPress isn't designed to handle these kind of rewrites. But there has to be a way to achieve what I'm trying to do.</p>
<p>The code at <a href="http://www.markwarddesign.com/2014/02/remove-custom-post-type-slug-permalink/" rel="nofollow">http://www.markwarddesign.com/2014/02/remove-custom-post-type-slug-permalink/</a> works to remove the base slug, but I can't manage to combine the functions with mine below. As soon as I add the function from markwarddesign.com it results in a 404.</p>
<p>I tried the solution posted at <a href="https://wordpress.stackexchange.com/questions/57493/custom-taxonomy-specific-to-a-custom-post-type?lq=1">Custom Taxonomy specific to a Custom Post type</a> but it still contains the base slug.</p>
<p>Please take a look at my setup.</p>
<pre><code>function brand_permalink($permalink, $post_id, $leavename) {
if (strpos($permalink, '%brand%') === FALSE) return $permalink;
// Get post
$post = get_post($post_id);
if (!$post) return $permalink;
// Get taxonomy terms
$terms = wp_get_object_terms($post->ID, 'brand');
if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0]))
$taxonomy_slug = $terms[0]->slug;
else $taxonomy_slug = 'other';
return str_replace('%brand%', $taxonomy_slug, $permalink);
}
add_filter('post_link', 'brand_permalink', 1, 3);
add_filter('post_type_link', 'brand_permalink', 1, 3);
/**
* Code below is from https://wordpress.stackexchange.com/questions/57493/custom-taxonomy-specific-to-a-custom-post-type
* A custom taxonomy is created and linked to CPT 'review'.
* The goal is to create permalinks containing the taxonomy + CPT post name, e.g. /some-brand/xyz-review/
*/
function custom_brand_taxonomy() {
register_taxonomy(
'brand', //The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces).
'review', //post type name
array(
'hierarchical' => true,
'label' => 'Brand', //Display name
'query_var' => true,
'rewrite' => array(
'slug' => '', // This controls the base slug that will display before each term
'with_front' => false // Don't display the category base before
)
)
);
}
add_action( 'init', 'custom_brand_taxonomy');
/**
* Creating a function to create our CPT
*
*/
function xyz_custom_post_types() {
// Set options for Custom Post Type REVIEW
$review_args = array(
'label' => __( 'review', 'mythemexyz' ),
'description' => __( 'Descrption review bla bla', 'mythemexyz' ),
'labels' => array(
'name' => _x( 'reviewe', 'Post Type General Name', 'mythemexyz' ),
'singular_name' => _x( 'review', 'Post Type Singular Name', 'mythemexyz' ),
'menu_name' => __( 'reviewe', 'mythemexyz' ),
'parent_item_colon' => __( 'Parent review', 'mythemexyz' ),
'all_items' => __( 'Alle reviewe', 'mythemexyz' ),
'view_item' => __( 'review ansehen', 'mythemexyz' ),
'add_new_item' => __( 'review erstellen', 'mythemexyz' ),
'add_new' => __( 'Erstellen', 'mythemexyz' ),
'edit_item' => __( 'review bearbeiten', 'mythemexyz' ),
'update_item' => __( 'review aktualisieren', 'mythemexyz' ),
'search_items' => __( 'review suchen', 'mythemexyz' ),
'not_found' => __( 'Nicht gefunden', 'mythemexyz' ),
'not_found_in_trash' => __( 'Nicht in Papierkorb gefunden', 'mythemexyz' ),
),
// Features this CPT supports in Post Editor
'supports' => array( 'title', 'editor', 'revisions', 'custom-fields', 'page-attributes' ),
/* A hierarchical CPT is like Pages and can have
* Parent and child items. A non-hierarchical CPT
* is like Posts.
*/
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 99,
'can_export' => true,
'rewrite' => array( 'slug' => 'review/%brand%', 'with_front' => false ),
'has_archive' => 'review',
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
// Registering your Custom Post Type
register_post_type( 'review', $review_args );
}
/* Hook into the 'init' action so that the function
* Containing our post type registration is not
* unnecessarily executed.
*/
add_action( 'init', 'xyz_custom_post_types', 0 );
</code></pre>
<p>Any help is appreciated.</p>
|
[
{
"answer_id": 215946,
"author": "Ben H",
"author_id": 64567,
"author_profile": "https://wordpress.stackexchange.com/users/64567",
"pm_score": 2,
"selected": true,
"text": "<p>I used substr to remove the first 21 characters from the string in the end. This was more consistent.</p>\n\n<pre><code>$str = get_the_excerpt();\n$str2 = substr($str, 21);\necho str2;\n</code></pre>\n"
},
{
"answer_id": 215950,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>A more reliable way would be to filter the excerpt and to explode the string into an array, remove the first two key/value pairs from the array and then return your string</p>\n\n<pre><code>add_filter( 'wp_trim_excerpt', function ( $text )\n{\n // Make sure we have a text\n if ( !$text )\n return $text;\n\n $text = ltrim( $text );\n $text_as_array = explode( ' ', $text );\n\n // Make sure we have at least X amount of words as an array\n if ( 10 > count( $text_as_array ) )\n return $text;\n\n $text_array_to_keep = array_slice( $text_as_array, 2 );\n $text_as_string = implode( ' ', $text_array_to_keep );\n $text = $text_as_string;\n\n return $text;\n}):\n</code></pre>\n"
},
{
"answer_id": 215977,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://php.net/manual/en/function.preg-replace.php\" rel=\"nofollow\">preg_replace</a> to the one-call rescue. <code>/\\w+/</code> will match words, while the third argument of <a href=\"http://php.net/manual/en/function.preg-replace.php\" rel=\"nofollow\"><code>preg_replace()</code></a> will specify the number of matches. Since you want to remove them then we just pass an empty string as the replacement.</p>\n\n<pre><code>$str = 'These are some words. But the first two will not remain.';\n\n// pattern, replacement, string, limit\n\necho preg_replace( '/\\w+/', '', $str, 2 );\n\n// output: some words. But the first 2 will not remain.\n</code></pre>\n\n<p>An alternative is to use <a href=\"http://php.net/manual/en/function.substr.php\" rel=\"nofollow\">substr</a> with <a href=\"http://php.net/manual/en/function.strpos.php\" rel=\"nofollow\">strpos</a>.</p>\n\n<pre><code>// reduce the extra whitespace\n\n$str = trim( \" This is some text and stuff. \" );\n\n// find the second space and pull everything after\n\necho trim( substr( $str, strpos( $str, ' ', strpos( $str, ' ' ) + 1 ) ) );\n\n// output: some text and stuff.\n</code></pre>\n"
}
] |
2016/01/28
|
[
"https://wordpress.stackexchange.com/questions/215987",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87365/"
] |
I've come quite far, but can't manage to get this to work.
I'd like to remove the base slug from my Custom Post Type `review` and my Custom Taxonomy `brand`.
The final result should be a URL like this: `https://example.org/apple/iphone7`.
Right now I got this: `https://example.org/review/apple/iphone7`.
I've read quite a lot and I know about the consequences and possible conflicts and that WordPress isn't designed to handle these kind of rewrites. But there has to be a way to achieve what I'm trying to do.
The code at <http://www.markwarddesign.com/2014/02/remove-custom-post-type-slug-permalink/> works to remove the base slug, but I can't manage to combine the functions with mine below. As soon as I add the function from markwarddesign.com it results in a 404.
I tried the solution posted at [Custom Taxonomy specific to a Custom Post type](https://wordpress.stackexchange.com/questions/57493/custom-taxonomy-specific-to-a-custom-post-type?lq=1) but it still contains the base slug.
Please take a look at my setup.
```
function brand_permalink($permalink, $post_id, $leavename) {
if (strpos($permalink, '%brand%') === FALSE) return $permalink;
// Get post
$post = get_post($post_id);
if (!$post) return $permalink;
// Get taxonomy terms
$terms = wp_get_object_terms($post->ID, 'brand');
if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0]))
$taxonomy_slug = $terms[0]->slug;
else $taxonomy_slug = 'other';
return str_replace('%brand%', $taxonomy_slug, $permalink);
}
add_filter('post_link', 'brand_permalink', 1, 3);
add_filter('post_type_link', 'brand_permalink', 1, 3);
/**
* Code below is from https://wordpress.stackexchange.com/questions/57493/custom-taxonomy-specific-to-a-custom-post-type
* A custom taxonomy is created and linked to CPT 'review'.
* The goal is to create permalinks containing the taxonomy + CPT post name, e.g. /some-brand/xyz-review/
*/
function custom_brand_taxonomy() {
register_taxonomy(
'brand', //The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces).
'review', //post type name
array(
'hierarchical' => true,
'label' => 'Brand', //Display name
'query_var' => true,
'rewrite' => array(
'slug' => '', // This controls the base slug that will display before each term
'with_front' => false // Don't display the category base before
)
)
);
}
add_action( 'init', 'custom_brand_taxonomy');
/**
* Creating a function to create our CPT
*
*/
function xyz_custom_post_types() {
// Set options for Custom Post Type REVIEW
$review_args = array(
'label' => __( 'review', 'mythemexyz' ),
'description' => __( 'Descrption review bla bla', 'mythemexyz' ),
'labels' => array(
'name' => _x( 'reviewe', 'Post Type General Name', 'mythemexyz' ),
'singular_name' => _x( 'review', 'Post Type Singular Name', 'mythemexyz' ),
'menu_name' => __( 'reviewe', 'mythemexyz' ),
'parent_item_colon' => __( 'Parent review', 'mythemexyz' ),
'all_items' => __( 'Alle reviewe', 'mythemexyz' ),
'view_item' => __( 'review ansehen', 'mythemexyz' ),
'add_new_item' => __( 'review erstellen', 'mythemexyz' ),
'add_new' => __( 'Erstellen', 'mythemexyz' ),
'edit_item' => __( 'review bearbeiten', 'mythemexyz' ),
'update_item' => __( 'review aktualisieren', 'mythemexyz' ),
'search_items' => __( 'review suchen', 'mythemexyz' ),
'not_found' => __( 'Nicht gefunden', 'mythemexyz' ),
'not_found_in_trash' => __( 'Nicht in Papierkorb gefunden', 'mythemexyz' ),
),
// Features this CPT supports in Post Editor
'supports' => array( 'title', 'editor', 'revisions', 'custom-fields', 'page-attributes' ),
/* A hierarchical CPT is like Pages and can have
* Parent and child items. A non-hierarchical CPT
* is like Posts.
*/
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 99,
'can_export' => true,
'rewrite' => array( 'slug' => 'review/%brand%', 'with_front' => false ),
'has_archive' => 'review',
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
// Registering your Custom Post Type
register_post_type( 'review', $review_args );
}
/* Hook into the 'init' action so that the function
* Containing our post type registration is not
* unnecessarily executed.
*/
add_action( 'init', 'xyz_custom_post_types', 0 );
```
Any help is appreciated.
|
I used substr to remove the first 21 characters from the string in the end. This was more consistent.
```
$str = get_the_excerpt();
$str2 = substr($str, 21);
echo str2;
```
|
216,004 |
<p>I have a <a href="http://creative-thunder.com/" rel="nofollow">WordPress website</a>. I've tested it for speed test with google tools, but I see some of errors like this:</p>
<blockquote>
<p>Leverage browser caching Setting an expiry date or a maximum age in the HTTP headers for static resources instructs the browser to load previously downloaded resources from local disk rather than over the network. Leverage browser caching for the following cacheable resources:</p>
</blockquote>
<p>So how can I solve this errors and seed up my site. Please give me a better way to fix it by any coding or by any Plugins.</p>
<p>You can see it live <a href="https://developers.google.com/speed/pagespeed/insights/?url=http%3A%2F%2Fcreative-thunder.com%2F&tab=desktop" rel="nofollow">here</a></p>
|
[
{
"answer_id": 216019,
"author": "Emanuel Rocha Costa",
"author_id": 75873,
"author_profile": "https://wordpress.stackexchange.com/users/75873",
"pm_score": 2,
"selected": false,
"text": "<p>For WordPress Website optimization you should take a look at: <a href=\"https://codex.wordpress.org/WordPress_Optimization\" rel=\"nofollow\">https://codex.wordpress.org/WordPress_Optimization</a></p>\n\n<p>I took a look at your pagespeed report and the main thing there are the images you are using. There are many plugins that can optimize them for you. I like this one in particular: <a href=\"https://wordpress.org/plugins/imsanity/\" rel=\"nofollow\">https://wordpress.org/plugins/imsanity/</a></p>\n\n<p>As per the server cache, you can either try the popular cache plugins or ask a sysadmin to optimize these options for you on the server level.</p>\n\n<p>In my case. Using Apache 2.4 I have this configuration in my pre_virtualhost_global.conf:</p>\n\n<pre><code># Cache Control Settings for one hour cache\n<FilesMatch \".(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$\">\nHeader set Cache-Control \"max-age=3600, public\"\n</FilesMatch>\n\n<FilesMatch \".(xml|txt)$\">\nHeader set Cache-Control \"max-age=3600, public, must-revalidate\"\n</FilesMatch>\n\n<FilesMatch \".(html|htm)$\">\nHeader set Cache-Control \"max-age=3600, must-revalidate\"\n</FilesMatch>\n\n# Mod Deflate performs data compression\n<IfModule mod_deflate.c>\n<FilesMatch \".(js|css|html|php|xml|jpg|png|gif)$\">\nSetOutputFilter DEFLATE\nBrowserMatch ^Mozilla/4 gzip-only-text/html\nBrowserMatch ^Mozilla/4.0[678] no-gzip\nBrowserMatch bMSIE no-gzip\n</FilesMatch>\n</IfModule>\n</code></pre>\n\n<p>Pagespeed also offer instructions on the other factors. You should follow them. </p>\n"
},
{
"answer_id": 219026,
"author": "CodyA",
"author_id": 84632,
"author_profile": "https://wordpress.stackexchange.com/users/84632",
"pm_score": 0,
"selected": false,
"text": "<p>I would suggest reading <a href=\"https://www.keycdn.com/support/leverage-browser-caching/\" rel=\"nofollow\">this article</a> which helps better explain the page speed recommendation of \"leverage browsing caching\". You can set your desired expires header either in your .htaccess file:</p>\n\n<p>E.g.</p>\n\n<pre><code>## EXPIRES CACHING ##\n<IfModule mod_expires.c>\nExpiresActive On\nExpiresByType image/jpg \"access 1 year\"\nExpiresByType image/jpeg \"access 1 year\"\nExpiresByType image/gif \"access 1 year\"\nExpiresByType image/png \"access 1 year\"\nExpiresByType text/css \"access 1 month\"\nExpiresByType text/html \"access 1 month\"\nExpiresByType application/pdf \"access 1 month\"\nExpiresByType text/x-javascript \"access 1 month\"\nExpiresByType application/x-shockwave-flash \"access 1 month\"\nExpiresByType image/x-icon \"access 1 year\"\nExpiresDefault \"access 1 month\"\n</IfModule>\n## EXPIRES CACHING ##\n</code></pre>\n\n<p>or if you're using Nginx it can be included within your configuration file:</p>\n\n<p>E.g.</p>\n\n<pre><code>server {\n listen 80;\n server_name example.com;\n\n location / {\n root /var/www/example;\n index index.html index.htm;\n }\n\n location ~* \\.(jpg|jpeg|gif|png)$ {\n expires 365d;\n }\n\n location ~* \\.(pdf|css|html|js|swf)$ {\n expires 30d;\n }\n}\n</code></pre>\n"
}
] |
2016/01/28
|
[
"https://wordpress.stackexchange.com/questions/216004",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85296/"
] |
I have a [WordPress website](http://creative-thunder.com/). I've tested it for speed test with google tools, but I see some of errors like this:
>
> Leverage browser caching Setting an expiry date or a maximum age in the HTTP headers for static resources instructs the browser to load previously downloaded resources from local disk rather than over the network. Leverage browser caching for the following cacheable resources:
>
>
>
So how can I solve this errors and seed up my site. Please give me a better way to fix it by any coding or by any Plugins.
You can see it live [here](https://developers.google.com/speed/pagespeed/insights/?url=http%3A%2F%2Fcreative-thunder.com%2F&tab=desktop)
|
For WordPress Website optimization you should take a look at: <https://codex.wordpress.org/WordPress_Optimization>
I took a look at your pagespeed report and the main thing there are the images you are using. There are many plugins that can optimize them for you. I like this one in particular: <https://wordpress.org/plugins/imsanity/>
As per the server cache, you can either try the popular cache plugins or ask a sysadmin to optimize these options for you on the server level.
In my case. Using Apache 2.4 I have this configuration in my pre\_virtualhost\_global.conf:
```
# Cache Control Settings for one hour cache
<FilesMatch ".(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
Header set Cache-Control "max-age=3600, public"
</FilesMatch>
<FilesMatch ".(xml|txt)$">
Header set Cache-Control "max-age=3600, public, must-revalidate"
</FilesMatch>
<FilesMatch ".(html|htm)$">
Header set Cache-Control "max-age=3600, must-revalidate"
</FilesMatch>
# Mod Deflate performs data compression
<IfModule mod_deflate.c>
<FilesMatch ".(js|css|html|php|xml|jpg|png|gif)$">
SetOutputFilter DEFLATE
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4.0[678] no-gzip
BrowserMatch bMSIE no-gzip
</FilesMatch>
</IfModule>
```
Pagespeed also offer instructions on the other factors. You should follow them.
|
216,028 |
<p>So, I have been working on an SQL query involving the users and usermeta tables in wordpress. I am not getting the correct results. I have the following query written</p>
<pre><code>SELECT
*
FROM
IL9_users
LEFT JOIN
(
SELECT
user_id,
MAX(case when meta_key = 'first_name' then meta_value end) first_name,
MAX(case when meta_key = 'last_name' then meta_value end) last_name
FROM
IL9_usermeta
) AS um
ON
IL9_users.ID = um.user_id
</code></pre>
<p>This code returns all of the results except the correct values for first_name and last_name. The first value returned is incorrect, but at least it is being returned. All of the other values are null. Does anyone have any insight on this? </p>
|
[
{
"answer_id": 216019,
"author": "Emanuel Rocha Costa",
"author_id": 75873,
"author_profile": "https://wordpress.stackexchange.com/users/75873",
"pm_score": 2,
"selected": false,
"text": "<p>For WordPress Website optimization you should take a look at: <a href=\"https://codex.wordpress.org/WordPress_Optimization\" rel=\"nofollow\">https://codex.wordpress.org/WordPress_Optimization</a></p>\n\n<p>I took a look at your pagespeed report and the main thing there are the images you are using. There are many plugins that can optimize them for you. I like this one in particular: <a href=\"https://wordpress.org/plugins/imsanity/\" rel=\"nofollow\">https://wordpress.org/plugins/imsanity/</a></p>\n\n<p>As per the server cache, you can either try the popular cache plugins or ask a sysadmin to optimize these options for you on the server level.</p>\n\n<p>In my case. Using Apache 2.4 I have this configuration in my pre_virtualhost_global.conf:</p>\n\n<pre><code># Cache Control Settings for one hour cache\n<FilesMatch \".(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$\">\nHeader set Cache-Control \"max-age=3600, public\"\n</FilesMatch>\n\n<FilesMatch \".(xml|txt)$\">\nHeader set Cache-Control \"max-age=3600, public, must-revalidate\"\n</FilesMatch>\n\n<FilesMatch \".(html|htm)$\">\nHeader set Cache-Control \"max-age=3600, must-revalidate\"\n</FilesMatch>\n\n# Mod Deflate performs data compression\n<IfModule mod_deflate.c>\n<FilesMatch \".(js|css|html|php|xml|jpg|png|gif)$\">\nSetOutputFilter DEFLATE\nBrowserMatch ^Mozilla/4 gzip-only-text/html\nBrowserMatch ^Mozilla/4.0[678] no-gzip\nBrowserMatch bMSIE no-gzip\n</FilesMatch>\n</IfModule>\n</code></pre>\n\n<p>Pagespeed also offer instructions on the other factors. You should follow them. </p>\n"
},
{
"answer_id": 219026,
"author": "CodyA",
"author_id": 84632,
"author_profile": "https://wordpress.stackexchange.com/users/84632",
"pm_score": 0,
"selected": false,
"text": "<p>I would suggest reading <a href=\"https://www.keycdn.com/support/leverage-browser-caching/\" rel=\"nofollow\">this article</a> which helps better explain the page speed recommendation of \"leverage browsing caching\". You can set your desired expires header either in your .htaccess file:</p>\n\n<p>E.g.</p>\n\n<pre><code>## EXPIRES CACHING ##\n<IfModule mod_expires.c>\nExpiresActive On\nExpiresByType image/jpg \"access 1 year\"\nExpiresByType image/jpeg \"access 1 year\"\nExpiresByType image/gif \"access 1 year\"\nExpiresByType image/png \"access 1 year\"\nExpiresByType text/css \"access 1 month\"\nExpiresByType text/html \"access 1 month\"\nExpiresByType application/pdf \"access 1 month\"\nExpiresByType text/x-javascript \"access 1 month\"\nExpiresByType application/x-shockwave-flash \"access 1 month\"\nExpiresByType image/x-icon \"access 1 year\"\nExpiresDefault \"access 1 month\"\n</IfModule>\n## EXPIRES CACHING ##\n</code></pre>\n\n<p>or if you're using Nginx it can be included within your configuration file:</p>\n\n<p>E.g.</p>\n\n<pre><code>server {\n listen 80;\n server_name example.com;\n\n location / {\n root /var/www/example;\n index index.html index.htm;\n }\n\n location ~* \\.(jpg|jpeg|gif|png)$ {\n expires 365d;\n }\n\n location ~* \\.(pdf|css|html|js|swf)$ {\n expires 30d;\n }\n}\n</code></pre>\n"
}
] |
2016/01/29
|
[
"https://wordpress.stackexchange.com/questions/216028",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87687/"
] |
So, I have been working on an SQL query involving the users and usermeta tables in wordpress. I am not getting the correct results. I have the following query written
```
SELECT
*
FROM
IL9_users
LEFT JOIN
(
SELECT
user_id,
MAX(case when meta_key = 'first_name' then meta_value end) first_name,
MAX(case when meta_key = 'last_name' then meta_value end) last_name
FROM
IL9_usermeta
) AS um
ON
IL9_users.ID = um.user_id
```
This code returns all of the results except the correct values for first\_name and last\_name. The first value returned is incorrect, but at least it is being returned. All of the other values are null. Does anyone have any insight on this?
|
For WordPress Website optimization you should take a look at: <https://codex.wordpress.org/WordPress_Optimization>
I took a look at your pagespeed report and the main thing there are the images you are using. There are many plugins that can optimize them for you. I like this one in particular: <https://wordpress.org/plugins/imsanity/>
As per the server cache, you can either try the popular cache plugins or ask a sysadmin to optimize these options for you on the server level.
In my case. Using Apache 2.4 I have this configuration in my pre\_virtualhost\_global.conf:
```
# Cache Control Settings for one hour cache
<FilesMatch ".(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
Header set Cache-Control "max-age=3600, public"
</FilesMatch>
<FilesMatch ".(xml|txt)$">
Header set Cache-Control "max-age=3600, public, must-revalidate"
</FilesMatch>
<FilesMatch ".(html|htm)$">
Header set Cache-Control "max-age=3600, must-revalidate"
</FilesMatch>
# Mod Deflate performs data compression
<IfModule mod_deflate.c>
<FilesMatch ".(js|css|html|php|xml|jpg|png|gif)$">
SetOutputFilter DEFLATE
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4.0[678] no-gzip
BrowserMatch bMSIE no-gzip
</FilesMatch>
</IfModule>
```
Pagespeed also offer instructions on the other factors. You should follow them.
|
216,030 |
<p>I created a custom post type "Book", and successfully added to WordPress' admin menu as a root category. I can successfully list the post type contents with <code>/wp-admin/edit.php?post_type=test_book</code> & can add via <code>/wp-admin/post-new.php?post_type=test_book</code>.</p>
<p>However, I would like to add a custom post type "Chapter" (<code>test_chapter</code>) to "Book", by allowing users to choose chapters (and re-arrange the order in <code>post-new.php</code>), thus establishing the parent-child relationship.</p>
<p>How can I do so?</p>
|
[
{
"answer_id": 216032,
"author": "AjayShanker",
"author_id": 87560,
"author_profile": "https://wordpress.stackexchange.com/users/87560",
"pm_score": -1,
"selected": false,
"text": "<p>First you create test_book function and call <code>add_action()</code> function to initialize this function.</p>\n\n<p>Example: </p>\n\n<pre><code>add_action('admin_menu', 'test_book');\n</code></pre>\n\n<p>Then after you define test_book() function functionality, for adding menu and sub-menu you declare your <code>function test_book()</code> like this manner....</p>\n\n<pre><code>function test_book(){\n add_menu_page( \"Books\", \"Books\", \"manage_options\", \"test_book\", \"test_book\", \"\" );\n add_submenu_page( \"test_book\", \"Chapters\", \"Chapters\", \"manage_options\", \"test_chapter\", \"test_chapter\");\n}\n</code></pre>\n"
},
{
"answer_id": 216059,
"author": "Silenced",
"author_id": 59029,
"author_profile": "https://wordpress.stackexchange.com/users/59029",
"pm_score": 3,
"selected": true,
"text": "<p>The code you need to use here has some steps. First you need to create e metabox on your custom post type edit.php which will list all your posts of test_chapter post type. Then you have to hook the save_post action so you set the parent of your edited post to the chosen \"test_chapter\". The best way is to connect these two post types as post meta and not as parent-child relation so you can handle it better. According to this tutorial: <a href=\"http://wptheming.com/2010/08/custom-metabox-for-post-type/\" rel=\"nofollow\">http://wptheming.com/2010/08/custom-metabox-for-post-type/</a></p>\n\n<pre><code>add_action( 'add_meta_boxes', 'add_books_metaboxes' );\n // Add the Book Meta Boxes\n\n function add_books_metaboxes() {\n add_meta_box('wpt_test_chapter', 'Book chapter', 'wpt_test_chapter', 'test_book', 'side', 'default');\n }\n\n\n// Book chapter Metabox\n\nfunction wpt_test_chapter() {\n global $post;\n\n\n $args = array(\n 'posts_per_page' => -1,\n 'post_type' => 'test_chapter',\n );\n $books_array = get_posts( $args );\n $chapter_ids = get_post_meta($post->ID, 'related_chapters', true);\n ?>\n <select name=\"book_chapters\" multiple>\n <?php\n foreach($books_array as $book_array){\n if(in_array($book_array->ID, $chapter_ids)){$selected = 'selected;'}\n else{$selected = '';}\n echo '<option '.$book_array->ID.' '.$selected.'>'.$book_array->post_title.'</option>';\n }\n ?>\n </select>\n <?php\n // Noncename needed to verify where the data originated\n /* if you are using plugin:\n echo '<input type=\"hidden\" name=\"eventmeta_noncename\" id=\"eventmeta_noncename\" value=\"' . \n wp_create_nonce( plugin_basename(__FILE__) ) . '\" />';\n */\n}\n\n\n\n// Save the Metabox Data\n\nfunction wpt_save_chapter_meta($post_id, $post) {\n\n // verify this came from the our screen and with proper authorization,\n // because save_post can be triggered at other times\n /* if you are using plugin:\n if ( !wp_verify_nonce( $_POST['eventmeta_noncename'], plugin_basename(__FILE__) )) {\n return $post->ID;\n }\n */\n // Is the user allowed to edit the post or page?\n if ( !current_user_can( 'edit_post', $post->ID ))\n return $post->ID;\n\n // OK, we're authenticated: we need to find and save the data\n // We'll put it into an array to make it easier to loop though.\n\n $chapters_ids['book_chapters'] = $_POST['book_chapters'];\n\n // Add values of $events_meta as custom fields\n\n foreach ($chapter_ids as $chapter_id) { // Cycle through the $events_meta array!\n //if( $post->post_type == 'revision' ) return; // Don't store custom data twice\n update_post_meta($post->ID, 'related_chapters', $chapter_id);\n }\n\n}\n\nadd_action('save_post', 'wpt_save_chapter_meta', 1, 2); // save the custom fields\n</code></pre>\n\n<p>Have not tested the code so it may have some mistakes. Let me knwo so I can correct them.</p>\n"
}
] |
2016/01/29
|
[
"https://wordpress.stackexchange.com/questions/216030",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3608/"
] |
I created a custom post type "Book", and successfully added to WordPress' admin menu as a root category. I can successfully list the post type contents with `/wp-admin/edit.php?post_type=test_book` & can add via `/wp-admin/post-new.php?post_type=test_book`.
However, I would like to add a custom post type "Chapter" (`test_chapter`) to "Book", by allowing users to choose chapters (and re-arrange the order in `post-new.php`), thus establishing the parent-child relationship.
How can I do so?
|
The code you need to use here has some steps. First you need to create e metabox on your custom post type edit.php which will list all your posts of test\_chapter post type. Then you have to hook the save\_post action so you set the parent of your edited post to the chosen "test\_chapter". The best way is to connect these two post types as post meta and not as parent-child relation so you can handle it better. According to this tutorial: <http://wptheming.com/2010/08/custom-metabox-for-post-type/>
```
add_action( 'add_meta_boxes', 'add_books_metaboxes' );
// Add the Book Meta Boxes
function add_books_metaboxes() {
add_meta_box('wpt_test_chapter', 'Book chapter', 'wpt_test_chapter', 'test_book', 'side', 'default');
}
// Book chapter Metabox
function wpt_test_chapter() {
global $post;
$args = array(
'posts_per_page' => -1,
'post_type' => 'test_chapter',
);
$books_array = get_posts( $args );
$chapter_ids = get_post_meta($post->ID, 'related_chapters', true);
?>
<select name="book_chapters" multiple>
<?php
foreach($books_array as $book_array){
if(in_array($book_array->ID, $chapter_ids)){$selected = 'selected;'}
else{$selected = '';}
echo '<option '.$book_array->ID.' '.$selected.'>'.$book_array->post_title.'</option>';
}
?>
</select>
<?php
// Noncename needed to verify where the data originated
/* if you are using plugin:
echo '<input type="hidden" name="eventmeta_noncename" id="eventmeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
*/
}
// Save the Metabox Data
function wpt_save_chapter_meta($post_id, $post) {
// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
/* if you are using plugin:
if ( !wp_verify_nonce( $_POST['eventmeta_noncename'], plugin_basename(__FILE__) )) {
return $post->ID;
}
*/
// Is the user allowed to edit the post or page?
if ( !current_user_can( 'edit_post', $post->ID ))
return $post->ID;
// OK, we're authenticated: we need to find and save the data
// We'll put it into an array to make it easier to loop though.
$chapters_ids['book_chapters'] = $_POST['book_chapters'];
// Add values of $events_meta as custom fields
foreach ($chapter_ids as $chapter_id) { // Cycle through the $events_meta array!
//if( $post->post_type == 'revision' ) return; // Don't store custom data twice
update_post_meta($post->ID, 'related_chapters', $chapter_id);
}
}
add_action('save_post', 'wpt_save_chapter_meta', 1, 2); // save the custom fields
```
Have not tested the code so it may have some mistakes. Let me knwo so I can correct them.
|
216,047 |
<p>I am new to PHP and I'm unable to solve the code. It's showing an error.</p>
<pre><code><?php
function thumbImg() {
if ( has_post_thumbnail() ) {
the_post_thumbnail( array(54,54) );
} else {
<img src='<?php echo $data['featured_img']; ?>' alt='<?php the_title(); ?>' />
}
}
?>
</code></pre>
<p>What I am trying to achieve is that set a fallback image for a recent post widget if there is no featured image set, so I am trying to make a function/shortcode I can use in the my recent post widget page <code>['featured_img']</code> which will get data from admin panel.</p>
|
[
{
"answer_id": 216050,
"author": "macl",
"author_id": 72784,
"author_profile": "https://wordpress.stackexchange.com/users/72784",
"pm_score": 1,
"selected": false,
"text": "<p>You are mixing html and php content. You should write it like this:</p>\n\n<pre><code><?php \n\nfunction thumbImg() {\n if ( has_post_thumbnail() ) {\n the_post_thumbnail( array(54,54) );\n } else {\n echo \"<img src='{$data['featured_img']}' alt='\".get_the_title().\"' />\";\n }\n} \n\n?>\n</code></pre>\n\n<p>This way, you don't need to open and close again the php tag.</p>\n"
},
{
"answer_id": 216442,
"author": "Zohair Baloch",
"author_id": 87965,
"author_profile": "https://wordpress.stackexchange.com/users/87965",
"pm_score": 0,
"selected": false,
"text": "<p>You need to close the PHP tag before you write html code for image source and then reopen the PHP tag once your HTML is finished.</p>\n\n<pre><code> <?php \n\nfunction thumbImg() {\n if ( has_post_thumbnail() ) {\n the_post_thumbnail( array(54,54) );\n } else {\n ?>\n <img src='<?php echo $data['featured_img']; ?>' alt='<?php the_title(); ?>' />\n <?php\n }\n} \n\n?>\n</code></pre>\n"
}
] |
2016/01/29
|
[
"https://wordpress.stackexchange.com/questions/216047",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87218/"
] |
I am new to PHP and I'm unable to solve the code. It's showing an error.
```
<?php
function thumbImg() {
if ( has_post_thumbnail() ) {
the_post_thumbnail( array(54,54) );
} else {
<img src='<?php echo $data['featured_img']; ?>' alt='<?php the_title(); ?>' />
}
}
?>
```
What I am trying to achieve is that set a fallback image for a recent post widget if there is no featured image set, so I am trying to make a function/shortcode I can use in the my recent post widget page `['featured_img']` which will get data from admin panel.
|
You are mixing html and php content. You should write it like this:
```
<?php
function thumbImg() {
if ( has_post_thumbnail() ) {
the_post_thumbnail( array(54,54) );
} else {
echo "<img src='{$data['featured_img']}' alt='".get_the_title()."' />";
}
}
?>
```
This way, you don't need to open and close again the php tag.
|
216,054 |
<p>In woocommerce plugin file <code>class-wc-booking-cart-manager.php</code> there is this code</p>
<pre><code>/**
* Constructor
*/
public function __construct() {
add_filter( 'woocommerce_add_cart_item', array( $this, 'add_cart_item' ), 10, 1 );
}
/**
* Adjust the price of the booking product based on booking properties
*
* @param mixed $cart_item
* @return array cart item
*/
public function add_cart_item( $cart_item ) {
if ( ! empty( $cart_item['booking'] ) && ! empty( $cart_item['booking']['_cost'] ) ) {
$cart_item['data']->set_price( $cart_item['booking']['_cost'] );
}
return $cart_item;
}
</code></pre>
<p>I want to change <code>add_cart_item</code> function's code into my child theme <code>functions.php</code> file. I want to know how to override this plugin function.</p>
<p>So I did this :</p>
<pre><code>remove_all_filters('woocommerce_add_cart_item');
add_filter('woocommerce_add_cart_item', 'custom_add_cart_item');
function custom_add_cart_item($cart_item) {
if (empty( $cart_item['booking'] ) && empty( $cart_item['booking']['_cost'] ) ) {
$cart_item['data']->set_price( 2000 );
}
return $cart_item;
}
</code></pre>
<p>As you can see, I'm setting price to 2000.</p>
<p>But it does not work.. Thanks for your help !</p>
|
[
{
"answer_id": 216050,
"author": "macl",
"author_id": 72784,
"author_profile": "https://wordpress.stackexchange.com/users/72784",
"pm_score": 1,
"selected": false,
"text": "<p>You are mixing html and php content. You should write it like this:</p>\n\n<pre><code><?php \n\nfunction thumbImg() {\n if ( has_post_thumbnail() ) {\n the_post_thumbnail( array(54,54) );\n } else {\n echo \"<img src='{$data['featured_img']}' alt='\".get_the_title().\"' />\";\n }\n} \n\n?>\n</code></pre>\n\n<p>This way, you don't need to open and close again the php tag.</p>\n"
},
{
"answer_id": 216442,
"author": "Zohair Baloch",
"author_id": 87965,
"author_profile": "https://wordpress.stackexchange.com/users/87965",
"pm_score": 0,
"selected": false,
"text": "<p>You need to close the PHP tag before you write html code for image source and then reopen the PHP tag once your HTML is finished.</p>\n\n<pre><code> <?php \n\nfunction thumbImg() {\n if ( has_post_thumbnail() ) {\n the_post_thumbnail( array(54,54) );\n } else {\n ?>\n <img src='<?php echo $data['featured_img']; ?>' alt='<?php the_title(); ?>' />\n <?php\n }\n} \n\n?>\n</code></pre>\n"
}
] |
2016/01/29
|
[
"https://wordpress.stackexchange.com/questions/216054",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87707/"
] |
In woocommerce plugin file `class-wc-booking-cart-manager.php` there is this code
```
/**
* Constructor
*/
public function __construct() {
add_filter( 'woocommerce_add_cart_item', array( $this, 'add_cart_item' ), 10, 1 );
}
/**
* Adjust the price of the booking product based on booking properties
*
* @param mixed $cart_item
* @return array cart item
*/
public function add_cart_item( $cart_item ) {
if ( ! empty( $cart_item['booking'] ) && ! empty( $cart_item['booking']['_cost'] ) ) {
$cart_item['data']->set_price( $cart_item['booking']['_cost'] );
}
return $cart_item;
}
```
I want to change `add_cart_item` function's code into my child theme `functions.php` file. I want to know how to override this plugin function.
So I did this :
```
remove_all_filters('woocommerce_add_cart_item');
add_filter('woocommerce_add_cart_item', 'custom_add_cart_item');
function custom_add_cart_item($cart_item) {
if (empty( $cart_item['booking'] ) && empty( $cart_item['booking']['_cost'] ) ) {
$cart_item['data']->set_price( 2000 );
}
return $cart_item;
}
```
As you can see, I'm setting price to 2000.
But it does not work.. Thanks for your help !
|
You are mixing html and php content. You should write it like this:
```
<?php
function thumbImg() {
if ( has_post_thumbnail() ) {
the_post_thumbnail( array(54,54) );
} else {
echo "<img src='{$data['featured_img']}' alt='".get_the_title()."' />";
}
}
?>
```
This way, you don't need to open and close again the php tag.
|
216,070 |
<p>in the search box I would like visitors to be able to search for more than one location (houses). The code right now is:</p>
<pre><code> <div class="col-md-3 col-sm-6 col-xs-12">
<label for="property_location"><?php _ex( 'Locatie', 'property search label', 'ci_theme' ); ?></label>
<div class="ci-select">
<?php
wp_dropdown_categories( array(
'taxonomy' => 'property_location',
'hierarchical' => true,
'show_option_none' => esc_html_x( '-', 'any property location', 'ci_theme' ),
'option_none_value' => '',
'name' => 's_property_location',
'id' => 'property_location',
'selected' => isset( $_GET['s_property_location'] ) ? $_GET['s_property_location'] : '',
) );
?>
</div>
</div>
</code></pre>
<p>How do I change this to a multiple select?</p>
<p>Thank you so much for your answer.
Carlijn</p>
|
[
{
"answer_id": 216079,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 0,
"selected": false,
"text": "<p>You can check:</p>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/wp_category_checklist\" rel=\"nofollow\">wp_category_checklist</a> You can define a custom walker and change the check-boxes to drop-down with multiple select.</p>\n\n<p><code>wp_category_checklist</code> output an unordered list of checkbox <code><input></code> elements labeled with category names. </p>\n"
},
{
"answer_id": 253403,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/wp_dropdown_categories/\" rel=\"nofollow noreferrer\"><strong><code>wp_dropdown_categories</code></strong></a> has a filter applied to the output that is called right before the function returns or echos the output.</p>\n\n<p>With this you can add a filter to your funtions.php file that manipulates the select field and adds a multiple attribute to it.</p>\n\n<p>The filter below would search for the select opening tag and add the multiple attribute to it. You can also add the size attribute to control the number of items displayed at a time.</p>\n\n<pre><code>add_filter( 'wp_dropdown_cats', 'dropdown_filter', 10, 2);\n\nfunction dropdown_filter( $output, $r ) {\n $output = preg_replace( '/<select (.*?) >/', '<select $1 size=\"5\" multiple>', $output);\n return $output;\n}\n</code></pre>\n"
},
{
"answer_id": 261094,
"author": "MahdiY",
"author_id": 105285,
"author_profile": "https://wordpress.stackexchange.com/users/105285",
"pm_score": 2,
"selected": false,
"text": "<p>Just add this code to your functions.php\n\n\n<pre><code>add_filter( 'wp_dropdown_cats', 'wp_dropdown_cats_multiple', 10, 2 );\n\nfunction wp_dropdown_cats_multiple( $output, $r ) {\n\n if( isset( $r['multiple'] ) && $r['multiple'] ) {\n\n $output = preg_replace( '/^<select/i', '<select multiple', $output );\n\n $output = str_replace( \"name='{$r['name']}'\", \"name='{$r['name']}[]'\", $output );\n\n foreach ( array_map( 'trim', explode( \",\", $r['selected'] ) ) as $value )\n $output = str_replace( \"value=\\\"{$value}\\\"\", \"value=\\\"{$value}\\\" selected\", $output );\n\n }\n\n return $output;\n}\n</code></pre>\n\n<p>And add multiple arg like below:\n \n </p>\n\n<pre><code><div class=\"ci-select\">\n <?php\n wp_dropdown_categories( array(\n 'taxonomy' => 'property_location',\n 'hierarchical' => true,\n 'show_option_none' => esc_html_x( '-', 'any property location', 'ci_theme' ),\n 'option_none_value' => '',\n 'name' => 's_property_location',\n 'id' => 'property_location',\n 'selected' => isset( $_GET['s_property_location'] ) ? $_GET['s_property_location'] : '', // e.x 86,110,786\n 'multiple' => true\n ) );\n ?>\n</div>\n</code></pre>\n\n<p></p>\n"
},
{
"answer_id": 279272,
"author": "jer0dh",
"author_id": 103755,
"author_profile": "https://wordpress.stackexchange.com/users/103755",
"pm_score": 1,
"selected": false,
"text": "<p>This is an addition to @MahdiY answer. That answer assumes the multiselect data will be in comma delimited form. I'm finding my multi select is actually an array in which case the <code>wp_dropdown_cats_multiple</code> breaks. I added a line and altered the <code>foreach</code>.</p>\n\n<pre><code>function wp_dropdown_cats_multiple( $output, $r ) {\n\n if( isset( $r['multiple'] ) && $r['multiple'] ) {\n\n $output = preg_replace( '/^<select/i', '<select multiple data-live-search=\"true\" data-style=\"btn-info\"', $output );\n\n $output = str_replace( \"name='{$r['name']}'\", \"name='{$r['name']}[]'\", $output );\n\n $selected = is_array($r['selected']) ? $r['selected'] : explode( \",\", $r['selected'] );\n foreach ( array_map( 'trim', $selected ) as $value )\n $output = str_replace( \"value=\\\"{$value}\\\"\", \"value=\\\"{$value}\\\" selected\", $output );\n\n }\n\n return $output;\n}\n</code></pre>\n\n<p>Couldn't add this as a comment as my reputation is too low.</p>\n"
}
] |
2016/01/29
|
[
"https://wordpress.stackexchange.com/questions/216070",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87719/"
] |
in the search box I would like visitors to be able to search for more than one location (houses). The code right now is:
```
<div class="col-md-3 col-sm-6 col-xs-12">
<label for="property_location"><?php _ex( 'Locatie', 'property search label', 'ci_theme' ); ?></label>
<div class="ci-select">
<?php
wp_dropdown_categories( array(
'taxonomy' => 'property_location',
'hierarchical' => true,
'show_option_none' => esc_html_x( '-', 'any property location', 'ci_theme' ),
'option_none_value' => '',
'name' => 's_property_location',
'id' => 'property_location',
'selected' => isset( $_GET['s_property_location'] ) ? $_GET['s_property_location'] : '',
) );
?>
</div>
</div>
```
How do I change this to a multiple select?
Thank you so much for your answer.
Carlijn
|
[**`wp_dropdown_categories`**](https://developer.wordpress.org/reference/functions/wp_dropdown_categories/) has a filter applied to the output that is called right before the function returns or echos the output.
With this you can add a filter to your funtions.php file that manipulates the select field and adds a multiple attribute to it.
The filter below would search for the select opening tag and add the multiple attribute to it. You can also add the size attribute to control the number of items displayed at a time.
```
add_filter( 'wp_dropdown_cats', 'dropdown_filter', 10, 2);
function dropdown_filter( $output, $r ) {
$output = preg_replace( '/<select (.*?) >/', '<select $1 size="5" multiple>', $output);
return $output;
}
```
|
216,084 |
<p>I've a wordpress installation at mytld.com. So far the primary intent was to run a blog and my posts are in the format mytld.com/y/m/postname.</p>
<p>Now I want to shift the blog under a new URL structure mytld.com/blog/y/m/postname and instead setup a website under mytld.com by using wordpress pages.</p>
<p>I'm looking for suggestions / best strategy for the most effective way to do this. Also what .htaccess rules do I have to introduce to redirect all /y/m/postname --> /blog/y/m/postname so that I don't loose any link juice.</p>
<p>Thank you.</p>
|
[
{
"answer_id": 216079,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 0,
"selected": false,
"text": "<p>You can check:</p>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/wp_category_checklist\" rel=\"nofollow\">wp_category_checklist</a> You can define a custom walker and change the check-boxes to drop-down with multiple select.</p>\n\n<p><code>wp_category_checklist</code> output an unordered list of checkbox <code><input></code> elements labeled with category names. </p>\n"
},
{
"answer_id": 253403,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/wp_dropdown_categories/\" rel=\"nofollow noreferrer\"><strong><code>wp_dropdown_categories</code></strong></a> has a filter applied to the output that is called right before the function returns or echos the output.</p>\n\n<p>With this you can add a filter to your funtions.php file that manipulates the select field and adds a multiple attribute to it.</p>\n\n<p>The filter below would search for the select opening tag and add the multiple attribute to it. You can also add the size attribute to control the number of items displayed at a time.</p>\n\n<pre><code>add_filter( 'wp_dropdown_cats', 'dropdown_filter', 10, 2);\n\nfunction dropdown_filter( $output, $r ) {\n $output = preg_replace( '/<select (.*?) >/', '<select $1 size=\"5\" multiple>', $output);\n return $output;\n}\n</code></pre>\n"
},
{
"answer_id": 261094,
"author": "MahdiY",
"author_id": 105285,
"author_profile": "https://wordpress.stackexchange.com/users/105285",
"pm_score": 2,
"selected": false,
"text": "<p>Just add this code to your functions.php\n\n\n<pre><code>add_filter( 'wp_dropdown_cats', 'wp_dropdown_cats_multiple', 10, 2 );\n\nfunction wp_dropdown_cats_multiple( $output, $r ) {\n\n if( isset( $r['multiple'] ) && $r['multiple'] ) {\n\n $output = preg_replace( '/^<select/i', '<select multiple', $output );\n\n $output = str_replace( \"name='{$r['name']}'\", \"name='{$r['name']}[]'\", $output );\n\n foreach ( array_map( 'trim', explode( \",\", $r['selected'] ) ) as $value )\n $output = str_replace( \"value=\\\"{$value}\\\"\", \"value=\\\"{$value}\\\" selected\", $output );\n\n }\n\n return $output;\n}\n</code></pre>\n\n<p>And add multiple arg like below:\n \n </p>\n\n<pre><code><div class=\"ci-select\">\n <?php\n wp_dropdown_categories( array(\n 'taxonomy' => 'property_location',\n 'hierarchical' => true,\n 'show_option_none' => esc_html_x( '-', 'any property location', 'ci_theme' ),\n 'option_none_value' => '',\n 'name' => 's_property_location',\n 'id' => 'property_location',\n 'selected' => isset( $_GET['s_property_location'] ) ? $_GET['s_property_location'] : '', // e.x 86,110,786\n 'multiple' => true\n ) );\n ?>\n</div>\n</code></pre>\n\n<p></p>\n"
},
{
"answer_id": 279272,
"author": "jer0dh",
"author_id": 103755,
"author_profile": "https://wordpress.stackexchange.com/users/103755",
"pm_score": 1,
"selected": false,
"text": "<p>This is an addition to @MahdiY answer. That answer assumes the multiselect data will be in comma delimited form. I'm finding my multi select is actually an array in which case the <code>wp_dropdown_cats_multiple</code> breaks. I added a line and altered the <code>foreach</code>.</p>\n\n<pre><code>function wp_dropdown_cats_multiple( $output, $r ) {\n\n if( isset( $r['multiple'] ) && $r['multiple'] ) {\n\n $output = preg_replace( '/^<select/i', '<select multiple data-live-search=\"true\" data-style=\"btn-info\"', $output );\n\n $output = str_replace( \"name='{$r['name']}'\", \"name='{$r['name']}[]'\", $output );\n\n $selected = is_array($r['selected']) ? $r['selected'] : explode( \",\", $r['selected'] );\n foreach ( array_map( 'trim', $selected ) as $value )\n $output = str_replace( \"value=\\\"{$value}\\\"\", \"value=\\\"{$value}\\\" selected\", $output );\n\n }\n\n return $output;\n}\n</code></pre>\n\n<p>Couldn't add this as a comment as my reputation is too low.</p>\n"
}
] |
2016/01/29
|
[
"https://wordpress.stackexchange.com/questions/216084",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/5195/"
] |
I've a wordpress installation at mytld.com. So far the primary intent was to run a blog and my posts are in the format mytld.com/y/m/postname.
Now I want to shift the blog under a new URL structure mytld.com/blog/y/m/postname and instead setup a website under mytld.com by using wordpress pages.
I'm looking for suggestions / best strategy for the most effective way to do this. Also what .htaccess rules do I have to introduce to redirect all /y/m/postname --> /blog/y/m/postname so that I don't loose any link juice.
Thank you.
|
[**`wp_dropdown_categories`**](https://developer.wordpress.org/reference/functions/wp_dropdown_categories/) has a filter applied to the output that is called right before the function returns or echos the output.
With this you can add a filter to your funtions.php file that manipulates the select field and adds a multiple attribute to it.
The filter below would search for the select opening tag and add the multiple attribute to it. You can also add the size attribute to control the number of items displayed at a time.
```
add_filter( 'wp_dropdown_cats', 'dropdown_filter', 10, 2);
function dropdown_filter( $output, $r ) {
$output = preg_replace( '/<select (.*?) >/', '<select $1 size="5" multiple>', $output);
return $output;
}
```
|
216,115 |
<p>I'm trying to make my blog posts show an excerpt but can't seem to do it manually. <a href="http://averylawoffice.ca/blog" rel="nofollow">My blog site is here</a>.</p>
<p>I've gotten this snippet from the wordpress.org site</p>
<pre><code><?php the_excerpt(); ?>
</code></pre>
<p>and it tells me to replace the </p>
<pre><code><?php the_content(); ?>
</code></pre>
<p>with it. However I can't just replace it my index.php file as then it excerpts everything. (Maybe because of how my index.php file is set up?) </p>
<pre><code><?php
/**
* The main template file.
*/
get_header(); ?>
<div id="main">
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<?php endwhile; // end of the loop. ?>
<?php if (function_exists("pagination")) {
pagination($additional_loop->max_num_pages);
} ?>
</div><!-- #main -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
</code></pre>
<p>I've tried to replace the have_posts() and then replace the second line of code and then even alter this lines:</p>
<p>and I get my excerpt under my post in my post but then it makes my website REALLY slow.</p>
<p>For some reason my choices for only showing summary in Settings > Review don't apply so I'm having to do it manually. </p>
<p>Any help is appreciated as to how I can customize this excerpt code to work with my blog.</p>
<h2>UPDATED</h2>
<p>As Linnea suggested I have updated the content-page.php page to this:</p>
<pre><code><?php
/**
* The template used for displaying separate posts on blog page.
*
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<span class="entry-header">
<h1 class="blog entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<h2 class="blog entry-subtitle">Posted on: <?php the_time('F j, Y'); ?></h2>
</span><!-- .entry-header -->
<div class="entry-content">
<?php the_excerpt(); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'toolbox' ), 'after' => '</div>' ) ); ?>
<?php edit_post_link( __( 'Edit', 'toolbox' ), '<span class="edit-link">', '</span>' ); ?>
</div><!-- .entry-content -->
</article><!-- #post-<?php the_ID(); ?> -->
</code></pre>
<p>Where the <code><?php the_excerpt(); ?></code> is now used to be <code><?php the_content('<br/><br/>CONTINUE READING...'); ?></code> however there is no change to my blog entries on my blog. Maybe there is another area I should be looking?</p>
|
[
{
"answer_id": 216079,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 0,
"selected": false,
"text": "<p>You can check:</p>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/wp_category_checklist\" rel=\"nofollow\">wp_category_checklist</a> You can define a custom walker and change the check-boxes to drop-down with multiple select.</p>\n\n<p><code>wp_category_checklist</code> output an unordered list of checkbox <code><input></code> elements labeled with category names. </p>\n"
},
{
"answer_id": 253403,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/wp_dropdown_categories/\" rel=\"nofollow noreferrer\"><strong><code>wp_dropdown_categories</code></strong></a> has a filter applied to the output that is called right before the function returns or echos the output.</p>\n\n<p>With this you can add a filter to your funtions.php file that manipulates the select field and adds a multiple attribute to it.</p>\n\n<p>The filter below would search for the select opening tag and add the multiple attribute to it. You can also add the size attribute to control the number of items displayed at a time.</p>\n\n<pre><code>add_filter( 'wp_dropdown_cats', 'dropdown_filter', 10, 2);\n\nfunction dropdown_filter( $output, $r ) {\n $output = preg_replace( '/<select (.*?) >/', '<select $1 size=\"5\" multiple>', $output);\n return $output;\n}\n</code></pre>\n"
},
{
"answer_id": 261094,
"author": "MahdiY",
"author_id": 105285,
"author_profile": "https://wordpress.stackexchange.com/users/105285",
"pm_score": 2,
"selected": false,
"text": "<p>Just add this code to your functions.php\n\n\n<pre><code>add_filter( 'wp_dropdown_cats', 'wp_dropdown_cats_multiple', 10, 2 );\n\nfunction wp_dropdown_cats_multiple( $output, $r ) {\n\n if( isset( $r['multiple'] ) && $r['multiple'] ) {\n\n $output = preg_replace( '/^<select/i', '<select multiple', $output );\n\n $output = str_replace( \"name='{$r['name']}'\", \"name='{$r['name']}[]'\", $output );\n\n foreach ( array_map( 'trim', explode( \",\", $r['selected'] ) ) as $value )\n $output = str_replace( \"value=\\\"{$value}\\\"\", \"value=\\\"{$value}\\\" selected\", $output );\n\n }\n\n return $output;\n}\n</code></pre>\n\n<p>And add multiple arg like below:\n \n </p>\n\n<pre><code><div class=\"ci-select\">\n <?php\n wp_dropdown_categories( array(\n 'taxonomy' => 'property_location',\n 'hierarchical' => true,\n 'show_option_none' => esc_html_x( '-', 'any property location', 'ci_theme' ),\n 'option_none_value' => '',\n 'name' => 's_property_location',\n 'id' => 'property_location',\n 'selected' => isset( $_GET['s_property_location'] ) ? $_GET['s_property_location'] : '', // e.x 86,110,786\n 'multiple' => true\n ) );\n ?>\n</div>\n</code></pre>\n\n<p></p>\n"
},
{
"answer_id": 279272,
"author": "jer0dh",
"author_id": 103755,
"author_profile": "https://wordpress.stackexchange.com/users/103755",
"pm_score": 1,
"selected": false,
"text": "<p>This is an addition to @MahdiY answer. That answer assumes the multiselect data will be in comma delimited form. I'm finding my multi select is actually an array in which case the <code>wp_dropdown_cats_multiple</code> breaks. I added a line and altered the <code>foreach</code>.</p>\n\n<pre><code>function wp_dropdown_cats_multiple( $output, $r ) {\n\n if( isset( $r['multiple'] ) && $r['multiple'] ) {\n\n $output = preg_replace( '/^<select/i', '<select multiple data-live-search=\"true\" data-style=\"btn-info\"', $output );\n\n $output = str_replace( \"name='{$r['name']}'\", \"name='{$r['name']}[]'\", $output );\n\n $selected = is_array($r['selected']) ? $r['selected'] : explode( \",\", $r['selected'] );\n foreach ( array_map( 'trim', $selected ) as $value )\n $output = str_replace( \"value=\\\"{$value}\\\"\", \"value=\\\"{$value}\\\" selected\", $output );\n\n }\n\n return $output;\n}\n</code></pre>\n\n<p>Couldn't add this as a comment as my reputation is too low.</p>\n"
}
] |
2016/01/29
|
[
"https://wordpress.stackexchange.com/questions/216115",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25108/"
] |
I'm trying to make my blog posts show an excerpt but can't seem to do it manually. [My blog site is here](http://averylawoffice.ca/blog).
I've gotten this snippet from the wordpress.org site
```
<?php the_excerpt(); ?>
```
and it tells me to replace the
```
<?php the_content(); ?>
```
with it. However I can't just replace it my index.php file as then it excerpts everything. (Maybe because of how my index.php file is set up?)
```
<?php
/**
* The main template file.
*/
get_header(); ?>
<div id="main">
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<?php endwhile; // end of the loop. ?>
<?php if (function_exists("pagination")) {
pagination($additional_loop->max_num_pages);
} ?>
</div><!-- #main -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
```
I've tried to replace the have\_posts() and then replace the second line of code and then even alter this lines:
and I get my excerpt under my post in my post but then it makes my website REALLY slow.
For some reason my choices for only showing summary in Settings > Review don't apply so I'm having to do it manually.
Any help is appreciated as to how I can customize this excerpt code to work with my blog.
UPDATED
-------
As Linnea suggested I have updated the content-page.php page to this:
```
<?php
/**
* The template used for displaying separate posts on blog page.
*
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<span class="entry-header">
<h1 class="blog entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<h2 class="blog entry-subtitle">Posted on: <?php the_time('F j, Y'); ?></h2>
</span><!-- .entry-header -->
<div class="entry-content">
<?php the_excerpt(); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'toolbox' ), 'after' => '</div>' ) ); ?>
<?php edit_post_link( __( 'Edit', 'toolbox' ), '<span class="edit-link">', '</span>' ); ?>
</div><!-- .entry-content -->
</article><!-- #post-<?php the_ID(); ?> -->
```
Where the `<?php the_excerpt(); ?>` is now used to be `<?php the_content('<br/><br/>CONTINUE READING...'); ?>` however there is no change to my blog entries on my blog. Maybe there is another area I should be looking?
|
[**`wp_dropdown_categories`**](https://developer.wordpress.org/reference/functions/wp_dropdown_categories/) has a filter applied to the output that is called right before the function returns or echos the output.
With this you can add a filter to your funtions.php file that manipulates the select field and adds a multiple attribute to it.
The filter below would search for the select opening tag and add the multiple attribute to it. You can also add the size attribute to control the number of items displayed at a time.
```
add_filter( 'wp_dropdown_cats', 'dropdown_filter', 10, 2);
function dropdown_filter( $output, $r ) {
$output = preg_replace( '/<select (.*?) >/', '<select $1 size="5" multiple>', $output);
return $output;
}
```
|
216,127 |
<p>I cannot find WP_Query() in my wordpress folder, the global refers to $wp_query but I don't find the class itself. From my wordpress folder, or here directly : <a href="https://core.trac.wordpress.org/browser/tags/4.4.1/src/wp-includes?order=name" rel="nofollow">https://core.trac.wordpress.org/browser/tags/4.4.1/src/wp-includes?order=name</a></p>
|
[
{
"answer_id": 216079,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 0,
"selected": false,
"text": "<p>You can check:</p>\n\n<p><a href=\"http://codex.wordpress.org/Function_Reference/wp_category_checklist\" rel=\"nofollow\">wp_category_checklist</a> You can define a custom walker and change the check-boxes to drop-down with multiple select.</p>\n\n<p><code>wp_category_checklist</code> output an unordered list of checkbox <code><input></code> elements labeled with category names. </p>\n"
},
{
"answer_id": 253403,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/wp_dropdown_categories/\" rel=\"nofollow noreferrer\"><strong><code>wp_dropdown_categories</code></strong></a> has a filter applied to the output that is called right before the function returns or echos the output.</p>\n\n<p>With this you can add a filter to your funtions.php file that manipulates the select field and adds a multiple attribute to it.</p>\n\n<p>The filter below would search for the select opening tag and add the multiple attribute to it. You can also add the size attribute to control the number of items displayed at a time.</p>\n\n<pre><code>add_filter( 'wp_dropdown_cats', 'dropdown_filter', 10, 2);\n\nfunction dropdown_filter( $output, $r ) {\n $output = preg_replace( '/<select (.*?) >/', '<select $1 size=\"5\" multiple>', $output);\n return $output;\n}\n</code></pre>\n"
},
{
"answer_id": 261094,
"author": "MahdiY",
"author_id": 105285,
"author_profile": "https://wordpress.stackexchange.com/users/105285",
"pm_score": 2,
"selected": false,
"text": "<p>Just add this code to your functions.php\n\n\n<pre><code>add_filter( 'wp_dropdown_cats', 'wp_dropdown_cats_multiple', 10, 2 );\n\nfunction wp_dropdown_cats_multiple( $output, $r ) {\n\n if( isset( $r['multiple'] ) && $r['multiple'] ) {\n\n $output = preg_replace( '/^<select/i', '<select multiple', $output );\n\n $output = str_replace( \"name='{$r['name']}'\", \"name='{$r['name']}[]'\", $output );\n\n foreach ( array_map( 'trim', explode( \",\", $r['selected'] ) ) as $value )\n $output = str_replace( \"value=\\\"{$value}\\\"\", \"value=\\\"{$value}\\\" selected\", $output );\n\n }\n\n return $output;\n}\n</code></pre>\n\n<p>And add multiple arg like below:\n \n </p>\n\n<pre><code><div class=\"ci-select\">\n <?php\n wp_dropdown_categories( array(\n 'taxonomy' => 'property_location',\n 'hierarchical' => true,\n 'show_option_none' => esc_html_x( '-', 'any property location', 'ci_theme' ),\n 'option_none_value' => '',\n 'name' => 's_property_location',\n 'id' => 'property_location',\n 'selected' => isset( $_GET['s_property_location'] ) ? $_GET['s_property_location'] : '', // e.x 86,110,786\n 'multiple' => true\n ) );\n ?>\n</div>\n</code></pre>\n\n<p></p>\n"
},
{
"answer_id": 279272,
"author": "jer0dh",
"author_id": 103755,
"author_profile": "https://wordpress.stackexchange.com/users/103755",
"pm_score": 1,
"selected": false,
"text": "<p>This is an addition to @MahdiY answer. That answer assumes the multiselect data will be in comma delimited form. I'm finding my multi select is actually an array in which case the <code>wp_dropdown_cats_multiple</code> breaks. I added a line and altered the <code>foreach</code>.</p>\n\n<pre><code>function wp_dropdown_cats_multiple( $output, $r ) {\n\n if( isset( $r['multiple'] ) && $r['multiple'] ) {\n\n $output = preg_replace( '/^<select/i', '<select multiple data-live-search=\"true\" data-style=\"btn-info\"', $output );\n\n $output = str_replace( \"name='{$r['name']}'\", \"name='{$r['name']}[]'\", $output );\n\n $selected = is_array($r['selected']) ? $r['selected'] : explode( \",\", $r['selected'] );\n foreach ( array_map( 'trim', $selected ) as $value )\n $output = str_replace( \"value=\\\"{$value}\\\"\", \"value=\\\"{$value}\\\" selected\", $output );\n\n }\n\n return $output;\n}\n</code></pre>\n\n<p>Couldn't add this as a comment as my reputation is too low.</p>\n"
}
] |
2016/01/30
|
[
"https://wordpress.stackexchange.com/questions/216127",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8432/"
] |
I cannot find WP\_Query() in my wordpress folder, the global refers to $wp\_query but I don't find the class itself. From my wordpress folder, or here directly : <https://core.trac.wordpress.org/browser/tags/4.4.1/src/wp-includes?order=name>
|
[**`wp_dropdown_categories`**](https://developer.wordpress.org/reference/functions/wp_dropdown_categories/) has a filter applied to the output that is called right before the function returns or echos the output.
With this you can add a filter to your funtions.php file that manipulates the select field and adds a multiple attribute to it.
The filter below would search for the select opening tag and add the multiple attribute to it. You can also add the size attribute to control the number of items displayed at a time.
```
add_filter( 'wp_dropdown_cats', 'dropdown_filter', 10, 2);
function dropdown_filter( $output, $r ) {
$output = preg_replace( '/<select (.*?) >/', '<select $1 size="5" multiple>', $output);
return $output;
}
```
|
216,135 |
<h2>UPDATE -Feb 2</h2>
<p>I've recently brought it back over to a testing server instead of a localhost environment. The address is <a href="http://onlinewebdraft.com/nuggettesting/" rel="nofollow noreferrer">http://onlinewebdraft.com/nuggettesting/</a></p>
<p>I have renamed my plugins folder and my genesis and genesis child folders to deactivate them but I still get nothing. </p>
<p><a href="https://i.stack.imgur.com/bp1Lc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bp1Lc.png" alt="enter image description here"></a></p>
<p>This one is a doozy and I'm willing to offer some points for the right answer (I can do that right?).</p>
<p>I had a website up (no point giving the link as it's just a landing page right now) and something happened to it. It was just a blank page when you visited it. It's a website I put up in the spring for my parent business, so thankfully they understand and I can work on trying to figure this out. </p>
<p>Steps I took to see if I could get it back up and running (as I have all my files and info on my server and can see it via ftp) is:</p>
<ul>
<li>Deactivate all plugins</li>
<li>Deactivated/Deleted my custom theme (Genesis framework & Back Country theme for those of you who know Genesis) </li>
<li>Renamed my .htaccess file</li>
</ul>
<p>I'm not really quite sure what is happening so I though if I were to take a copy of my files and backup my database to my local server and set it up locally then I could further diagnose what might be happening to this website. However I can't seem to figure out why my wp-admin isn't coming up or for that matter anything. </p>
<p><a href="http://www.wpbeginner.com/wp-tutorials/how-to-move-live-wordpress-site-to-local-server/" rel="nofollow noreferrer">I've followed the steps here</a> in order to get a backup of the files I have on my local server.</p>
<p>When I try to bring it up on my localhost all I get is "This webpage is not available".</p>
<p><a href="https://i.stack.imgur.com/CYbOd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CYbOd.png" alt="enter image description here"></a></p>
<p>I know my localhost is up and running as I check out any other localhost web sites I have and everything is running fine.</p>
<p>I've checked my error_log and these are the last couple thigns it's been complaining about</p>
<pre><code>[15-Jan-2016 11:41:01 UTC] WordPress database error Got error 28 from storage engine for query SELECT t.*, tt.* FROM ng_terms AS t INNER JOIN ng_term_taxonomy AS tt ON tt.term_id = t.term_id INNER JOIN ng_term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ('category') AND tr.object_id IN (134) ORDER BY t.name ASC made by require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'), include('/themes/genesis/page.php'), genesis, get_header, locate_template, load_template, require_once('/themes/genesis/header.php'), wp_head, do_action('wp_head'), call_user_func_array, WPSEO_Frontend->head, do_action('wpseo_head'), call_user_func_array, WPSEO_OpenGraph->opengraph, do_action('wpseo_opengraph'), call_user_func_array, WPSEO_OpenGraph->category, get_the_category, get_the_terms, wp_get_object_terms
[25-Jan-2016 19:53:28 UTC] PHP Fatal error: Call to undefined function get_term_meta() in /home3/ambergoo/public_html/nuggetcity/wp-content/themes/genesis/lib/admin/term-meta.php on line 253
</code></pre>
<p>I have all my tables imported into my localhost database, I've renamed my htaccess file, renamed my plugins folder and deleted everything but the twenty twelvetheme in my localhost server so I'm not sure what else I can do? </p>
<p>I hope this is enough information to get some direction as to what might be happening as I do not have a backup of the site (the only website of the few I have that doesn't have a backup of course!). </p>
<p>ANY help is appreciated. I'm desperate. </p>
<h2>UPDATED</h2>
<p>Still no luck. I've started with a fresh install even and removed all but one theme (now I've added a NEW genesis framework and backcountry theme (what I had before) but I have no way of hooking it up as I can't get to the front end.. </p>
<p>Here is a screenshot of my initial setup.</p>
<p><a href="https://i.stack.imgur.com/5bxvP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5bxvP.png" alt="enter image description here"></a></p>
<p>I don't understand it but whatever I do I can't seem to connect my front end to the content and information I see in the correctly chosen database from my wp-config.php file. I know the info is in there as this is the database and the tables I'm trying to call.</p>
<p><a href="https://i.stack.imgur.com/vQNNZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vQNNZ.png" alt="enter image description here"></a></p>
<h2>UPDATED - as per a comment from BillK</h2>
<p>I'm able to visit any other localhost site but my nuggetcity one. </p>
<p>nuggetcity
<a href="https://i.stack.imgur.com/uIIIm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uIIIm.png" alt="enter image description here"></a></p>
<p>another one in the same directory
<a href="https://i.stack.imgur.com/mlLS4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mlLS4.jpg" alt="enter image description here"></a></p>
<h2>UPDATED - as per a comment from AddWeb Solution Pvt Ltd</h2>
<p>Here is a snippet from m y apache error log</p>
<pre><code><IfModule> section
[Fri Jan 29 16:35:30 2016] [error] [client ::1] script '/Applications/MAMP/htdocs/index.php' not found or unable to stat
[Fri Jan 29 16:36:08 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Fri Jan 29 16:36:08 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Fri Jan 29 16:36:14 2016] [error] [client ::1] script '/Applications/MAMP/htdocs/index.php' not found or unable to stat
[Fri Jan 29 16:50:40 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Fri Jan 29 16:50:40 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Fri Jan 29 16:56:51 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Fri Jan 29 16:56:51 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Fri Jan 29 16:57:15 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Fri Jan 29 16:57:15 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Fri Jan 29 17:02:16 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Fri Jan 29 17:02:16 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Fri Jan 29 17:03:12 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Fri Jan 29 17:03:12 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Fri Jan 29 19:18:38 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Fri Jan 29 19:18:38 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Fri Jan 29 19:35:48 2016] [notice] caught SIGTERM, shutting down
[Fri Jan 29 21:00:44 2016] [notice] Digest: generating secret for digest authentication ...
[Fri Jan 29 21:00:44 2016] [notice] Digest: done
[Fri Jan 29 21:00:44 2016] [notice] Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8y DAV/2 PHP/5.3.6 configured -- resuming normal operations
[Fri Jan 29 21:01:34 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Fri Jan 29 21:01:34 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
sh: /usr/local/bin/zip: No such file or directory
sh: /usr/local/bin/unzip: No such file or directory
[Sun Jan 31 16:46:33 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Sun Jan 31 16:46:33 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Tue Feb 02 16:08:25 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Tue Feb 02 16:08:26 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Tue Feb 02 16:12:15 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Tue Feb 02 16:12:15 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Tue Feb 02 16:12:15 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Tue Feb 02 16:12:15 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Tue Feb 02 16:12:26 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Tue Feb 02 16:12:26 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Tue Feb 02 16:17:53 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Tue Feb 02 16:17:53 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
</code></pre>
|
[
{
"answer_id": 216139,
"author": "Emanuel Rocha Costa",
"author_id": 75873,
"author_profile": "https://wordpress.stackexchange.com/users/75873",
"pm_score": -1,
"selected": false,
"text": "<p>Try remove the genesis theme folder and see what happens. Make sure you have the default WordPress theme folders under /wp-content/themes/</p>\n"
},
{
"answer_id": 216155,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 0,
"selected": false,
"text": "<p><strong>For error:</strong> <em>WordPress database error Got error 28 from storage engine</em>\n<em>Solution:</em> The error come when MySQL doesn't have any free hard disk space to write to. Check your <code>/tmp</code> directory, that's where I had run into problems. Once clear and restarting mysql should look working.</p>\n\n<p>You can check disk space via command line:</p>\n\n<pre><code>myServer# df -h\n</code></pre>\n\n<p>Don't forgot to check <code>.htaccess</code> file. Compare and correct it with your domain.</p>\n\n<p><strong>For error:</strong> <em>PHP Fatal error: Call to undefined function <code>get_term_meta()</code></em>\n<em>Solution:</em> Check for your <em>genesis</em> update where as in your case you removed it but you need to update it whenever you use.</p>\n\n<p><strong>Basic <code>.htaccess</code> content like</strong>:\nYour server log says : </p>\n\n<blockquote>\n <p>[Tue Feb 02 16:17:53 2016] [alert] [client ::1]\n /Applications/MAMP/htdocs/2016/superclean/.htaccess: \n without matching section</p>\n</blockquote>\n\n<p>Without check your <code>.htaccess</code> file code, I can suggest you: </p>\n\n<p><strong>1.</strong> Either try deleting/renaming your .htaccess file.<br>\n<strong>2.</strong> OR replace your <code>.htaccess</code> content with below basic content. </p>\n\n<pre><code># BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n\n# END WordPress\n</code></pre>\n\n<p>You can share you <code>.htaccess</code> code if above any option not working. So we can drill down for proper solution.</p>\n\n<p>Let me know if there is any concern from above!</p>\n"
},
{
"answer_id": 216392,
"author": "BillK",
"author_id": 87352,
"author_profile": "https://wordpress.stackexchange.com/users/87352",
"pm_score": 0,
"selected": false,
"text": "<p>The message displayed by Chrome in your screen shot indicates the problem is more likely a network / server issue than a problem with the website. The puzzling part is you say you can open other sites on localhost. Do you access those sites the same way i.e <code>localhost/someotherdir</code>?</p>\n\n<p>What happens if you type <code>http://127.0.0.1/2016/nuggetcity</code>?</p>\n\n<p>Look for error messages in Chrome's developer tools / console.</p>\n\n<p>Check .htaccess files in the server's root directory.</p>\n"
},
{
"answer_id": 216541,
"author": "kia4567",
"author_id": 25108,
"author_profile": "https://wordpress.stackexchange.com/users/25108",
"pm_score": 1,
"selected": true,
"text": "<p>I have found out how to fix it but can't seem to find out what caused it. The website was fairly new and was launched on April 20th, 2015. Not many updates had been done so maybe thats why?</p>\n\n<p>Someone had suggested that I replace all instances of the wordpress core files (except wp-config.php and wp-content as these are important for your website and without them you don't have your custom website).</p>\n\n<p>So you:</p>\n\n<ul>\n<li>Go to <a href=\"http://www.wordpress.org\" rel=\"nofollow\">wordpress.org</a> and download the latest copy of wordpress</li>\n<li>Unzip the folder and extract the files</li>\n<li>Visit your website (I had a copy of my files on a different server to play with and test - i manually moved it over with the <a href=\"http://www.wpexplorer.com/migrating-wordpress-website/\" rel=\"nofollow\">help of this article</a> but don't forget to <a href=\"https://wpbeaches.com/updating-wordpress-mysql-database-after-moving-to-a-new-url/\" rel=\"nofollow\">change your URL's</a>)</li>\n<li>Replace every file and folder (except wp-config.php and wp-content) with a fresh install of wordpress</li>\n<li>Follow the rest of the steps in the <a href=\"http://www.wpexplorer.com/migrating-wordpress-website/\" rel=\"nofollow\">manual migration article</a> I referenced earlier. Don't forget about the URL change if you moved to another server for testing.</li>\n<li>Refresh the page where your wordpress website should be</li>\n<li>You may get a wordpress notification about repairing the database, run the repair and all should be good.</li>\n</ul>\n\n<p>So I was able to do this on the test site I put up earlier and then after visiting the site and repairing the database all was well.</p>\n\n<p>I'm not quite sure now what caused the white screen of death, but a fresh update of wordpress did the trick.</p>\n\n<p>So now, either install your backup plugin (I use Backup Buddy) or manually migrate these files back over (in the same fashion) to your actual website server.</p>\n\n<p>Hope this ends up helping someone.</p>\n"
}
] |
2016/01/30
|
[
"https://wordpress.stackexchange.com/questions/216135",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25108/"
] |
UPDATE -Feb 2
-------------
I've recently brought it back over to a testing server instead of a localhost environment. The address is <http://onlinewebdraft.com/nuggettesting/>
I have renamed my plugins folder and my genesis and genesis child folders to deactivate them but I still get nothing.
[](https://i.stack.imgur.com/bp1Lc.png)
This one is a doozy and I'm willing to offer some points for the right answer (I can do that right?).
I had a website up (no point giving the link as it's just a landing page right now) and something happened to it. It was just a blank page when you visited it. It's a website I put up in the spring for my parent business, so thankfully they understand and I can work on trying to figure this out.
Steps I took to see if I could get it back up and running (as I have all my files and info on my server and can see it via ftp) is:
* Deactivate all plugins
* Deactivated/Deleted my custom theme (Genesis framework & Back Country theme for those of you who know Genesis)
* Renamed my .htaccess file
I'm not really quite sure what is happening so I though if I were to take a copy of my files and backup my database to my local server and set it up locally then I could further diagnose what might be happening to this website. However I can't seem to figure out why my wp-admin isn't coming up or for that matter anything.
[I've followed the steps here](http://www.wpbeginner.com/wp-tutorials/how-to-move-live-wordpress-site-to-local-server/) in order to get a backup of the files I have on my local server.
When I try to bring it up on my localhost all I get is "This webpage is not available".
[](https://i.stack.imgur.com/CYbOd.png)
I know my localhost is up and running as I check out any other localhost web sites I have and everything is running fine.
I've checked my error\_log and these are the last couple thigns it's been complaining about
```
[15-Jan-2016 11:41:01 UTC] WordPress database error Got error 28 from storage engine for query SELECT t.*, tt.* FROM ng_terms AS t INNER JOIN ng_term_taxonomy AS tt ON tt.term_id = t.term_id INNER JOIN ng_term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ('category') AND tr.object_id IN (134) ORDER BY t.name ASC made by require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'), include('/themes/genesis/page.php'), genesis, get_header, locate_template, load_template, require_once('/themes/genesis/header.php'), wp_head, do_action('wp_head'), call_user_func_array, WPSEO_Frontend->head, do_action('wpseo_head'), call_user_func_array, WPSEO_OpenGraph->opengraph, do_action('wpseo_opengraph'), call_user_func_array, WPSEO_OpenGraph->category, get_the_category, get_the_terms, wp_get_object_terms
[25-Jan-2016 19:53:28 UTC] PHP Fatal error: Call to undefined function get_term_meta() in /home3/ambergoo/public_html/nuggetcity/wp-content/themes/genesis/lib/admin/term-meta.php on line 253
```
I have all my tables imported into my localhost database, I've renamed my htaccess file, renamed my plugins folder and deleted everything but the twenty twelvetheme in my localhost server so I'm not sure what else I can do?
I hope this is enough information to get some direction as to what might be happening as I do not have a backup of the site (the only website of the few I have that doesn't have a backup of course!).
ANY help is appreciated. I'm desperate.
UPDATED
-------
Still no luck. I've started with a fresh install even and removed all but one theme (now I've added a NEW genesis framework and backcountry theme (what I had before) but I have no way of hooking it up as I can't get to the front end..
Here is a screenshot of my initial setup.
[](https://i.stack.imgur.com/5bxvP.png)
I don't understand it but whatever I do I can't seem to connect my front end to the content and information I see in the correctly chosen database from my wp-config.php file. I know the info is in there as this is the database and the tables I'm trying to call.
[](https://i.stack.imgur.com/vQNNZ.png)
UPDATED - as per a comment from BillK
-------------------------------------
I'm able to visit any other localhost site but my nuggetcity one.
nuggetcity
[](https://i.stack.imgur.com/uIIIm.png)
another one in the same directory
[](https://i.stack.imgur.com/mlLS4.jpg)
UPDATED - as per a comment from AddWeb Solution Pvt Ltd
-------------------------------------------------------
Here is a snippet from m y apache error log
```
<IfModule> section
[Fri Jan 29 16:35:30 2016] [error] [client ::1] script '/Applications/MAMP/htdocs/index.php' not found or unable to stat
[Fri Jan 29 16:36:08 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Fri Jan 29 16:36:08 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Fri Jan 29 16:36:14 2016] [error] [client ::1] script '/Applications/MAMP/htdocs/index.php' not found or unable to stat
[Fri Jan 29 16:50:40 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Fri Jan 29 16:50:40 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Fri Jan 29 16:56:51 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Fri Jan 29 16:56:51 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Fri Jan 29 16:57:15 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Fri Jan 29 16:57:15 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Fri Jan 29 17:02:16 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Fri Jan 29 17:02:16 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Fri Jan 29 17:03:12 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Fri Jan 29 17:03:12 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Fri Jan 29 19:18:38 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Fri Jan 29 19:18:38 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Fri Jan 29 19:35:48 2016] [notice] caught SIGTERM, shutting down
[Fri Jan 29 21:00:44 2016] [notice] Digest: generating secret for digest authentication ...
[Fri Jan 29 21:00:44 2016] [notice] Digest: done
[Fri Jan 29 21:00:44 2016] [notice] Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8y DAV/2 PHP/5.3.6 configured -- resuming normal operations
[Fri Jan 29 21:01:34 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Fri Jan 29 21:01:34 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
sh: /usr/local/bin/zip: No such file or directory
sh: /usr/local/bin/unzip: No such file or directory
[Sun Jan 31 16:46:33 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Sun Jan 31 16:46:33 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Tue Feb 02 16:08:25 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Tue Feb 02 16:08:26 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Tue Feb 02 16:12:15 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Tue Feb 02 16:12:15 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Tue Feb 02 16:12:15 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Tue Feb 02 16:12:15 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Tue Feb 02 16:12:26 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Tue Feb 02 16:12:26 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
[Tue Feb 02 16:17:53 2016] [error] [client ::1] client denied by server configuration: /Applications/MAMP/htdocs/2016/.DS_Store
[Tue Feb 02 16:17:53 2016] [alert] [client ::1] /Applications/MAMP/htdocs/2016/superclean/.htaccess: </IfModule> without matching <IfModule> section
```
|
I have found out how to fix it but can't seem to find out what caused it. The website was fairly new and was launched on April 20th, 2015. Not many updates had been done so maybe thats why?
Someone had suggested that I replace all instances of the wordpress core files (except wp-config.php and wp-content as these are important for your website and without them you don't have your custom website).
So you:
* Go to [wordpress.org](http://www.wordpress.org) and download the latest copy of wordpress
* Unzip the folder and extract the files
* Visit your website (I had a copy of my files on a different server to play with and test - i manually moved it over with the [help of this article](http://www.wpexplorer.com/migrating-wordpress-website/) but don't forget to [change your URL's](https://wpbeaches.com/updating-wordpress-mysql-database-after-moving-to-a-new-url/))
* Replace every file and folder (except wp-config.php and wp-content) with a fresh install of wordpress
* Follow the rest of the steps in the [manual migration article](http://www.wpexplorer.com/migrating-wordpress-website/) I referenced earlier. Don't forget about the URL change if you moved to another server for testing.
* Refresh the page where your wordpress website should be
* You may get a wordpress notification about repairing the database, run the repair and all should be good.
So I was able to do this on the test site I put up earlier and then after visiting the site and repairing the database all was well.
I'm not quite sure now what caused the white screen of death, but a fresh update of wordpress did the trick.
So now, either install your backup plugin (I use Backup Buddy) or manually migrate these files back over (in the same fashion) to your actual website server.
Hope this ends up helping someone.
|
216,152 |
<p>In my WordPress theme I created the custom post type <code>articles</code>. I also created two taxonomies called <code>article</code> & <code>news</code>.
How can I display each taxonomy in its own single template?
For now it only displays using the <code>single-articles.php</code> template.</p>
|
[
{
"answer_id": 216158,
"author": "Nathan Powell",
"author_id": 27196,
"author_profile": "https://wordpress.stackexchange.com/users/27196",
"pm_score": -1,
"selected": false,
"text": "<p>You will need to read the <a href=\"https://developer.wordpress.org/themes/template-files-section/taxonomy-templates/\" rel=\"nofollow\">taxonomy template article</a> on WordPress.org for that information.</p>\n"
},
{
"answer_id": 279786,
"author": "Dev",
"author_id": 104464,
"author_profile": "https://wordpress.stackexchange.com/users/104464",
"pm_score": 2,
"selected": true,
"text": "<p>Use the single_template filter in your functions file with the correct <a href=\"https://codex.wordpress.org/Function_Reference/has_term\" rel=\"nofollow noreferrer\">conditional tag</a></p>\n\n<pre><code>add_filter( 'single_template', 'single_tax_term_template' );\nfunction single_tax_term_template( $single_template ) {\n\n global $post;\n\n if ( has_term( '', 'article' ) ) {\n $single_template = dirname( __FILE__ ) . '/article.php';\n }\n\n if ( has_term( '', 'news' ) ) {\n $single_template = dirname( __FILE__ ) . '/news.php';\n }\n\n return $single_template;\n}\n</code></pre>\n\n<p>This code targets all terms in news and article taxonomies.</p>\n"
}
] |
2016/01/30
|
[
"https://wordpress.stackexchange.com/questions/216152",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83974/"
] |
In my WordPress theme I created the custom post type `articles`. I also created two taxonomies called `article` & `news`.
How can I display each taxonomy in its own single template?
For now it only displays using the `single-articles.php` template.
|
Use the single\_template filter in your functions file with the correct [conditional tag](https://codex.wordpress.org/Function_Reference/has_term)
```
add_filter( 'single_template', 'single_tax_term_template' );
function single_tax_term_template( $single_template ) {
global $post;
if ( has_term( '', 'article' ) ) {
$single_template = dirname( __FILE__ ) . '/article.php';
}
if ( has_term( '', 'news' ) ) {
$single_template = dirname( __FILE__ ) . '/news.php';
}
return $single_template;
}
```
This code targets all terms in news and article taxonomies.
|
216,169 |
<p>Actions usually support the following (if you are creating your plugin using a class based approach):</p>
<pre><code>add_action('admin_notices', array(&$this, 'emailNoticeGUI'));
</code></pre>
<p>The <code>wp_schedule_event</code> does not support this kind of triggering. Is there any way I could do this, but still use a class based approach? What are the alternatives? I would like to schedule a hook upon plugin activation, but the activation logic is also based in the class itself.</p>
|
[
{
"answer_id": 216158,
"author": "Nathan Powell",
"author_id": 27196,
"author_profile": "https://wordpress.stackexchange.com/users/27196",
"pm_score": -1,
"selected": false,
"text": "<p>You will need to read the <a href=\"https://developer.wordpress.org/themes/template-files-section/taxonomy-templates/\" rel=\"nofollow\">taxonomy template article</a> on WordPress.org for that information.</p>\n"
},
{
"answer_id": 279786,
"author": "Dev",
"author_id": 104464,
"author_profile": "https://wordpress.stackexchange.com/users/104464",
"pm_score": 2,
"selected": true,
"text": "<p>Use the single_template filter in your functions file with the correct <a href=\"https://codex.wordpress.org/Function_Reference/has_term\" rel=\"nofollow noreferrer\">conditional tag</a></p>\n\n<pre><code>add_filter( 'single_template', 'single_tax_term_template' );\nfunction single_tax_term_template( $single_template ) {\n\n global $post;\n\n if ( has_term( '', 'article' ) ) {\n $single_template = dirname( __FILE__ ) . '/article.php';\n }\n\n if ( has_term( '', 'news' ) ) {\n $single_template = dirname( __FILE__ ) . '/news.php';\n }\n\n return $single_template;\n}\n</code></pre>\n\n<p>This code targets all terms in news and article taxonomies.</p>\n"
}
] |
2016/01/30
|
[
"https://wordpress.stackexchange.com/questions/216169",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87772/"
] |
Actions usually support the following (if you are creating your plugin using a class based approach):
```
add_action('admin_notices', array(&$this, 'emailNoticeGUI'));
```
The `wp_schedule_event` does not support this kind of triggering. Is there any way I could do this, but still use a class based approach? What are the alternatives? I would like to schedule a hook upon plugin activation, but the activation logic is also based in the class itself.
|
Use the single\_template filter in your functions file with the correct [conditional tag](https://codex.wordpress.org/Function_Reference/has_term)
```
add_filter( 'single_template', 'single_tax_term_template' );
function single_tax_term_template( $single_template ) {
global $post;
if ( has_term( '', 'article' ) ) {
$single_template = dirname( __FILE__ ) . '/article.php';
}
if ( has_term( '', 'news' ) ) {
$single_template = dirname( __FILE__ ) . '/news.php';
}
return $single_template;
}
```
This code targets all terms in news and article taxonomies.
|
216,174 |
<p>I have a custom post type (projects) which have custom cmb2 meta keys (str_dte and end_dte), so each project has a start date and end date. What I am trying to do is to get projects between two dates.</p>
<p>Example:</p>
<p>Project #1: start date = 20120101 (Jan 2012) / end date = 20120601 (Jun 2012) (Ymd)</p>
<p>Project #2: start date = 20120401 (Apr 2012) / end date = 20121201 (Dec 2012) (Ymd)</p>
<p>The query:</p>
<pre><code>query_posts(array(
'posts_per_page' => $numPosts,
'paged' => $page,
'post_type' => 'projects',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'str_dte',
'compare' => '>=',
'value' => '20120501', //May 2012
'type' => 'DATE'
),
array(
'key' => 'end_dte',
'compare' => '<=',
'value' => '20120701', //July 2012
'type' => 'DATE'
)
),
));
</code></pre>
<p>Problem: this query didn't display any project, because it didn't realise the date range between the start date and end date of each project.</p>
<p>Shortly: I need to find a solution to query projects/posts between two dates (start date and end date) considering the date range between each project start and end date. </p>
<p>Online Resources: the most useful solution I have found online was <a href="http://support.advancedcustomfields.com/forums/topic/query-between-dates-using-date-picker-fields/" rel="nofollow">(robbiegod/keesiemeijer) solution</a> but it didn't work for me, I don't know why!</p>
<p>Your help is appreciated.
Thank you.</p>
<p><strong>SOLUTION</strong> </p>
<pre><code>query_posts(array(
'posts_per_page' => $numPosts,
'paged' => $page,
'post_type' => 'projects',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'str_dte',
'compare' => '<=',
'value' => '$end_date_value', // 20120701 July (Ymd or UnixTime)
'type' => 'DATE'
),
array(
'key' => 'end_dte',
'compare' => '>=',
'value' => '$start_date_value', // 20120501 May (Ymd or UnixTime)
'type' => 'DATE'
)
),
));
</code></pre>
<p>Just put the start date value result (date) as value for the end date meta key, and put the end date value result (date) as value for the start date meta key.</p>
<p>That's it.</p>
|
[
{
"answer_id": 216181,
"author": "nyan",
"author_id": 72720,
"author_profile": "https://wordpress.stackexchange.com/users/72720",
"pm_score": 0,
"selected": false,
"text": "<p>First, do not use query_posts! (Why not? <a href=\"https://stackoverflow.com/a/25589475\">That is why!</a>)</p>\n\n<p>Second, if your custom fields (CF) are saved in the Ymd-form (you are sure about that, yes?!), everything should be fine, even if you do not define the \"type\" as \"date\". Reading through several discussions on SE, etc. it seems to be better just to avoid the \"date\"-type, if you are not comparing a date-value against an array of two dates in one meta_query-array. So, remove <code>'type'=>'date'</code>.</p>\n\n<p>Having said that, I wonder that your query returns a result at all, because if I walk through it, this is what comes out: Both conditions have to be true as you are using a <code>relation</code> of \"and\".</p>\n\n<p><strong>First condition</strong>: If the value of 20120101 (= <code>value</code>) is greater than or equal to (= <code>compare</code>) the value stored in str_date (= <code>key</code>), we are good to go.</p>\n\n<ul>\n<li>Project #1: 20120101 >= 20120101: true.</li>\n<li>Project #2: 20120101 >= 20120401: false.</li>\n</ul>\n\n<p><strong>Second condition</strong>: If the value of 20120630 (= <code>value</code>) is less than or equal to (= <code>compare</code>) the value stored in end_dte (= <code>key</code>), we are good to go.</p>\n\n<ul>\n<li>Project #1: 20120630 <= 20120601: false.</li>\n<li>Project #2: 20120630 <= 20121201: true.</li>\n</ul>\n\n<p>As neither project fulfills both conditions, I am wondering that WP returns even one. I think for what you want, this query should work:</p>\n\n<pre><code>// New Query: se216174\n$se216174_args = array(\n 'posts_per_page' => -1, // Why '-1'? Because the custom fields limit the results anyway\n 'post_type' => 'projects',\n 'meta_query' => array(\n 'relation' => 'AND', // This is default, you could skip it\n array(\n 'key' => 'str_dte',\n 'compare' => '<=', // I have changed this, so everything with a date greater than what we have in the next line should be displayed.\n 'value' => '20120101',\n ),\n array(\n 'key' => 'end_dte',\n 'compare' => '>=', // Same as above\n 'value' => '20121201', // New date so that both your projects will match\n ),\n ),\n);\n$se216174_query = new WP_Query( $se216174_args );\nif ( $se216174_query->have_posts() ) : \n while ( $se216174_query->have_posts() ) :\n $se216174_query->the_post();\n // Display post, eg. echo the_title();\n endwhile; wp_reset_postdata();\nelse :\n // No posts, eg. echo 'Nothing found';\nendif;\n</code></pre>\n\n<p>Not tested, but this should work. Let me quickly check as I did above:</p>\n\n<p><strong>First condition</strong>: If the value of 20120101 (= <code>value</code>) is less than or equal to (= <code>compare</code>) the value stored in str_date (= <code>key</code>), we are good to go.</p>\n\n<ul>\n<li>Project #1: 20120101 <= 20120101: true.</li>\n<li>Project #2: 20120101 <= 20120401: true.</li>\n</ul>\n\n<p><strong>Second condition</strong>: If the value of 20120630 (= <code>value</code>) is greater than or equal to (= <code>compare</code>) the value stored in end_dte (= <code>key</code>), we are good to go.</p>\n\n<ul>\n<li>Project #1: 20121201 >= 20120601: true.</li>\n<li>Project #2: 20121201 >= 20121201: true.</li>\n</ul>\n\n<p>So, if you want to show everything between 20120101 and 20121201 - this is the query you need.</p>\n"
},
{
"answer_id": 216211,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>To find projects happening within a range of dates, there are 3 cases you have to account for:</p>\n\n<ul>\n<li>A project starts within the range</li>\n<li>A project ends within the range</li>\n<li>A project starts before the range and ends after the range</li>\n</ul>\n\n<p>You can test for these 3 cases separately with an <code>OR</code> meta query and 1 nested <code>AND</code>:</p>\n\n<pre><code>'meta_query' => array(\n 'relation' => 'OR',\n array(\n 'key' => 'str_dte',\n 'value' => array( $range_start, $range_end ),\n 'compare' => 'BETWEEN',\n ),\n array(\n 'key' => 'end_dte',\n 'value' => array( $range_start, $range_end ),\n 'compare' => 'BETWEEN',\n ),\n array(\n 'relation' => 'AND',\n array(\n 'key' => 'str_dte',\n 'value' => $range_start,\n 'compare' => '<',\n ),\n array(\n 'key' => 'end_dte',\n 'value' => $range_end,\n 'compare' => '>',\n ),\n ),\n),\n</code></pre>\n\n<p>If you're doing lots of these queries and performance is a concern, you can probably come up with a faster query manually than this will generate.</p>\n"
}
] |
2016/01/30
|
[
"https://wordpress.stackexchange.com/questions/216174",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/42810/"
] |
I have a custom post type (projects) which have custom cmb2 meta keys (str\_dte and end\_dte), so each project has a start date and end date. What I am trying to do is to get projects between two dates.
Example:
Project #1: start date = 20120101 (Jan 2012) / end date = 20120601 (Jun 2012) (Ymd)
Project #2: start date = 20120401 (Apr 2012) / end date = 20121201 (Dec 2012) (Ymd)
The query:
```
query_posts(array(
'posts_per_page' => $numPosts,
'paged' => $page,
'post_type' => 'projects',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'str_dte',
'compare' => '>=',
'value' => '20120501', //May 2012
'type' => 'DATE'
),
array(
'key' => 'end_dte',
'compare' => '<=',
'value' => '20120701', //July 2012
'type' => 'DATE'
)
),
));
```
Problem: this query didn't display any project, because it didn't realise the date range between the start date and end date of each project.
Shortly: I need to find a solution to query projects/posts between two dates (start date and end date) considering the date range between each project start and end date.
Online Resources: the most useful solution I have found online was [(robbiegod/keesiemeijer) solution](http://support.advancedcustomfields.com/forums/topic/query-between-dates-using-date-picker-fields/) but it didn't work for me, I don't know why!
Your help is appreciated.
Thank you.
**SOLUTION**
```
query_posts(array(
'posts_per_page' => $numPosts,
'paged' => $page,
'post_type' => 'projects',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'str_dte',
'compare' => '<=',
'value' => '$end_date_value', // 20120701 July (Ymd or UnixTime)
'type' => 'DATE'
),
array(
'key' => 'end_dte',
'compare' => '>=',
'value' => '$start_date_value', // 20120501 May (Ymd or UnixTime)
'type' => 'DATE'
)
),
));
```
Just put the start date value result (date) as value for the end date meta key, and put the end date value result (date) as value for the start date meta key.
That's it.
|
To find projects happening within a range of dates, there are 3 cases you have to account for:
* A project starts within the range
* A project ends within the range
* A project starts before the range and ends after the range
You can test for these 3 cases separately with an `OR` meta query and 1 nested `AND`:
```
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'str_dte',
'value' => array( $range_start, $range_end ),
'compare' => 'BETWEEN',
),
array(
'key' => 'end_dte',
'value' => array( $range_start, $range_end ),
'compare' => 'BETWEEN',
),
array(
'relation' => 'AND',
array(
'key' => 'str_dte',
'value' => $range_start,
'compare' => '<',
),
array(
'key' => 'end_dte',
'value' => $range_end,
'compare' => '>',
),
),
),
```
If you're doing lots of these queries and performance is a concern, you can probably come up with a faster query manually than this will generate.
|
216,178 |
<p>I am inserting some post into wordpress using the function <a href="https://developer.wordpress.org/reference/functions/wp_insert_post/">wp_insert_post()</a>.</p>
<p>I want to insert some custom fields on each post and reading the documentation I though the meta_info parameter was used for that, I tried something like this:</p>
<pre><code>$data = array(
'post_author' => 1,
'post_status' => 'publish',
'post_title' => $post->getTitle(),
'post_content' => $post->getContent(),
'post_category' => $post->getCategory(),
'tags_input' => $post->getTags(),
'meta_input' => array( "_test" => "testx1" )
);
$postID = wp_insert_post( $data );
</code></pre>
<p>The post gets inserted correctly and tags too. But there are no custom fields added. I know I could use <em>add_post_meta()</em> to add them but I still would like to know what the <em>meta_input</em> parameter is used for, because I did a search on the database for "testx1" after inserting the post and couldn't find any result.</p>
|
[
{
"answer_id": 216180,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<p>This part of <a href=\"https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/post.php#L3259\" rel=\"noreferrer\"><code>wp_insert_posts()</code></a> gives it away:</p>\n\n<pre><code> if ( ! empty( $postarr['meta_input'] ) ) {\n foreach ( $postarr['meta_input'] as $field => $value ) {\n update_post_meta( $post_ID, $field, $value );\n }\n } \n</code></pre>\n\n<p>where we see how the post meta fields are updated/added with <code>update_post_meta()</code>.</p>\n\n<p>Here's the inline description for <code>meta_input</code>:</p>\n\n<blockquote>\n <p>Array of post meta values keyed by their post meta key. Default empty.</p>\n</blockquote>\n\n<p>This was added in WordPress 4.4 and here's relevant ticket <a href=\"https://core.trac.wordpress.org/ticket/20451\" rel=\"noreferrer\">#20451</a> for more information.</p>\n\n<p>Note that using the underscore in front of the the meta key <code>_test</code> will hide it from the <em>custom fields</em> metabox in the post edit screen.</p>\n"
},
{
"answer_id": 325722,
"author": "Alex DS",
"author_id": 70848,
"author_profile": "https://wordpress.stackexchange.com/users/70848",
"pm_score": 0,
"selected": false,
"text": "<p>The way I do it is via term_id not slug and it works: </p>\n\n<pre><code>//insert Art items into database\n$arr = array('item 1', 'item 2');\n// $arr = array('art item 1', 'art item 2');\n\nforeach ($arr as $a) { \n wp_insert_post(array(\n //essentials\n //'ID' => 1131,\n 'post_author' => 1,\n 'post_title' => $a,\n 'post_type' => 'post',\n 'post_content' => 'Something...',\n 'post_status' => 'publish',\n 'post_name' => 'post name',\n 'meta_input' => array( //(array) Array of post meta values keyed by their post meta key. Default empty.\n 'city' => '',// 'name' => $post['name']\n 'country' => ''// 'city' => $post['city']\n ),\n 'tax_input' => array(\n 'category' => array(33,32), //id numbers work, slugs tend to be ignored !!!\n 'post_tag' => array('one', 'two') //for tags slugs seem to work\n ),//(array) Array of taxonomy terms keyed by their taxonomy name. Default empty. Equivalent to calling wp_set_post_terms() / wp_set_object_terms()\n //'tags_input' => array('una', 'trei'), //(array) Array of tag names, slugs, or IDs. Default empty. Equivalent to calling wp_set_post_tags().\n ), true); \n}\n</code></pre>\n"
}
] |
2016/01/30
|
[
"https://wordpress.stackexchange.com/questions/216178",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82844/"
] |
I am inserting some post into wordpress using the function [wp\_insert\_post()](https://developer.wordpress.org/reference/functions/wp_insert_post/).
I want to insert some custom fields on each post and reading the documentation I though the meta\_info parameter was used for that, I tried something like this:
```
$data = array(
'post_author' => 1,
'post_status' => 'publish',
'post_title' => $post->getTitle(),
'post_content' => $post->getContent(),
'post_category' => $post->getCategory(),
'tags_input' => $post->getTags(),
'meta_input' => array( "_test" => "testx1" )
);
$postID = wp_insert_post( $data );
```
The post gets inserted correctly and tags too. But there are no custom fields added. I know I could use *add\_post\_meta()* to add them but I still would like to know what the *meta\_input* parameter is used for, because I did a search on the database for "testx1" after inserting the post and couldn't find any result.
|
This part of [`wp_insert_posts()`](https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/post.php#L3259) gives it away:
```
if ( ! empty( $postarr['meta_input'] ) ) {
foreach ( $postarr['meta_input'] as $field => $value ) {
update_post_meta( $post_ID, $field, $value );
}
}
```
where we see how the post meta fields are updated/added with `update_post_meta()`.
Here's the inline description for `meta_input`:
>
> Array of post meta values keyed by their post meta key. Default empty.
>
>
>
This was added in WordPress 4.4 and here's relevant ticket [#20451](https://core.trac.wordpress.org/ticket/20451) for more information.
Note that using the underscore in front of the the meta key `_test` will hide it from the *custom fields* metabox in the post edit screen.
|
216,183 |
<p>Can anyone guide me in the right direction on how to loosen or disable the strong password policy?
Would like to do it without the use of a plugin.
I'm running a non-public site and don't need strong security.
<a href="https://i.stack.imgur.com/gYpZE.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/gYpZE.jpg" alt="enter image description here"></a></p>
|
[
{
"answer_id": 223453,
"author": "MrCalvin",
"author_id": 87041,
"author_profile": "https://wordpress.stackexchange.com/users/87041",
"pm_score": 4,
"selected": false,
"text": "<p>This will do it :-)</p>\n\n<pre><code>add_action( 'wp_print_scripts', 'DisableStrongPW', 100 );\n\nfunction DisableStrongPW() {\n if ( wp_script_is( 'wc-password-strength-meter', 'enqueued' ) ) {\n wp_dequeue_script( 'wc-password-strength-meter' );\n }\n}\n</code></pre>\n\n<p>I found the solution <a href=\"https://nicolamustone.com/2016/01/27/remove-the-password-strength-meter-on-the-checkout-page/\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 324994,
"author": "phenomenia",
"author_id": 96561,
"author_profile": "https://wordpress.stackexchange.com/users/96561",
"pm_score": -1,
"selected": false,
"text": "<p>It can also be set in the wp_generate_password function. Just in case you use it for your own code. See: <a href=\"https://codex.wordpress.org/Function_Reference/wp_generate_password\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_generate_password</a></p>\n"
},
{
"answer_id": 341103,
"author": "jockolad",
"author_id": 129357,
"author_profile": "https://wordpress.stackexchange.com/users/129357",
"pm_score": 1,
"selected": false,
"text": "<p>Just to update this answer:</p>\n\n<pre><code>add_action( 'wp_print_scripts', 'DisableStrongPW', 100 );\n\nfunction DisableStrongPW() {\n if ( wp_script_is( 'user-profile', 'enqueued' ) ) {\n wp_dequeue_script( 'user-profile' );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 356727,
"author": "Michael Schober",
"author_id": 147081,
"author_profile": "https://wordpress.stackexchange.com/users/147081",
"pm_score": 2,
"selected": false,
"text": "<p>Currently it's not possible to change the strength requirements of the password. \nYou can only deactivate it the functionality completely by dequeueing the password script:</p>\n\n<pre><code>add_action( 'wp_print_scripts', 'DisableStrongPW', 100 );\n\nfunction DisableStrongPW() {\n if ( wp_script_is( 'user-profile', 'enqueued' ) ) {\n wp_dequeue_script( 'user-profile' );\n }\n}\n</code></pre>\n\n<p>For changing the minimum strength of the password I can recommend this plugin which builds on the same library and integrates nicely into woocommerce:\n<a href=\"https://wordpress.org/plugins/wc-password-strength-settings/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wc-password-strength-settings/</a></p>\n"
}
] |
2016/01/30
|
[
"https://wordpress.stackexchange.com/questions/216183",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87041/"
] |
Can anyone guide me in the right direction on how to loosen or disable the strong password policy?
Would like to do it without the use of a plugin.
I'm running a non-public site and don't need strong security.
[](https://i.stack.imgur.com/gYpZE.jpg)
|
This will do it :-)
```
add_action( 'wp_print_scripts', 'DisableStrongPW', 100 );
function DisableStrongPW() {
if ( wp_script_is( 'wc-password-strength-meter', 'enqueued' ) ) {
wp_dequeue_script( 'wc-password-strength-meter' );
}
}
```
I found the solution [here](https://nicolamustone.com/2016/01/27/remove-the-password-strength-meter-on-the-checkout-page/).
|
216,189 |
<p>I am new to WP-CLI and having trouble finding examples of what I want to do. I know how to create a single page. <code>wp post create --post_type=page --post_status=publish --post_title='Contact'</code></p>
<p>Is there a way to create multiple pages with a single command? </p>
|
[
{
"answer_id": 216222,
"author": "JediTricks007",
"author_id": 49017,
"author_profile": "https://wordpress.stackexchange.com/users/49017",
"pm_score": 1,
"selected": false,
"text": "<p>After looking further I found a page on the site. It looks like you can.</p>\n\n<pre><code>wp post generate --count=100 --post_type=page --post_date=1999-01-04 curl http://loripsum.net/api/5 | wp post generate --post_content --count=10\n</code></pre>\n\n<p><a href=\"http://wp-cli.org/commands/post/generate/\" rel=\"nofollow\">http://wp-cli.org/commands/post/generate/</a></p>\n"
},
{
"answer_id": 216235,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 2,
"selected": false,
"text": "<p>There are a few ways. As mentioned, <a href=\"http://wp-cli.org/commands/post/generate/\" rel=\"nofollow\"><code>post generate</code></a>.</p>\n\n<pre><code>wp post generate --count=10 --post_type=page --post_date=1999-01-04\ncurl http://loripsum.net/api/5 | wp post generate --post_content --count=10\n</code></pre>\n\n<p>You could write your own <a href=\"https://github.com/wp-cli/wp-cli/wiki/Commands-Cookbook#anatomy\" rel=\"nofollow\">custom command</a>. See the <a href=\"https://github.com/wp-cli/wp-cli/wiki/List-of-community-commands\" rel=\"nofollow\">List of community commands</a> for examples or the <a href=\"http://wp-cli.org/package-index/\" rel=\"nofollow\">package index</a>.</p>\n\n<pre><code><?php\n/**\n * Implements example command.\n */\nclass Example_Command extends WP_CLI_Command {\n\n /**\n * Prints a greeting.\n * \n * ## OPTIONS\n * \n * <name>\n * : The name of the person to greet.\n * \n * ## EXAMPLES\n * \n * wp example hello Newman\n *\n * @synopsis <name>\n */\n function hello( $args, $assoc_args ) {\n list( $name ) = $args;\n\n // Print a success message\n WP_CLI::success( \"Hello, $name!\" );\n }\n}\n\nWP_CLI::add_command( 'example', 'Example_Command' );\n</code></pre>\n\n<p>And <a href=\"http://wptest.io\" rel=\"nofollow\">WPTest.io</a> is a good example of using the <a href=\"http://wp-cli.org/commands/import/\" rel=\"nofollow\"><code>import</code></a> command to create test content from xml.</p>\n\n<pre><code>#!/bin/sh\n#\n# WP Test - WP-CLI Quick Install Script\n# http://wptest.io/\n#\n# Note: This script assumes you have wp-cli installed.\n#####################################################################################\n\n# Ask user where WordPress is installed.\nprintf \"Please provide the local path to your WordPress install: \"\nread WPPATH\n\n# Import WP Test data.\ncd $WPPATH\ncurl -OL https://raw.githubusercontent.com/manovotny/wptest/master/wptest.xml\nwp import wptest.xml --authors=create\nrm wptest.xml\n</code></pre>\n"
},
{
"answer_id": 286207,
"author": "patrickzdb",
"author_id": 20327,
"author_profile": "https://wordpress.stackexchange.com/users/20327",
"pm_score": 1,
"selected": false,
"text": "<p>You could just chain them up using the && operator. E.g:</p>\n\n<p><code>wp post create --post_type=page --post_status=publish --post_title='Contact' && wp post create --post_type=page --post_status=publish --post_title='Home' && wp post create --post_type=page --post_status=publish --post_title='Another Page' ...</code></p>\n"
}
] |
2016/01/30
|
[
"https://wordpress.stackexchange.com/questions/216189",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81532/"
] |
I am new to WP-CLI and having trouble finding examples of what I want to do. I know how to create a single page. `wp post create --post_type=page --post_status=publish --post_title='Contact'`
Is there a way to create multiple pages with a single command?
|
There are a few ways. As mentioned, [`post generate`](http://wp-cli.org/commands/post/generate/).
```
wp post generate --count=10 --post_type=page --post_date=1999-01-04
curl http://loripsum.net/api/5 | wp post generate --post_content --count=10
```
You could write your own [custom command](https://github.com/wp-cli/wp-cli/wiki/Commands-Cookbook#anatomy). See the [List of community commands](https://github.com/wp-cli/wp-cli/wiki/List-of-community-commands) for examples or the [package index](http://wp-cli.org/package-index/).
```
<?php
/**
* Implements example command.
*/
class Example_Command extends WP_CLI_Command {
/**
* Prints a greeting.
*
* ## OPTIONS
*
* <name>
* : The name of the person to greet.
*
* ## EXAMPLES
*
* wp example hello Newman
*
* @synopsis <name>
*/
function hello( $args, $assoc_args ) {
list( $name ) = $args;
// Print a success message
WP_CLI::success( "Hello, $name!" );
}
}
WP_CLI::add_command( 'example', 'Example_Command' );
```
And [WPTest.io](http://wptest.io) is a good example of using the [`import`](http://wp-cli.org/commands/import/) command to create test content from xml.
```
#!/bin/sh
#
# WP Test - WP-CLI Quick Install Script
# http://wptest.io/
#
# Note: This script assumes you have wp-cli installed.
#####################################################################################
# Ask user where WordPress is installed.
printf "Please provide the local path to your WordPress install: "
read WPPATH
# Import WP Test data.
cd $WPPATH
curl -OL https://raw.githubusercontent.com/manovotny/wptest/master/wptest.xml
wp import wptest.xml --authors=create
rm wptest.xml
```
|
216,197 |
<p>To disable a custom post types archive page, we should use the following code:</p>
<pre><code>$args = array(
'has_archive' => false,
);
</code></pre>
<p>But when we use <code>false</code> for <code>has_archive</code>, the feeds page (like : <code>name.com/books/feed</code>) of that custom post type becomes disabled too. Now I want to know how I can disable custom post types archive page but keep the feed active?</p>
|
[
{
"answer_id": 216208,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 3,
"selected": false,
"text": "<p>Set the <code>feeds</code> argument of <code>rewrite</code> to <code>true</code> to generate feed rewrite rules. It defaults to whatever <code>has_archive</code> is set to if nothing is explicitly passed.</p>\n\n<pre><code>$args = array(\n 'has_archive' => false,\n 'rewrite' => array(\n 'feeds' => true\n ),\n // your other args...\n);\n</code></pre>\n"
},
{
"answer_id": 216224,
"author": "saeed shabani",
"author_id": 39305,
"author_profile": "https://wordpress.stackexchange.com/users/39305",
"pm_score": 1,
"selected": true,
"text": "<p>Finally I found a solution for it. I set <code>has_archive</code> to <code>true</code>. Now both the feed and the archive page of CPT are active. To only disable the archive page of CPT, I use the following filter in the <code>functions.php</code> file:</p>\n\n<pre><code>function AryanThemes_disable_cpt_archive_template(){\n if ( is_post_type_archive('cpt') ) {\n global $wp_query;\n $wp_query->set_404();\n status_header( 404 );\n get_template_part( 404 ); exit();\n }\n}\nadd_filter( 'archive_template', 'AryanThemes_disable_cpt_archive_template', -1 );\n</code></pre>\n"
}
] |
2016/01/30
|
[
"https://wordpress.stackexchange.com/questions/216197",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/39305/"
] |
To disable a custom post types archive page, we should use the following code:
```
$args = array(
'has_archive' => false,
);
```
But when we use `false` for `has_archive`, the feeds page (like : `name.com/books/feed`) of that custom post type becomes disabled too. Now I want to know how I can disable custom post types archive page but keep the feed active?
|
Finally I found a solution for it. I set `has_archive` to `true`. Now both the feed and the archive page of CPT are active. To only disable the archive page of CPT, I use the following filter in the `functions.php` file:
```
function AryanThemes_disable_cpt_archive_template(){
if ( is_post_type_archive('cpt') ) {
global $wp_query;
$wp_query->set_404();
status_header( 404 );
get_template_part( 404 ); exit();
}
}
add_filter( 'archive_template', 'AryanThemes_disable_cpt_archive_template', -1 );
```
|
216,216 |
<p>Where do we add our custom widget? I keep on getting internal errors, I tried to add the class in wp_content > plugins, or wp_includes > widgets, but I get an internal error.</p>
<p>The class is simple, inside "My_Widget.php" :</p>
<pre><code><?php
/*
Plugin Name: My_Widget
Description: my widet description
Author: Author
*/
class My_Widget extends WP_Widget {
/**
* Sets up the widgets name etc
*/
public function __construct() {
$widget_ops = array(
'class_name' => 'my_widget',
'description' => 'My Widget is awesome',
);
parent::__construct( 'my_widget', 'My Widget', $widget_ops );
}
/**
* Outputs the content of the widget
*
* @param array $args
* @param array $instance
*/
public function widget( $args, $instance ) {
// outputs the content of the widget
}
/**
* Outputs the options form on admin
*
* @param array $instance The widget options
*/
public function form( $instance ) {
// outputs the options form on admin
}
/**
* Processing widget options on save
*
* @param array $new_instance The new options
* @param array $old_instance The previous options
*/
public function update( $new_instance, $old_instance ) {
// processes widget options to be saved
}
}
</code></pre>
<p>Then in my functions.php : </p>
<pre><code>register_widget( 'My_Widget' );
</code></pre>
|
[
{
"answer_id": 216226,
"author": "Prasad Nevase",
"author_id": 62283,
"author_profile": "https://wordpress.stackexchange.com/users/62283",
"pm_score": 2,
"selected": true,
"text": "<p>I copied the class definition and <code>register_widget( 'My_Widget' );</code> to my theme's functions.php file & it did show <strong>My Widget</strong> under <code>Appearance > Widgets</code>. So please place this code directly in your theme's functions.php file. It is not recommended to edit anything in <strong>wp-includes</strong> directory.</p>\n"
},
{
"answer_id": 216229,
"author": "Saiful Islam",
"author_id": 83449,
"author_profile": "https://wordpress.stackexchange.com/users/83449",
"pm_score": -1,
"selected": false,
"text": "<p>You have 2way to active your class .</p>\n\n<ol>\n<li>you can create a folder inside plugins folder ...</li>\n<li><p>you can include in <code>functions.php</code> like as Bellow</p>\n\n<pre><code>require_once(get_template_directory().'My_Widget.php'); \n</code></pre></li>\n</ol>\n"
}
] |
2016/01/31
|
[
"https://wordpress.stackexchange.com/questions/216216",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8432/"
] |
Where do we add our custom widget? I keep on getting internal errors, I tried to add the class in wp\_content > plugins, or wp\_includes > widgets, but I get an internal error.
The class is simple, inside "My\_Widget.php" :
```
<?php
/*
Plugin Name: My_Widget
Description: my widet description
Author: Author
*/
class My_Widget extends WP_Widget {
/**
* Sets up the widgets name etc
*/
public function __construct() {
$widget_ops = array(
'class_name' => 'my_widget',
'description' => 'My Widget is awesome',
);
parent::__construct( 'my_widget', 'My Widget', $widget_ops );
}
/**
* Outputs the content of the widget
*
* @param array $args
* @param array $instance
*/
public function widget( $args, $instance ) {
// outputs the content of the widget
}
/**
* Outputs the options form on admin
*
* @param array $instance The widget options
*/
public function form( $instance ) {
// outputs the options form on admin
}
/**
* Processing widget options on save
*
* @param array $new_instance The new options
* @param array $old_instance The previous options
*/
public function update( $new_instance, $old_instance ) {
// processes widget options to be saved
}
}
```
Then in my functions.php :
```
register_widget( 'My_Widget' );
```
|
I copied the class definition and `register_widget( 'My_Widget' );` to my theme's functions.php file & it did show **My Widget** under `Appearance > Widgets`. So please place this code directly in your theme's functions.php file. It is not recommended to edit anything in **wp-includes** directory.
|
216,217 |
<p>I'm trying to sort the popular posts so it shows the most visited in the last week, but it hasn't worked. Anyone have an idea of why it isn't working?</p>
<pre><code><?php
$popularpost = new WP_Query( array (
'posts_per_page' => 5,
'ignore_sticky_posts' => 1,
'meta_key' => 'sw_post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'date_query' => array (
array (
'year' => date( 'Y' ),
'week' => date( 'W' ),
),
),
) );
while( $popularpost->have_posts() ) :
$popularpost->the_post(); ?>
</code></pre>
|
[
{
"answer_id": 216233,
"author": "Vasim Shaikh",
"author_id": 87704,
"author_profile": "https://wordpress.stackexchange.com/users/87704",
"pm_score": -1,
"selected": false,
"text": "<p>If you are looking for plugin then this is simple way to install Plugin: WordPress Popular Posts</p>\n\n<p>Add Shortcode to sidebar:</p>\n\n<pre><code> [wpp range=weekly stats_comments=0 thumbnail_width=30 thumbnail_height=30 thumbnail_selection=usergenerated do_pattern=1 pattern_form={image}]\n</code></pre>\n"
},
{
"answer_id": 216238,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 3,
"selected": true,
"text": "<p>Use <code>strtotime</code> to compare dates.</p>\n\n<pre><code>$start = strtotime('yesterday');\n$end = strtotime( '+1 week',$start);\n\n$args = array(\n 'posts_per_page' => 5,\n 'ignore_sticky_posts' => 1,\n 'meta_key' => 'sw_post_views_count',\n 'orderby' => 'meta_value_num',\n 'order' => 'DESC',\n 'date_query' => array(\n 'after' => $end,\n 'before' => $start,\n ),\n);\n\n$popularpost = new WP_Query( $args );\n\nif ( $popularpost->have_posts() ) {\n\n while ( $popularpost->have_posts() ) {\n $popularpost->the_post();\n\n // Do your stuffs\n\n }\n\n} \n</code></pre>\n\n<p>Please note, this will return the posts from last 7 days, not last week.</p>\n"
}
] |
2016/01/31
|
[
"https://wordpress.stackexchange.com/questions/216217",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63307/"
] |
I'm trying to sort the popular posts so it shows the most visited in the last week, but it hasn't worked. Anyone have an idea of why it isn't working?
```
<?php
$popularpost = new WP_Query( array (
'posts_per_page' => 5,
'ignore_sticky_posts' => 1,
'meta_key' => 'sw_post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'date_query' => array (
array (
'year' => date( 'Y' ),
'week' => date( 'W' ),
),
),
) );
while( $popularpost->have_posts() ) :
$popularpost->the_post(); ?>
```
|
Use `strtotime` to compare dates.
```
$start = strtotime('yesterday');
$end = strtotime( '+1 week',$start);
$args = array(
'posts_per_page' => 5,
'ignore_sticky_posts' => 1,
'meta_key' => 'sw_post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'date_query' => array(
'after' => $end,
'before' => $start,
),
);
$popularpost = new WP_Query( $args );
if ( $popularpost->have_posts() ) {
while ( $popularpost->have_posts() ) {
$popularpost->the_post();
// Do your stuffs
}
}
```
Please note, this will return the posts from last 7 days, not last week.
|
216,244 |
<p>I'm am working on a WooCommerce website, and have all my jQuery in the footer inside script tags. I use PHP to filter out the needed scripts for any particular page.</p>
<p>However, I would like to use the suggested method of using wp_enqueue_script to load my jquery. The trouble is that scripts containing PHP wont work unless I pass any PHP variables to he script using <code>wp_localize_script</code>, which works.... mostly.</p>
<p>I call the enqueue in my functions.php using the wp_enqueue_scripts hook, but some of the PHP variables are not available when I register the script. Some global variables are, but some of my custom variables that are defined further down the line are empty when I try to access them via <code>localize_script</code>.</p>
<p>I'm hoping this makes some sense? If so, how would I go about doing this properly? </p>
<p>For example, let's say some PHP variables are defined in a particular page template. These variables won't be accessible if I enqueue a script using the hook mentioned above. How can I enqueue a script that has access to all the PHP variables defined on the page?</p>
<p>The actual code is a bit complex so ill try to simplify:-</p>
<p>In my functions.php I have the following:-</p>
<pre><code>function wp_enqueue_woocommerce_style(){
$array = array(
"var1" => <?php echo $var1 ?>,
"var2" => <?php echo $var2 ?>
);
wp_register_script('chroma_js', get_template_directory_uri() . '/js/chroma.js', '', '1.1', TRUE);
wp_enqueue_script('chroma_js');
wp_localize_script( "chroma_js", "php_vars", $array);
}
add_action( 'wp_enqueue_scripts', 'wp_enqueue_woocommerce_style',99 );
</code></pre>
<p>Which enqueues my script to the footer. However, the 2 PHP variables are defined in the function I hook into 'woocommerce_before_single_product'. When I try to access var1 & var2 in my script they are not defined. Any PHP variables already defined when I call the enqueue work fine. So, im not sure how to go about passing these variables to an enqueued script.</p>
|
[
{
"answer_id": 216245,
"author": "Vasim Shaikh",
"author_id": 87704,
"author_profile": "https://wordpress.stackexchange.com/users/87704",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php\n\n// Register the script\nwp_register_script( 'some_handle', 'path/to/myscript.js' );\n\n// Localize the script with new data\n$translation_array = array(\n 'some_string' => __( 'Some string to translate', 'plugin-domain' ),\n 'a_value' => '10'\n);\nwp_localize_script( 'some_handle', 'object_name', $translation_array );\n\n// Enqueued script with localized data.\nwp_enqueue_script( 'some_handle' );\n</code></pre>\n\n<p>You can access the variables in JavaScript as follows:</p>\n\n<pre><code><script>\n// alerts 'Some string to translate'\nalert( object_name.some_string);\n</script> \nNote: The data in the resulting JavaScript call will be passed as text (see ticket #25280). If you are trying to pass integers you will need to call the JavaScript parseInt() function.\n\n<script>\n// Call a function that needs an int.\nFinalZoom = map.getBoundsZoomLevel( bounds ) - parseInt( object_name.a_value, 10 ); \n</script>\n</code></pre>\n"
},
{
"answer_id": 216250,
"author": "Vasim Shaikh",
"author_id": 87704,
"author_profile": "https://wordpress.stackexchange.com/users/87704",
"pm_score": 0,
"selected": false,
"text": "<p>I'm used this code recently to get variable in header image path.Add this function to your functions.php:</p>\n\n<pre><code>function img()\n{\n return get_template_directory_uri().'/assets/img/';\n}\n</code></pre>\n\n<p>and use this in your header.php like this:</p>\n\n<pre><code><img src=\"<?php echo img(); ?>my-image.jpg\">\n</code></pre>\n"
},
{
"answer_id": 216253,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": true,
"text": "<p>If you're outputting the script in the footer, you can call <code>wp_localize_script</code> at any point after your script is enqueued but before the script is output on <code>wp_footer</code> priority 20.</p>\n\n<pre><code>function wp_enqueue_woocommerce_style(){\n wp_enqueue_script(\n 'chroma_js',\n get_template_directory_uri() . '/js/chroma.js',\n '',\n '1.1',\n true\n );\n}\nadd_action( 'wp_enqueue_scripts', 'wp_enqueue_woocommerce_style' );\n\nfunction wp_localize_woocommerce_style(){\n $array = array(\n 'var1' => $var1,\n 'var2' => $var2\n );\n wp_localize_script( 'chroma_js', 'php_vars', $array );\n}\nadd_action( 'wp_footer', 'wp_localize_woocommerce_style', 0 );\n</code></pre>\n"
}
] |
2016/01/31
|
[
"https://wordpress.stackexchange.com/questions/216244",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87826/"
] |
I'm am working on a WooCommerce website, and have all my jQuery in the footer inside script tags. I use PHP to filter out the needed scripts for any particular page.
However, I would like to use the suggested method of using wp\_enqueue\_script to load my jquery. The trouble is that scripts containing PHP wont work unless I pass any PHP variables to he script using `wp_localize_script`, which works.... mostly.
I call the enqueue in my functions.php using the wp\_enqueue\_scripts hook, but some of the PHP variables are not available when I register the script. Some global variables are, but some of my custom variables that are defined further down the line are empty when I try to access them via `localize_script`.
I'm hoping this makes some sense? If so, how would I go about doing this properly?
For example, let's say some PHP variables are defined in a particular page template. These variables won't be accessible if I enqueue a script using the hook mentioned above. How can I enqueue a script that has access to all the PHP variables defined on the page?
The actual code is a bit complex so ill try to simplify:-
In my functions.php I have the following:-
```
function wp_enqueue_woocommerce_style(){
$array = array(
"var1" => <?php echo $var1 ?>,
"var2" => <?php echo $var2 ?>
);
wp_register_script('chroma_js', get_template_directory_uri() . '/js/chroma.js', '', '1.1', TRUE);
wp_enqueue_script('chroma_js');
wp_localize_script( "chroma_js", "php_vars", $array);
}
add_action( 'wp_enqueue_scripts', 'wp_enqueue_woocommerce_style',99 );
```
Which enqueues my script to the footer. However, the 2 PHP variables are defined in the function I hook into 'woocommerce\_before\_single\_product'. When I try to access var1 & var2 in my script they are not defined. Any PHP variables already defined when I call the enqueue work fine. So, im not sure how to go about passing these variables to an enqueued script.
|
If you're outputting the script in the footer, you can call `wp_localize_script` at any point after your script is enqueued but before the script is output on `wp_footer` priority 20.
```
function wp_enqueue_woocommerce_style(){
wp_enqueue_script(
'chroma_js',
get_template_directory_uri() . '/js/chroma.js',
'',
'1.1',
true
);
}
add_action( 'wp_enqueue_scripts', 'wp_enqueue_woocommerce_style' );
function wp_localize_woocommerce_style(){
$array = array(
'var1' => $var1,
'var2' => $var2
);
wp_localize_script( 'chroma_js', 'php_vars', $array );
}
add_action( 'wp_footer', 'wp_localize_woocommerce_style', 0 );
```
|
216,257 |
<p>I'm quite new to Wordpress, I've build a website and found out in the Google WebMaster tool that one of the most present keyword was <code>[%%LINKS%%]</code>...</p>
<p>I've found this code:</p>
<pre><code><div style="display:none">[%%LINKS%%]</div>
</code></pre>
<p>I've browse the whole database and the files on my server, I can't find any trace of the line (using <code>grep -rn "LINKS" .</code>).</p>
<p>Here's my set up:</p>
<ul>
<li>wordpress 4.4;</li>
<li>Contact Form 7;</li>
<li>Envato WordPress Toolkit;</li>
<li>BeTheme;</li>
<li>Force Regenerate Thumbnails;</li>
<li>Google XML Sitemaps;</li>
<li>Slider Revolution;</li>
<li>W3 Total Cache;</li>
</ul>
<p>Where should I dig next to solve my problem?</p>
<p>Here's <a href="http://pastebin.com/Pf4iGJyW" rel="nofollow">the source</a></p>
<p>And the output foom r-debug:</p>
<pre><code>>>>>> wp_footer
10 wpcf7_recaptcha_callback_script
wp_func_jquery
RevSliderFront::load_icon_fonts
RevSliderFront::putAdminBarMenus
20 wp_print_footer_scripts
100 mfn_google_remarketing
mfn_scripts_custom
1000 wp_admin_bar_render
</code></pre>
|
[
{
"answer_id": 216278,
"author": "markratledge",
"author_id": 268,
"author_profile": "https://wordpress.stackexchange.com/users/268",
"pm_score": 0,
"selected": false,
"text": "<p><code>[%%LINKS%%]</code>is very suspicious. It's inside a <code>display:none</code> div, so any links output by a function will be in page source for SEO purposes, but won't display on the site.</p>\n<p>You probably did get hacked. Try using <a href=\"http://wordpress.org/plugins/adminer/\" rel=\"nofollow noreferrer\">Adminer « WordPress Plugins</a> to search the database for that string.</p>\n<p>If you find it, carefully follow <a href=\"https://codex.wordpress.org/FAQ_My_site_was_hacked\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/FAQ_My_site_was_hacked</a></p>\n<p>Then take a look at the recommended security measures in <a href=\"https://wordpress.org/support/article/hardening-wordpress/\" rel=\"nofollow noreferrer\">Hardening WordPress - WordPress Support</a> and <a href=\"https://wordpress.org/support/article/brute-force-attacks/\" rel=\"nofollow noreferrer\">Brute Force Attacks - WordPress Support</a></p>\n"
},
{
"answer_id": 216295,
"author": "fischi",
"author_id": 15680,
"author_profile": "https://wordpress.stackexchange.com/users/15680",
"pm_score": 1,
"selected": false,
"text": "<p>This looks like a hack, probably in W3TC.</p>\n\n<p>Try disabling all the Plugins one by one, and if it doesn't go away, try switching to the default theme.</p>\n\n<p>If that did not work, install WordPress from scratch, and transfer the database to it.</p>\n\n<p>If you prefer another debug mode, I suppose your script gets hooked into WordPress in the <code>wp_footer</code> action. To verify that, you could comment the line <code>wp_footer();</code> out, probably in <code>footer.php</code>.\nIt should be gone with that.</p>\n\n<p>To find out what injected it, try out @rarst <a href=\"https://gist.github.com/Rarst/1739714\" rel=\"nofollow\">R Debug</a>, which helps you see what action get performed where.</p>\n\n<p>Good luck!</p>\n"
}
] |
2016/01/31
|
[
"https://wordpress.stackexchange.com/questions/216257",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87832/"
] |
I'm quite new to Wordpress, I've build a website and found out in the Google WebMaster tool that one of the most present keyword was `[%%LINKS%%]`...
I've found this code:
```
<div style="display:none">[%%LINKS%%]</div>
```
I've browse the whole database and the files on my server, I can't find any trace of the line (using `grep -rn "LINKS" .`).
Here's my set up:
* wordpress 4.4;
* Contact Form 7;
* Envato WordPress Toolkit;
* BeTheme;
* Force Regenerate Thumbnails;
* Google XML Sitemaps;
* Slider Revolution;
* W3 Total Cache;
Where should I dig next to solve my problem?
Here's [the source](http://pastebin.com/Pf4iGJyW)
And the output foom r-debug:
```
>>>>> wp_footer
10 wpcf7_recaptcha_callback_script
wp_func_jquery
RevSliderFront::load_icon_fonts
RevSliderFront::putAdminBarMenus
20 wp_print_footer_scripts
100 mfn_google_remarketing
mfn_scripts_custom
1000 wp_admin_bar_render
```
|
This looks like a hack, probably in W3TC.
Try disabling all the Plugins one by one, and if it doesn't go away, try switching to the default theme.
If that did not work, install WordPress from scratch, and transfer the database to it.
If you prefer another debug mode, I suppose your script gets hooked into WordPress in the `wp_footer` action. To verify that, you could comment the line `wp_footer();` out, probably in `footer.php`.
It should be gone with that.
To find out what injected it, try out @rarst [R Debug](https://gist.github.com/Rarst/1739714), which helps you see what action get performed where.
Good luck!
|
216,271 |
<p>I have many security plugins setup. Could someone tell me what changes I need to make to my <a href="http://pastebin.com/6VkejW2R" rel="nofollow"><code>.htaccess</code></a> file (while keeping as much of my current rule set as possible) to make pretty URLs work?</p>
<pre><code># BEGIN iThemes Security - Do not modify or remove this line
# iThemes Security Config Details: 2
# Enable HackRepair.com's blacklist feature - Security > Settings > Banned Users > Default Blacklist
# Start HackRepair.com Blacklist
RewriteEngine on
# Start Abuse Agent Blocking
RewriteCond %{HTTP_USER_AGENT} "^Mozilla.*Indy" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^Mozilla.*NEWT" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^$" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^Maxthon$" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^SeaMonkey$" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^Acunetix" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^binlar" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^BlackWidow" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^Bolt 0" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^BOT for JCE" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^Bot mailto\:craftbot@yahoo\.com" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^casper" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^checkprivacy" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^ChinaClaw" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^clshttp" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^cmsworldmap" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^comodo" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^Custo" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^Default Browser 0" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^diavol" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^DIIbot" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^DISCo" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^dotbot" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^Download Demon" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^eCatch" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^EirGrabber" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^EmailCollector" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^EmailSiphon" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^EmailWolf" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^Express WebPictures" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^extract" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^ExtractorPro" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^EyeNetIE" [NC,OR]
RewriteCond
# Protect System Files - Security > Settings > System Tweaks > System Files
<files .htaccess>
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order allow,deny
Deny from all
</IfModule>
</files>
<files readme.html>
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order allow,deny
Deny from all
</IfModule>
</files>
<files readme.txt>
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order allow,deny
Deny from all
</IfModule>
</files>
<files install.php>
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order allow,deny
Deny from all
</IfModule>
</files>
<files wp-config.php>
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order allow,deny
Deny from all
</IfModule>
</files>
# Disable Directory Browsing - Security > Settings > System Tweaks > Directory Browsing
Options -Indexes
<IfModule mod_rewrite.c>
RewriteEngine On
# Protect System Files - Security > Settings > System Tweaks > System Files
RewriteRule ^wp-admin/includes/ - [F]
RewriteRule !^wp-includes/ - [S=3]
RewriteCond %{SCRIPT_FILENAME} !^(.*)wp-includes/ms-files.php
RewriteRule ^wp-includes/[^/]+\.php$ - [F]
RewriteRule ^wp-includes/js/tinymce/langs/.+\.php - [F]
RewriteRule ^wp-includes/theme-compat/ - [F]
# Disable PHP in Uploads - Security > Settings > System Tweaks > Uploads
RewriteRule ^wp\-content/uploads/.*\.(?:php[1-6]?|pht|phtml?)$ - [NC,F]
# Filter Request Methods - Security > Settings > System Tweaks > Request Methods
RewriteCond %{REQUEST_METHOD} ^(TRACE|DELETE|TRACK) [NC]
RewriteRule ^.* - [F]
# Filter Suspicious Query Strings in the URL - Security > Settings > System Tweaks > Suspicious Query Strings
RewriteCond %{QUERY_STRING} \.\.\/ [NC,OR]
RewriteCond %{QUERY_STRING} ^.*\.(bash|git|hg|log|svn|swp|cvs) [NC,OR]
RewriteCond %{QUERY_STRING} etc/passwd [NC,OR]
RewriteCond %{QUERY_STRING} boot\.ini [NC,OR]
RewriteCond %{QUERY_STRING} ftp\: [NC,OR]
RewriteCond %{QUERY_STRING} http\: [NC,OR]
RewriteCond %{QUERY_STRING} https\: [NC,OR]
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|%3D) [NC,OR]
RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [NC,OR]
RewriteCond %{QUERY_STRING} ^.*(%24&x).* [NC,OR]
RewriteCond %{QUERY_STRING} ^.*(127\.0).* [NC,OR]
RewriteCond %{QUERY_STRING} ^.*(globals|encode|localhost|loopback).* [NC,OR]
RewriteCond %{QUERY_STRING} ^.*(request|concat|insert|union|declare).* [NC]
RewriteCond %{QUERY_STRING} !^loggedout=true
RewriteCond %{QUERY_STRING} !^action=jetpack-sso
RewriteCond %{QUERY_STRING} !^action=rp
RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in_.*$
RewriteCond %{HTTP_REFERER} !^http://maps\.googleapis\.com(.*)$
RewriteRule ^.* - [F]
# Filter Non-English Characters - Security > Settings > System Tweaks > Non-English Characters
RewriteCond %{QUERY_STRING} ^.*(%0|%A|%B|%C|%D|%E|%F).* [NC]
RewriteRule ^.* - [F]
# Reduce Comment Spam - Security > Settings > System Tweaks > Comment Spam
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} /wp-comments-post\.php$
RewriteCond %{HTTP_USER_AGENT} ^$ [OR]
RewriteCond %{HTTP_REFERER} !^https?://(([^/]+\.)?sn0w\.io|jetpack\.wordpress\.com/jetpack-comment)(/|$) [NC]
RewriteRule ^.* - [F]
</IfModule>
# END iThemes Security - Do not modify or remove this line
# BULLETPROOF .53.1 >>>>>>> SECURE .HTACCESS
# PHP/PHP.INI HANDLER/CACHE CODE
# Use BPS Custom Code to add php/php.ini Handler and Cache htaccess code and to save it permanently.
# Most Hosts do not have/use/require php/php.ini Handler htaccess code
# TURN OFF YOUR SERVER SIGNATURE
# Suppresses the footer line server version number and ServerName of the serving virtual host
ServerSignature Off
# DO NOT SHOW DIRECTORY LISTING
# Disallow mod_autoindex from displaying a directory listing
# If a 500 Internal Server Error occurs when activating Root BulletProof Mode
# copy the entire DO NOT SHOW DIRECTORY LISTING and DIRECTORY INDEX sections of code
# and paste it into BPS Custom Code and comment out Options -Indexes
# by adding a # sign in front of it.
# Example: #Options -Indexes
Options -Indexes
# DIRECTORY INDEX FORCE INDEX.PHP
# Use index.php as default directory index file. index.html will be ignored.
# If a 500 Internal Server Error occurs when activating Root BulletProof Mode
# copy the entire DO NOT SHOW DIRECTORY LISTING and DIRECTORY INDEX sections of code
# and paste it into BPS Custom Code and comment out DirectoryIndex
# by adding a # sign in front of it.
# Example: #DirectoryIndex index.php index.html /index.php
DirectoryIndex index.php index.html /index.php
# BRUTE FORCE LOGIN PAGE PROTECTION
# PLACEHOLDER ONLY
# Use BPS Custom Code to add Brute Force Login protection code and to save it permanently.
# See this link: http://forum.ait-pro.com/forums/topic/protect-login-page-from-brute-force-login-attacks/
# for more information.
# BPS ERROR LOGGING AND TRACKING
# Use BPS Custom Code to modify/edit/change this code and to save it permanently.
# BPS has premade 400 Bad Request, 403 Forbidden, 404 Not Found, 405 Method Not Allowed and
# 410 Gone template logging files that are used to track and log 400, 403, 404, 405 and 410 errors
# that occur on your website. When a hacker attempts to hack your website the hackers IP address,
# Host name, Request Method, Referering link, the file name or requested resource, the user agent
# of the hacker and the query string used in the hack attempt are logged.
# All BPS log files are htaccess protected so that only you can view them.
# The 400.php, 403.php, 404.php, 405.php and 410.php files are located in /wp-content/plugins/bulletproof-security/
# The 400, 403, 405 and 410 Error logging files are already set up and will automatically start logging errors
# after you install BPS and have activated BulletProof Mode for your Root folder.
# If you would like to log 404 errors you will need to copy the logging code in the BPS 404.php file
# to your Theme's 404.php template file. Simple instructions are included in the BPS 404.php file.
# You can open the BPS 404.php file using the WP Plugins Editor or manually editing the file.
# NOTE: By default WordPress automatically looks in your Theme's folder for a 404.php Theme template file.
ErrorDocument 400 /wp-content/plugins/bulletproof-security/400.php
ErrorDocument 401 default
ErrorDocument 403 /wp-content/plugins/bulletproof-security/403.php
ErrorDocument 404 /404.php
ErrorDocument 405 /wp-content/plugins/bulletproof-security/405.php
ErrorDocument 410 /wp-content/plugins/bulletproof-security/410.php
# DENY ACCESS TO PROTECTED SERVER FILES AND FOLDERS
# Use BPS Custom Code to modify/edit/change this code and to save it permanently.
# Files and folders starting with a dot: .htaccess, .htpasswd, .errordocs, .logs
RedirectMatch 403 \.(htaccess|htpasswd|errordocs|logs)$
# WP-ADMIN/INCLUDES
# Use BPS Custom Code to remove this code permanently.
RewriteEngine On
RewriteBase /
RewriteRule ^wp-admin/includes/ - [F]
RewriteRule !^wp-includes/ - [S=3]
RewriteRule ^wp-includes/[^/]+\.php$ - [F]
RewriteRule ^wp-includes/js/tinymce/langs/.+\.php - [F]
RewriteRule ^wp-includes/theme-compat/ - [F]
# WP REWRITE LOOP START
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# REQUEST METHODS FILTERED
# If you want to allow HEAD Requests use BPS Custom Code and copy
# this entire REQUEST METHODS FILTERED section of code to this BPS Custom Code
# text box: CUSTOM CODE REQUEST METHODS FILTERED.
# See the CUSTOM CODE REQUEST METHODS FILTERED help text for additional steps.
RewriteCond %{REQUEST_METHOD} ^(TRACE|DELETE|TRACK|DEBUG) [NC]
RewriteRule ^(.*)$ - [F]
RewriteCond %{REQUEST_METHOD} ^(HEAD) [NC]
RewriteRule ^(.*)$ - [R=405,L]
# PLUGINS/THEMES AND VARIOUS EXPLOIT FILTER SKIP RULES
# To add plugin/theme skip/bypass rules use BPS Custom Code.
# The [S] flag is used to skip following rules. Skip rule [S=12] will skip 12 following RewriteRules.
# The skip rules MUST be in descending consecutive number order: 12, 11, 10, 9...
# If you delete a skip rule, change the other skip rule numbers accordingly.
# Examples: If RewriteRule [S=5] is deleted than change [S=6] to [S=5], [S=7] to [S=6], etc.
# If you add a new skip rule above skip rule 12 it will be skip rule 13: [S=13]
# Adminer MySQL management tool data populate
RewriteCond %{REQUEST_URI} ^/wp-content/plugins/adminer/ [NC]
RewriteRule . - [S=12]
# Comment Spam Pack MU Plugin - CAPTCHA images not displaying
RewriteCond %{REQUEST_URI} ^/wp-content/mu-plugins/custom-anti-spam/ [NC]
RewriteRule . - [S=11]
# Peters Custom Anti-Spam display CAPTCHA Image
RewriteCond %{REQUEST_URI} ^/wp-content/plugins/peters-custom-anti-spam-image/ [NC]
RewriteRule . - [S=10]
# Status Updater plugin fb connect
RewriteCond %{REQUEST_URI} ^/wp-content/plugins/fb-status-updater/ [NC]
RewriteRule . - [S=9]
# Stream Video Player - Adding FLV Videos Blocked
RewriteCond %{REQUEST_URI} ^/wp-content/plugins/stream-video-player/ [NC]
RewriteRule . - [S=8]
# XCloner 404 or 403 error when updating settings
RewriteCond %{REQUEST_URI} ^/wp-content/plugins/xcloner-backup-and-restore/ [NC]
RewriteRule . - [S=7]
# BuddyPress Logout Redirect
RewriteCond %{QUERY_STRING} action=logout&redirect_to=http%3A%2F%2F(.*) [NC]
RewriteRule . - [S=6]
# redirect_to=
RewriteCond %{QUERY_STRING} redirect_to=(.*) [NC]
RewriteRule . - [S=5]
# Login Plugins Password Reset And Redirect 1
RewriteCond %{QUERY_STRING} action=resetpass&key=(.*) [NC]
RewriteRule . - [S=4]
# Login Plugins Password Reset And Redirect 2
RewriteCond %{QUERY_STRING} action=rp&key=(.*) [NC]
RewriteRule . - [S=3]
# TIMTHUMB FORBID RFI and MISC FILE SKIP/BYPASS RULE
# Use BPS Custom Code to modify/edit/change this code and to save it permanently.
# Remote File Inclusion (RFI) security rules
# Note: Only whitelist your additional domains or files if needed - do not whitelist hacker domains or files
RewriteCond %{QUERY_STRING} ^.*(http|https|ftp)(%3A|:)(%2F|/)(%2F|/)(w){0,3}.?(blogger|picasa|blogspot|tsunami|petapolitik|photobucket|imgur|imageshack|wordpress\.com|img\.youtube|tinypic\.com|upload\.wikimedia|kkc|start-thegame).*$ [NC,OR]
RewriteCond %{THE_REQUEST} ^.*(http|https|ftp)(%3A|:)(%2F|/)(%2F|/)(w){0,3}.?(blogger|picasa|blogspot|tsunami|petapolitik|photobucket|imgur|imageshack|wordpress\.com|img\.youtube|tinypic\.com|upload\.wikimedia|kkc|start-thegame).*$ [NC]
RewriteRule .* index.php [F]
#
# Example: Whitelist additional misc files: (example\.php|another-file\.php|phpthumb\.php|thumb\.php|thumbs\.php)
RewriteCond %{REQUEST_URI} (timthumb\.php|phpthumb\.php|thumb\.php|thumbs\.php) [NC]
# Example: Whitelist additional website domains: RewriteCond %{HTTP_REFERER} ^.*(YourWebsite.com|AnotherWebsite.com).*
RewriteCond %{HTTP_REFERER} ^.*sn0w.io.*
RewriteRule . - [S=1]
# BEGIN BPSQSE BPS QUERY STRING EXPLOITS
# The libwww-perl User Agent is forbidden - Many bad bots use libwww-perl modules, but some good bots use it too.
# Good sites such as W3C use it for their W3C-LinkChecker.
# Use BPS Custom Code to add or remove user agents temporarily or permanently from the
# User Agent filters directly below or to modify/edit/change any of the other security code rules below.
RewriteCond %{HTTP_USER_AGENT} (havij|libwww-perl|wget|python|nikto|curl|scan|java|winhttp|clshttp|loader) [NC,OR]
RewriteCond %{HTTP_USER_AGENT} (%0A|%0D|%27|%3C|%3E|%00) [NC,OR]
RewriteCond %{HTTP_USER_AGENT} (;|<|>|'|"|\)|\(|%0A|%0D|%22|%27|%28|%3C|%3E|%00).*(libwww-perl|wget|python|nikto|curl|scan|java|winhttp|HTTrack|clshttp|archiver|loader|email|harvest|extract|grab|miner) [NC,OR]
RewriteCond %{THE_REQUEST} (\?|\*|%2a)+(%20+|\\s+|%20+\\s+|\\s+%20+|\\s+%20+\\s+)HTTP(:/|/) [NC,OR]
RewriteCond %{THE_REQUEST} etc/passwd [NC,OR]
RewriteCond %{THE_REQUEST} cgi-bin [NC,OR]
RewriteCond %{THE_REQUEST} (%0A|%0D|\\r|\\n) [NC,OR]
RewriteCond %{REQUEST_URI} owssvr\.dll [NC,OR]
RewriteCond %{HTTP_REFERER} (%0A|%0D|%27|%3C|%3E|%00) [NC,OR]
RewriteCond %{HTTP_REFERER} \.opendirviewer\. [NC,OR]
RewriteCond %{HTTP_REFERER} users\.skynet\.be.* [NC,OR]
RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=http:// [NC,OR]
RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=(\.\.//?)+ [NC,OR]
RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=/([a-z0-9_.]//?)+ [NC,OR]
RewriteCond %{QUERY_STRING} \=PHP[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12} [NC,OR]
RewriteCond %{QUERY_STRING} (\.\./|%2e%2e%2f|%2e%2e/|\.\.%2f|%2e\.%2f|%2e\./|\.%2e%2f|\.%2e/) [NC,OR]
RewriteCond %{QUERY_STRING} ftp\: [NC,OR]
RewriteCond %{QUERY_STRING} http\: [NC,OR]
RewriteCond %{QUERY_STRING} https\: [NC,OR]
RewriteCond %{QUERY_STRING} \=\|w\| [NC,OR]
RewriteCond %{QUERY_STRING} ^(.*)/self/(.*)$ [NC,OR]
RewriteCond %{QUERY_STRING} ^(.*)cPath=http://(.*)$ [NC,OR]
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (\<|%3C).*embed.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (<|%3C)([^e]*e)+mbed.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (\<|%3C).*object.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (<|%3C)([^o]*o)+bject.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (\<|%3C).*iframe.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (<|%3C)([^i]*i)+frame.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [NC,OR]
RewriteCond %{QUERY_STRING} base64_(en|de)code[^(]*\([^)]*\) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} ^.*(\(|\)|<|>|%3c|%3e).* [NC,OR]
RewriteCond %{QUERY_STRING} ^.*(\x00|\x04|\x08|\x0d|\x1b|\x20|\x3c|\x3e|\x7f).* [NC,OR]
RewriteCond %{QUERY_STRING} (NULL|OUTFILE|LOAD_FILE) [OR]
RewriteCond %{QUERY_STRING} (\.{1,}/)+(motd|etc|bin) [NC,OR]
RewriteCond %{QUERY_STRING} (localhost|loopback|127\.0\.0\.1) [NC,OR]
RewriteCond %{QUERY_STRING} (<|>|'|%0A|%0D|%27|%3C|%3E|%00) [NC,OR]
RewriteCond %{QUERY_STRING} concat[^\(]*\( [NC,OR]
RewriteCond %{QUERY_STRING} union([^s]*s)+elect [NC,OR]
RewriteCond %{QUERY_STRING} union([^a]*a)+ll([^s]*s)+elect [NC,OR]
RewriteCond %{QUERY_STRING} \-[sdcr].*(allow_url_include|allow_url_fopen|safe_mode|disable_functions|auto_prepend_file) [NC,OR]
RewriteCond %{QUERY_STRING} (;|<|>|'|"|\)|%0A|%0D|%22|%27|%3C|%3E|%00).*(/\*|union|select|insert|drop|delete|update|cast|create|char|convert|alter|declare|order|script|set|md5|benchmark|encode) [NC,OR]
RewriteCond %{QUERY_STRING} (sp_executesql) [NC]
RewriteRule ^(.*)$ - [F]
# END BPSQSE BPS QUERY STRING EXPLOITS
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# WP REWRITE LOOP END
# DENY BROWSER ACCESS TO THESE FILES
# Use BPS Custom Code to modify/edit/change this code and to save it permanently.
# wp-config.php, bb-config.php, php.ini, php5.ini, readme.html
# To be able to view these files from a Browser, replace 127.0.0.1 with your actual
# current IP address. Comment out: #Deny from all and Uncomment: Allow from 127.0.0.1
# Note: The BPS System Info page displays which modules are loaded on your server.
<FilesMatch "^(wp-config\.php|php\.ini|php5\.ini|readme\.html|bb-config\.php)">
Order Allow,Deny
Deny from all
#Allow from 127.0.0.1
</FilesMatch>
# HOTLINKING/FORBID COMMENT SPAMMERS/BLOCK BOTS/BLOCK IP/REDIRECT CODE
# PLACEHOLDER ONLY
# Use BPS Custom Code to add custom code and save it permanently here.
# BEGIN WordPress
# END WordPress
</code></pre>
|
[
{
"answer_id": 216274,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>Your htaccess do not have the default wordpress related rules, go to the permalink page and save, if it it doesn't help turn off plugins.</p>\n"
},
{
"answer_id": 216285,
"author": "user122552",
"author_id": 84013,
"author_profile": "https://wordpress.stackexchange.com/users/84013",
"pm_score": 0,
"selected": false,
"text": "<p>Go to \"Settings\" > Permalinks > [click] Save Changes</p>\n\n<p>You don't need to change anything in the Permalinks page, it just resets everything to correctly link up. </p>\n"
}
] |
2016/01/31
|
[
"https://wordpress.stackexchange.com/questions/216271",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87844/"
] |
I have many security plugins setup. Could someone tell me what changes I need to make to my [`.htaccess`](http://pastebin.com/6VkejW2R) file (while keeping as much of my current rule set as possible) to make pretty URLs work?
```
# BEGIN iThemes Security - Do not modify or remove this line
# iThemes Security Config Details: 2
# Enable HackRepair.com's blacklist feature - Security > Settings > Banned Users > Default Blacklist
# Start HackRepair.com Blacklist
RewriteEngine on
# Start Abuse Agent Blocking
RewriteCond %{HTTP_USER_AGENT} "^Mozilla.*Indy" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^Mozilla.*NEWT" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^$" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^Maxthon$" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^SeaMonkey$" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^Acunetix" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^binlar" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^BlackWidow" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^Bolt 0" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^BOT for JCE" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^Bot mailto\:craftbot@yahoo\.com" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^casper" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^checkprivacy" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^ChinaClaw" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^clshttp" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^cmsworldmap" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^comodo" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^Custo" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^Default Browser 0" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^diavol" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^DIIbot" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^DISCo" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^dotbot" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^Download Demon" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^eCatch" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^EirGrabber" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^EmailCollector" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^EmailSiphon" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^EmailWolf" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^Express WebPictures" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^extract" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^ExtractorPro" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^EyeNetIE" [NC,OR]
RewriteCond
# Protect System Files - Security > Settings > System Tweaks > System Files
<files .htaccess>
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order allow,deny
Deny from all
</IfModule>
</files>
<files readme.html>
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order allow,deny
Deny from all
</IfModule>
</files>
<files readme.txt>
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order allow,deny
Deny from all
</IfModule>
</files>
<files install.php>
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order allow,deny
Deny from all
</IfModule>
</files>
<files wp-config.php>
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order allow,deny
Deny from all
</IfModule>
</files>
# Disable Directory Browsing - Security > Settings > System Tweaks > Directory Browsing
Options -Indexes
<IfModule mod_rewrite.c>
RewriteEngine On
# Protect System Files - Security > Settings > System Tweaks > System Files
RewriteRule ^wp-admin/includes/ - [F]
RewriteRule !^wp-includes/ - [S=3]
RewriteCond %{SCRIPT_FILENAME} !^(.*)wp-includes/ms-files.php
RewriteRule ^wp-includes/[^/]+\.php$ - [F]
RewriteRule ^wp-includes/js/tinymce/langs/.+\.php - [F]
RewriteRule ^wp-includes/theme-compat/ - [F]
# Disable PHP in Uploads - Security > Settings > System Tweaks > Uploads
RewriteRule ^wp\-content/uploads/.*\.(?:php[1-6]?|pht|phtml?)$ - [NC,F]
# Filter Request Methods - Security > Settings > System Tweaks > Request Methods
RewriteCond %{REQUEST_METHOD} ^(TRACE|DELETE|TRACK) [NC]
RewriteRule ^.* - [F]
# Filter Suspicious Query Strings in the URL - Security > Settings > System Tweaks > Suspicious Query Strings
RewriteCond %{QUERY_STRING} \.\.\/ [NC,OR]
RewriteCond %{QUERY_STRING} ^.*\.(bash|git|hg|log|svn|swp|cvs) [NC,OR]
RewriteCond %{QUERY_STRING} etc/passwd [NC,OR]
RewriteCond %{QUERY_STRING} boot\.ini [NC,OR]
RewriteCond %{QUERY_STRING} ftp\: [NC,OR]
RewriteCond %{QUERY_STRING} http\: [NC,OR]
RewriteCond %{QUERY_STRING} https\: [NC,OR]
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|%3D) [NC,OR]
RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [NC,OR]
RewriteCond %{QUERY_STRING} ^.*(%24&x).* [NC,OR]
RewriteCond %{QUERY_STRING} ^.*(127\.0).* [NC,OR]
RewriteCond %{QUERY_STRING} ^.*(globals|encode|localhost|loopback).* [NC,OR]
RewriteCond %{QUERY_STRING} ^.*(request|concat|insert|union|declare).* [NC]
RewriteCond %{QUERY_STRING} !^loggedout=true
RewriteCond %{QUERY_STRING} !^action=jetpack-sso
RewriteCond %{QUERY_STRING} !^action=rp
RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in_.*$
RewriteCond %{HTTP_REFERER} !^http://maps\.googleapis\.com(.*)$
RewriteRule ^.* - [F]
# Filter Non-English Characters - Security > Settings > System Tweaks > Non-English Characters
RewriteCond %{QUERY_STRING} ^.*(%0|%A|%B|%C|%D|%E|%F).* [NC]
RewriteRule ^.* - [F]
# Reduce Comment Spam - Security > Settings > System Tweaks > Comment Spam
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} /wp-comments-post\.php$
RewriteCond %{HTTP_USER_AGENT} ^$ [OR]
RewriteCond %{HTTP_REFERER} !^https?://(([^/]+\.)?sn0w\.io|jetpack\.wordpress\.com/jetpack-comment)(/|$) [NC]
RewriteRule ^.* - [F]
</IfModule>
# END iThemes Security - Do not modify or remove this line
# BULLETPROOF .53.1 >>>>>>> SECURE .HTACCESS
# PHP/PHP.INI HANDLER/CACHE CODE
# Use BPS Custom Code to add php/php.ini Handler and Cache htaccess code and to save it permanently.
# Most Hosts do not have/use/require php/php.ini Handler htaccess code
# TURN OFF YOUR SERVER SIGNATURE
# Suppresses the footer line server version number and ServerName of the serving virtual host
ServerSignature Off
# DO NOT SHOW DIRECTORY LISTING
# Disallow mod_autoindex from displaying a directory listing
# If a 500 Internal Server Error occurs when activating Root BulletProof Mode
# copy the entire DO NOT SHOW DIRECTORY LISTING and DIRECTORY INDEX sections of code
# and paste it into BPS Custom Code and comment out Options -Indexes
# by adding a # sign in front of it.
# Example: #Options -Indexes
Options -Indexes
# DIRECTORY INDEX FORCE INDEX.PHP
# Use index.php as default directory index file. index.html will be ignored.
# If a 500 Internal Server Error occurs when activating Root BulletProof Mode
# copy the entire DO NOT SHOW DIRECTORY LISTING and DIRECTORY INDEX sections of code
# and paste it into BPS Custom Code and comment out DirectoryIndex
# by adding a # sign in front of it.
# Example: #DirectoryIndex index.php index.html /index.php
DirectoryIndex index.php index.html /index.php
# BRUTE FORCE LOGIN PAGE PROTECTION
# PLACEHOLDER ONLY
# Use BPS Custom Code to add Brute Force Login protection code and to save it permanently.
# See this link: http://forum.ait-pro.com/forums/topic/protect-login-page-from-brute-force-login-attacks/
# for more information.
# BPS ERROR LOGGING AND TRACKING
# Use BPS Custom Code to modify/edit/change this code and to save it permanently.
# BPS has premade 400 Bad Request, 403 Forbidden, 404 Not Found, 405 Method Not Allowed and
# 410 Gone template logging files that are used to track and log 400, 403, 404, 405 and 410 errors
# that occur on your website. When a hacker attempts to hack your website the hackers IP address,
# Host name, Request Method, Referering link, the file name or requested resource, the user agent
# of the hacker and the query string used in the hack attempt are logged.
# All BPS log files are htaccess protected so that only you can view them.
# The 400.php, 403.php, 404.php, 405.php and 410.php files are located in /wp-content/plugins/bulletproof-security/
# The 400, 403, 405 and 410 Error logging files are already set up and will automatically start logging errors
# after you install BPS and have activated BulletProof Mode for your Root folder.
# If you would like to log 404 errors you will need to copy the logging code in the BPS 404.php file
# to your Theme's 404.php template file. Simple instructions are included in the BPS 404.php file.
# You can open the BPS 404.php file using the WP Plugins Editor or manually editing the file.
# NOTE: By default WordPress automatically looks in your Theme's folder for a 404.php Theme template file.
ErrorDocument 400 /wp-content/plugins/bulletproof-security/400.php
ErrorDocument 401 default
ErrorDocument 403 /wp-content/plugins/bulletproof-security/403.php
ErrorDocument 404 /404.php
ErrorDocument 405 /wp-content/plugins/bulletproof-security/405.php
ErrorDocument 410 /wp-content/plugins/bulletproof-security/410.php
# DENY ACCESS TO PROTECTED SERVER FILES AND FOLDERS
# Use BPS Custom Code to modify/edit/change this code and to save it permanently.
# Files and folders starting with a dot: .htaccess, .htpasswd, .errordocs, .logs
RedirectMatch 403 \.(htaccess|htpasswd|errordocs|logs)$
# WP-ADMIN/INCLUDES
# Use BPS Custom Code to remove this code permanently.
RewriteEngine On
RewriteBase /
RewriteRule ^wp-admin/includes/ - [F]
RewriteRule !^wp-includes/ - [S=3]
RewriteRule ^wp-includes/[^/]+\.php$ - [F]
RewriteRule ^wp-includes/js/tinymce/langs/.+\.php - [F]
RewriteRule ^wp-includes/theme-compat/ - [F]
# WP REWRITE LOOP START
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# REQUEST METHODS FILTERED
# If you want to allow HEAD Requests use BPS Custom Code and copy
# this entire REQUEST METHODS FILTERED section of code to this BPS Custom Code
# text box: CUSTOM CODE REQUEST METHODS FILTERED.
# See the CUSTOM CODE REQUEST METHODS FILTERED help text for additional steps.
RewriteCond %{REQUEST_METHOD} ^(TRACE|DELETE|TRACK|DEBUG) [NC]
RewriteRule ^(.*)$ - [F]
RewriteCond %{REQUEST_METHOD} ^(HEAD) [NC]
RewriteRule ^(.*)$ - [R=405,L]
# PLUGINS/THEMES AND VARIOUS EXPLOIT FILTER SKIP RULES
# To add plugin/theme skip/bypass rules use BPS Custom Code.
# The [S] flag is used to skip following rules. Skip rule [S=12] will skip 12 following RewriteRules.
# The skip rules MUST be in descending consecutive number order: 12, 11, 10, 9...
# If you delete a skip rule, change the other skip rule numbers accordingly.
# Examples: If RewriteRule [S=5] is deleted than change [S=6] to [S=5], [S=7] to [S=6], etc.
# If you add a new skip rule above skip rule 12 it will be skip rule 13: [S=13]
# Adminer MySQL management tool data populate
RewriteCond %{REQUEST_URI} ^/wp-content/plugins/adminer/ [NC]
RewriteRule . - [S=12]
# Comment Spam Pack MU Plugin - CAPTCHA images not displaying
RewriteCond %{REQUEST_URI} ^/wp-content/mu-plugins/custom-anti-spam/ [NC]
RewriteRule . - [S=11]
# Peters Custom Anti-Spam display CAPTCHA Image
RewriteCond %{REQUEST_URI} ^/wp-content/plugins/peters-custom-anti-spam-image/ [NC]
RewriteRule . - [S=10]
# Status Updater plugin fb connect
RewriteCond %{REQUEST_URI} ^/wp-content/plugins/fb-status-updater/ [NC]
RewriteRule . - [S=9]
# Stream Video Player - Adding FLV Videos Blocked
RewriteCond %{REQUEST_URI} ^/wp-content/plugins/stream-video-player/ [NC]
RewriteRule . - [S=8]
# XCloner 404 or 403 error when updating settings
RewriteCond %{REQUEST_URI} ^/wp-content/plugins/xcloner-backup-and-restore/ [NC]
RewriteRule . - [S=7]
# BuddyPress Logout Redirect
RewriteCond %{QUERY_STRING} action=logout&redirect_to=http%3A%2F%2F(.*) [NC]
RewriteRule . - [S=6]
# redirect_to=
RewriteCond %{QUERY_STRING} redirect_to=(.*) [NC]
RewriteRule . - [S=5]
# Login Plugins Password Reset And Redirect 1
RewriteCond %{QUERY_STRING} action=resetpass&key=(.*) [NC]
RewriteRule . - [S=4]
# Login Plugins Password Reset And Redirect 2
RewriteCond %{QUERY_STRING} action=rp&key=(.*) [NC]
RewriteRule . - [S=3]
# TIMTHUMB FORBID RFI and MISC FILE SKIP/BYPASS RULE
# Use BPS Custom Code to modify/edit/change this code and to save it permanently.
# Remote File Inclusion (RFI) security rules
# Note: Only whitelist your additional domains or files if needed - do not whitelist hacker domains or files
RewriteCond %{QUERY_STRING} ^.*(http|https|ftp)(%3A|:)(%2F|/)(%2F|/)(w){0,3}.?(blogger|picasa|blogspot|tsunami|petapolitik|photobucket|imgur|imageshack|wordpress\.com|img\.youtube|tinypic\.com|upload\.wikimedia|kkc|start-thegame).*$ [NC,OR]
RewriteCond %{THE_REQUEST} ^.*(http|https|ftp)(%3A|:)(%2F|/)(%2F|/)(w){0,3}.?(blogger|picasa|blogspot|tsunami|petapolitik|photobucket|imgur|imageshack|wordpress\.com|img\.youtube|tinypic\.com|upload\.wikimedia|kkc|start-thegame).*$ [NC]
RewriteRule .* index.php [F]
#
# Example: Whitelist additional misc files: (example\.php|another-file\.php|phpthumb\.php|thumb\.php|thumbs\.php)
RewriteCond %{REQUEST_URI} (timthumb\.php|phpthumb\.php|thumb\.php|thumbs\.php) [NC]
# Example: Whitelist additional website domains: RewriteCond %{HTTP_REFERER} ^.*(YourWebsite.com|AnotherWebsite.com).*
RewriteCond %{HTTP_REFERER} ^.*sn0w.io.*
RewriteRule . - [S=1]
# BEGIN BPSQSE BPS QUERY STRING EXPLOITS
# The libwww-perl User Agent is forbidden - Many bad bots use libwww-perl modules, but some good bots use it too.
# Good sites such as W3C use it for their W3C-LinkChecker.
# Use BPS Custom Code to add or remove user agents temporarily or permanently from the
# User Agent filters directly below or to modify/edit/change any of the other security code rules below.
RewriteCond %{HTTP_USER_AGENT} (havij|libwww-perl|wget|python|nikto|curl|scan|java|winhttp|clshttp|loader) [NC,OR]
RewriteCond %{HTTP_USER_AGENT} (%0A|%0D|%27|%3C|%3E|%00) [NC,OR]
RewriteCond %{HTTP_USER_AGENT} (;|<|>|'|"|\)|\(|%0A|%0D|%22|%27|%28|%3C|%3E|%00).*(libwww-perl|wget|python|nikto|curl|scan|java|winhttp|HTTrack|clshttp|archiver|loader|email|harvest|extract|grab|miner) [NC,OR]
RewriteCond %{THE_REQUEST} (\?|\*|%2a)+(%20+|\\s+|%20+\\s+|\\s+%20+|\\s+%20+\\s+)HTTP(:/|/) [NC,OR]
RewriteCond %{THE_REQUEST} etc/passwd [NC,OR]
RewriteCond %{THE_REQUEST} cgi-bin [NC,OR]
RewriteCond %{THE_REQUEST} (%0A|%0D|\\r|\\n) [NC,OR]
RewriteCond %{REQUEST_URI} owssvr\.dll [NC,OR]
RewriteCond %{HTTP_REFERER} (%0A|%0D|%27|%3C|%3E|%00) [NC,OR]
RewriteCond %{HTTP_REFERER} \.opendirviewer\. [NC,OR]
RewriteCond %{HTTP_REFERER} users\.skynet\.be.* [NC,OR]
RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=http:// [NC,OR]
RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=(\.\.//?)+ [NC,OR]
RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=/([a-z0-9_.]//?)+ [NC,OR]
RewriteCond %{QUERY_STRING} \=PHP[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12} [NC,OR]
RewriteCond %{QUERY_STRING} (\.\./|%2e%2e%2f|%2e%2e/|\.\.%2f|%2e\.%2f|%2e\./|\.%2e%2f|\.%2e/) [NC,OR]
RewriteCond %{QUERY_STRING} ftp\: [NC,OR]
RewriteCond %{QUERY_STRING} http\: [NC,OR]
RewriteCond %{QUERY_STRING} https\: [NC,OR]
RewriteCond %{QUERY_STRING} \=\|w\| [NC,OR]
RewriteCond %{QUERY_STRING} ^(.*)/self/(.*)$ [NC,OR]
RewriteCond %{QUERY_STRING} ^(.*)cPath=http://(.*)$ [NC,OR]
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (\<|%3C).*embed.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (<|%3C)([^e]*e)+mbed.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (\<|%3C).*object.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (<|%3C)([^o]*o)+bject.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (\<|%3C).*iframe.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (<|%3C)([^i]*i)+frame.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [NC,OR]
RewriteCond %{QUERY_STRING} base64_(en|de)code[^(]*\([^)]*\) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} ^.*(\(|\)|<|>|%3c|%3e).* [NC,OR]
RewriteCond %{QUERY_STRING} ^.*(\x00|\x04|\x08|\x0d|\x1b|\x20|\x3c|\x3e|\x7f).* [NC,OR]
RewriteCond %{QUERY_STRING} (NULL|OUTFILE|LOAD_FILE) [OR]
RewriteCond %{QUERY_STRING} (\.{1,}/)+(motd|etc|bin) [NC,OR]
RewriteCond %{QUERY_STRING} (localhost|loopback|127\.0\.0\.1) [NC,OR]
RewriteCond %{QUERY_STRING} (<|>|'|%0A|%0D|%27|%3C|%3E|%00) [NC,OR]
RewriteCond %{QUERY_STRING} concat[^\(]*\( [NC,OR]
RewriteCond %{QUERY_STRING} union([^s]*s)+elect [NC,OR]
RewriteCond %{QUERY_STRING} union([^a]*a)+ll([^s]*s)+elect [NC,OR]
RewriteCond %{QUERY_STRING} \-[sdcr].*(allow_url_include|allow_url_fopen|safe_mode|disable_functions|auto_prepend_file) [NC,OR]
RewriteCond %{QUERY_STRING} (;|<|>|'|"|\)|%0A|%0D|%22|%27|%3C|%3E|%00).*(/\*|union|select|insert|drop|delete|update|cast|create|char|convert|alter|declare|order|script|set|md5|benchmark|encode) [NC,OR]
RewriteCond %{QUERY_STRING} (sp_executesql) [NC]
RewriteRule ^(.*)$ - [F]
# END BPSQSE BPS QUERY STRING EXPLOITS
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# WP REWRITE LOOP END
# DENY BROWSER ACCESS TO THESE FILES
# Use BPS Custom Code to modify/edit/change this code and to save it permanently.
# wp-config.php, bb-config.php, php.ini, php5.ini, readme.html
# To be able to view these files from a Browser, replace 127.0.0.1 with your actual
# current IP address. Comment out: #Deny from all and Uncomment: Allow from 127.0.0.1
# Note: The BPS System Info page displays which modules are loaded on your server.
<FilesMatch "^(wp-config\.php|php\.ini|php5\.ini|readme\.html|bb-config\.php)">
Order Allow,Deny
Deny from all
#Allow from 127.0.0.1
</FilesMatch>
# HOTLINKING/FORBID COMMENT SPAMMERS/BLOCK BOTS/BLOCK IP/REDIRECT CODE
# PLACEHOLDER ONLY
# Use BPS Custom Code to add custom code and save it permanently here.
# BEGIN WordPress
# END WordPress
```
|
Your htaccess do not have the default wordpress related rules, go to the permalink page and save, if it it doesn't help turn off plugins.
|
216,284 |
<p>I am trying to implement a new tab next to Media Library. I couldn't find solution to implement this. I found an example how to implement a new tab in this link: <a href="https://gist.github.com/Fab1en/4586865" rel="nofollow noreferrer">https://gist.github.com/Fab1en/4586865</a> However the tab doesn't show up in the modal form triggered by Add Media button. But if I call the media popup for Featured Image or any other custom button the "New Tab" I created shows up. I am really lost here, not sure why those tabs show up in one place and don't in another. </p>
<p>Thank you</p>
<p><a href="https://i.stack.imgur.com/PxWSJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PxWSJ.jpg" alt="enter image description here"></a></p>
|
[
{
"answer_id": 216395,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 3,
"selected": true,
"text": "<p>It's not a tab but you might be able to get started with an upload button. Check out <a href=\"https://core.trac.wordpress.org/browser/tags/4.4.1/src/wp-admin/includes/media.php#L1826\" rel=\"nofollow\"><code>pre-upload-ui</code></a> and some actions that follow. Namely <a href=\"https://core.trac.wordpress.org/browser/tags/4.4.1/src/wp-admin/includes/media.php#L1902\" rel=\"nofollow\"><code>pre-plupload-upload-ui</code></a> and <a href=\"https://core.trac.wordpress.org/browser/tags/4.4.1/src/wp-admin/includes/media.php#L1956\" rel=\"nofollow\"><code>post-upload-ui</code></a>.</p>\n\n<p>This will add a couple buttons to the '<strong>Upload Files</strong>' tab and to '<strong>Media > Add New</strong>'.</p>\n\n<p><strong>BUTTONS</strong></p>\n\n<pre><code>add_action( 'pre-plupload-upload-ui', 'wpse_20160202_pre_plupload_upload_ui' );\nadd_action( 'post-upload-ui', 'wpse_20160202_post_upload_ui' );\n\nfunction wpse_20160202_pre_plupload_upload_ui()\n{\n # see https://core.trac.wordpress.org/browser/tags/4.4.1/src/wp-admin/includes/media.php#L1902\n\n print '<button onclick=\"javascript:alert(\\'Upload From Dropbox\\');\" id=\"db-upload-btn\" class=\"button media-button button-primary button-large\" style=\"margin-bottom:10px;\">Upload From Dropbox</button>';\n}\n\n\nfunction wpse_20160202_post_upload_ui()\n{\n # see wp-includes/media-template.php\n\n print '<button onclick=\"javascript:alert(\\'Another Upload From Dropbox\\');\" id=\"db-upload-btn\" class=\"button media-button button-primary button-large\" style=\"margin-bottom:10px;\">Another Upload From Dropbox</button>';\n}\n</code></pre>\n\n<p><strong>TABS</strong></p>\n\n<p>Adding this here just to show the alternate. <a href=\"https://developer.wordpress.org/reference/functions/media_upload_tabs/\" rel=\"nofollow\"><code>media_upload_tabs</code></a> will help you control which tabs are included in the side and <a href=\"https://developer.wordpress.org/reference/hooks/media_upload_tab/\" rel=\"nofollow\"><code>media_upload_{tab}</code></a> to render the contents using <a href=\"http://codex.wordpress.org/Function_Reference/wp_iframe\" rel=\"nofollow\"><code>wp_iframe()</code></a>.</p>\n\n<pre><code>add_filter( 'media_upload_tabs', 'media_upload_tabs__tab_slug' );\n\nfunction media_upload_tabs__tab_slug( $tabs ) {\n $newtab = array ( 'tab_slug' => 'Your Tab Name' );\n return array_merge( $tabs, $newtab );\n}\n\nadd_action( 'media_upload_tab_slug', 'media_upload_tab_slug__content' );\n\nfunction media_upload_tab_slug__content() {\n wp_iframe( 'media_upload_tab_slug_content__iframe' );\n}\n\nfunction media_upload_tab_slug_content__iframe() {\n ?>\n <div>tab_slug: Add your content here.</div><?php\n}\n</code></pre>\n"
},
{
"answer_id": 409215,
"author": "Adeleye Ayodeji",
"author_id": 166972,
"author_profile": "https://wordpress.stackexchange.com/users/166972",
"pm_score": 0,
"selected": false,
"text": "<p>I manage to solve this problem after many days of research.</p>\n<p>For a better understanding, you can check my short video tutorial: <a href=\"https://www.youtube.com/watch?v=LEr-WmVMkAQ\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=LEr-WmVMkAQ</a></p>\n<pre class=\"lang-js prettyprint-override\"><code>var frame = wp.media.view.MediaFrame.Post;\nwp.media.view.MediaFrame.Post = frame.extend({\n initialize: function () {\n frame.prototype.initialize.apply(this, arguments);\n\n var State = wp.media.controller.State.extend({\n insert: function () {\n console.log("Something...");\n this.frame.close();\n }\n });\n\n this.states.add([\n new State({\n id: "ademedia",\n search: false,\n title: "Ade Media"\n })\n ]);\n\n //on render\n this.on("content:render:ademedia", this.renderAdemediaContent, this);\n },\n browseRouter: function (routerView) {\n routerView.set({\n upload: {\n text: wp.media.view.l10n.uploadFilesTitle,\n priority: 20\n },\n ademedia: {\n text: "Ade Media",\n priority: 30\n },\n browse: {\n text: wp.media.view.l10n.mediaLibraryTitle,\n priority: 40\n }\n });\n },\n renderAdemediaContent: function () {\n var AdemediaContent = wp.Backbone.View.extend({\n tagName: "div",\n className: "ademediacontent",\n template: wp.template("ademedia"),\n active: !1,\n toolbar: null,\n frame: null\n });\n\n var view = new AdemediaContent();\n\n this.content.set(view);\n }\n});\n\n\n</code></pre>\n"
}
] |
2016/02/01
|
[
"https://wordpress.stackexchange.com/questions/216284",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87763/"
] |
I am trying to implement a new tab next to Media Library. I couldn't find solution to implement this. I found an example how to implement a new tab in this link: <https://gist.github.com/Fab1en/4586865> However the tab doesn't show up in the modal form triggered by Add Media button. But if I call the media popup for Featured Image or any other custom button the "New Tab" I created shows up. I am really lost here, not sure why those tabs show up in one place and don't in another.
Thank you
[](https://i.stack.imgur.com/PxWSJ.jpg)
|
It's not a tab but you might be able to get started with an upload button. Check out [`pre-upload-ui`](https://core.trac.wordpress.org/browser/tags/4.4.1/src/wp-admin/includes/media.php#L1826) and some actions that follow. Namely [`pre-plupload-upload-ui`](https://core.trac.wordpress.org/browser/tags/4.4.1/src/wp-admin/includes/media.php#L1902) and [`post-upload-ui`](https://core.trac.wordpress.org/browser/tags/4.4.1/src/wp-admin/includes/media.php#L1956).
This will add a couple buttons to the '**Upload Files**' tab and to '**Media > Add New**'.
**BUTTONS**
```
add_action( 'pre-plupload-upload-ui', 'wpse_20160202_pre_plupload_upload_ui' );
add_action( 'post-upload-ui', 'wpse_20160202_post_upload_ui' );
function wpse_20160202_pre_plupload_upload_ui()
{
# see https://core.trac.wordpress.org/browser/tags/4.4.1/src/wp-admin/includes/media.php#L1902
print '<button onclick="javascript:alert(\'Upload From Dropbox\');" id="db-upload-btn" class="button media-button button-primary button-large" style="margin-bottom:10px;">Upload From Dropbox</button>';
}
function wpse_20160202_post_upload_ui()
{
# see wp-includes/media-template.php
print '<button onclick="javascript:alert(\'Another Upload From Dropbox\');" id="db-upload-btn" class="button media-button button-primary button-large" style="margin-bottom:10px;">Another Upload From Dropbox</button>';
}
```
**TABS**
Adding this here just to show the alternate. [`media_upload_tabs`](https://developer.wordpress.org/reference/functions/media_upload_tabs/) will help you control which tabs are included in the side and [`media_upload_{tab}`](https://developer.wordpress.org/reference/hooks/media_upload_tab/) to render the contents using [`wp_iframe()`](http://codex.wordpress.org/Function_Reference/wp_iframe).
```
add_filter( 'media_upload_tabs', 'media_upload_tabs__tab_slug' );
function media_upload_tabs__tab_slug( $tabs ) {
$newtab = array ( 'tab_slug' => 'Your Tab Name' );
return array_merge( $tabs, $newtab );
}
add_action( 'media_upload_tab_slug', 'media_upload_tab_slug__content' );
function media_upload_tab_slug__content() {
wp_iframe( 'media_upload_tab_slug_content__iframe' );
}
function media_upload_tab_slug_content__iframe() {
?>
<div>tab_slug: Add your content here.</div><?php
}
```
|
216,286 |
<p>How do I get something like below? My code is like this:</p>
<pre><code>wp_nav_menu(
array(
'theme_location' => 'header_menu',
'container_id' => 'menu',
'link_before' => '<span data-hover="link-text-here">',
'link_after' => '</span>',
)
);
</code></pre>
<p>I want to get the result below:</p>
<pre><code><nav class="main-nav">
<li><a href="#"><span data-hover="Home">Home</span></a></li>
<li><a href="#"><span data-hover="Proyects">Proyects</span></a></li>
</nav>
</code></pre>
<p>Please advise me.</p>
|
[
{
"answer_id": 216287,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 3,
"selected": true,
"text": "<h1>Solution 1: Using customize walker</h1>\n<p>I got some idea from <a href=\"https://wordpress.stackexchange.com/questions/72651/add-span-class-inside-wp-nav-menu-link-anchor-tag\">add span class inside wp_nav_menu link anchor tag</a> and made some changes for your requirements.</p>\n<p><strong>1. Add this code below to your functions.php first.</strong></p>\n<pre><code>class Nav_Walker_Nav_Menu extends Walker_Nav_Menu{\n function start_el(&$output, $item, $depth, $args){\n global $wp_query;\n $indent = ( $depth ) ? str_repeat( "\\t", $depth ) : '';\n $class_names = $value = '';\n $classes = empty( $item->classes ) ? array() : (array) $item->classes;\n $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );\n $class_names = ' class="'. esc_attr( $class_names ) . '"';\n\n $output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>';\n\n $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';\n $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';\n $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';\n $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';\n\n\n $description = ! empty( $item->description ) ? '<span>'.esc_attr( $item->description ).'</span>' : '';\n\n\n\n $item_output = $args->before;\n $item_output .= '<a'. $attributes .'><span data-hover="'. $item->title .'">';\n $item_output .=$args->link_before .apply_filters( 'the_title', $item->title, $item->ID );\n $item_output .= $description.$args->link_after;\n $item_output .= '</span></a>';\n $item_output .= $args->after;\n\n $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );\n }\n}\n</code></pre>\n<p><strong>2. Add code below to your <code>header.php</code> where your <code>wp_nav_menu</code> is installed.</strong>\nExplained below is the code so it installs the new custom menu in this case would be <code>Nav_Walker_Nav_Menu</code>.</p>\n<pre><code><?php wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary', 'walker' => new Nav_Walker_Nav_Menu() ) ); ?>\n</code></pre>\n<p>Hope this help you well!</p>\n<h1>Solution 2: Using <code>wp_list_pages</code></h1>\n<p>Please check out <a href=\"http://codex.wordpress.org/Template_Tags/wp_list_pages\" rel=\"nofollow noreferrer\">this page</a> . You can see their snippet. If you put the spans around the link tags you can use <code>link_before</code> and <code>link_after</code></p>\n<pre><code>wp_list_pages("link_before=<span data-hover="link-text-here">&link_after=</span>");\n</code></pre>\n"
},
{
"answer_id": 216288,
"author": "Saiful Islam",
"author_id": 83449,
"author_profile": "https://wordpress.stackexchange.com/users/83449",
"pm_score": 2,
"selected": false,
"text": "<p>Please try the following:</p>\n\n<pre><code>wp_nav_menu(\n array(\n 'theme_location' => 'header_menu',\n 'container_id' => 'menu',\n 'walker' => new description_walker()\n )\n);\n</code></pre>\n\n<p>And add this to <code>functions.php</code>:</p>\n\n<pre><code>class description_walker extends Walker_Nav_Menu{\n function start_el(&$output, $item, $depth, $args){\n global $wp_query;\n $indent = ( $depth ) ? str_repeat( \"\\t\", $depth ) : '';\n $class_names = $value = '';\n $classes = empty( $item->classes ) ? array() : (array) $item->classes;\n $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );\n $class_names = ' class=\"'. esc_attr( $class_names ) . '\"';\n\n $output .= $indent . '<li id=\"menu-item-'. $item->ID . '\"' . $value . $class_names .'>';\n\n $attributes = ! empty( $item->attr_title ) ? ' title=\"' . esc_attr( $item->attr_title ) .'\"' : '';\n $attributes .= ! empty( $item->target ) ? ' target=\"' . esc_attr( $item->target ) .'\"' : '';\n $attributes .= ! empty( $item->xfn ) ? ' rel=\"' . esc_attr( $item->xfn ) .'\"' : '';\n $attributes .= ! empty( $item->url ) ? ' href=\"' . esc_attr( $item->url ) .'\"' : '';\n\n\n $description = ! empty( $item->description ) ? '<span>'.esc_attr( $item->description ).'</span>' : '';\n\n\n\n $item_output = $args->before;\n $item_output .= '<a'. $attributes .'><span>';\n $item_output .=$args->link_before .apply_filters( 'the_title', $item->title, $item->ID );\n $item_output .= $description.$args->link_after;\n $item_output .= '<span></a>';\n $item_output .= $args->after;\n\n $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );\n }\n}\n</code></pre>\n\n<p>This way you can easily add a span tag... </p>\n"
},
{
"answer_id": 305711,
"author": "Daren Zammit",
"author_id": 121801,
"author_profile": "https://wordpress.stackexchange.com/users/121801",
"pm_score": 4,
"selected": false,
"text": "<p>Since version 4.4.0 the 'nav_menu_item_args' filter was added. This allows you to set 'link_before' and 'link_after' attributes for each item.</p>\n\n<pre><code>add_filter('nav_menu_item_args', function ($args, $item, $depth) {\n if ($args->theme_location == 'header_menu') {\n $title = apply_filters('the_title', $item->title, $item->ID);\n $args->link_before = '<span data-hover=\"' . $title . '\">';\n $args->link_after = '</span>';\n }\n return $args;\n}, 10, 3);\n</code></pre>\n"
}
] |
2016/02/01
|
[
"https://wordpress.stackexchange.com/questions/216286",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85768/"
] |
How do I get something like below? My code is like this:
```
wp_nav_menu(
array(
'theme_location' => 'header_menu',
'container_id' => 'menu',
'link_before' => '<span data-hover="link-text-here">',
'link_after' => '</span>',
)
);
```
I want to get the result below:
```
<nav class="main-nav">
<li><a href="#"><span data-hover="Home">Home</span></a></li>
<li><a href="#"><span data-hover="Proyects">Proyects</span></a></li>
</nav>
```
Please advise me.
|
Solution 1: Using customize walker
==================================
I got some idea from [add span class inside wp\_nav\_menu link anchor tag](https://wordpress.stackexchange.com/questions/72651/add-span-class-inside-wp-nav-menu-link-anchor-tag) and made some changes for your requirements.
**1. Add this code below to your functions.php first.**
```
class Nav_Walker_Nav_Menu extends Walker_Nav_Menu{
function start_el(&$output, $item, $depth, $args){
global $wp_query;
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$class_names = $value = '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
$class_names = ' class="'. esc_attr( $class_names ) . '"';
$output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>';
$attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
$attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
$attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
$attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';
$description = ! empty( $item->description ) ? '<span>'.esc_attr( $item->description ).'</span>' : '';
$item_output = $args->before;
$item_output .= '<a'. $attributes .'><span data-hover="'. $item->title .'">';
$item_output .=$args->link_before .apply_filters( 'the_title', $item->title, $item->ID );
$item_output .= $description.$args->link_after;
$item_output .= '</span></a>';
$item_output .= $args->after;
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
}
```
**2. Add code below to your `header.php` where your `wp_nav_menu` is installed.**
Explained below is the code so it installs the new custom menu in this case would be `Nav_Walker_Nav_Menu`.
```
<?php wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary', 'walker' => new Nav_Walker_Nav_Menu() ) ); ?>
```
Hope this help you well!
Solution 2: Using `wp_list_pages`
=================================
Please check out [this page](http://codex.wordpress.org/Template_Tags/wp_list_pages) . You can see their snippet. If you put the spans around the link tags you can use `link_before` and `link_after`
```
wp_list_pages("link_before=<span data-hover="link-text-here">&link_after=</span>");
```
|
216,291 |
<p>I want to upload images in a specific folder like <code>http://example.com/custom_folder</code>.</p>
<p>Note: Not in <code>http://example.com/wp-content/uploads/custom_folder/image1.jpg</code></p>
|
[
{
"answer_id": 216399,
"author": "Aftab",
"author_id": 64614,
"author_profile": "https://wordpress.stackexchange.com/users/64614",
"pm_score": 0,
"selected": false,
"text": "<p>Add this in your wp-config.php file</p>\n\n<p><code>define( 'UPLOADS', 'custom_folder' );</code></p>\n\n<p>And make sure to add this code before that.</p>\n\n<p><code>require_once( ABSPATH.’wp-settings.php’ );</code></p>\n\n<p>For more information you can check here\n<a href=\"https://premium.wpmudev.org/blog/change-default-wordpress-uploads-folder/\" rel=\"nofollow\">https://premium.wpmudev.org/blog/change-default-wordpress-uploads-folder/</a></p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 216500,
"author": "Jan Beck",
"author_id": 18760,
"author_profile": "https://wordpress.stackexchange.com/users/18760",
"pm_score": 1,
"selected": false,
"text": "<p>The filter you'd want to use is <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/upload_dir\" rel=\"nofollow\"><code>upload_dir</code></a>. Check for the <code>post_id</code> key in the <code>$_REQUEST</code> super global array to be equal to the page ID you want to limit this for. Then change the uploads directory accordingly.</p>\n\n<p>In code:</p>\n\n<pre><code>add_filter( 'upload_dir', 'my_uploads_dir' );\n\nfunction my_uploads_dir( $param ){\n\n // change this to the ID of your page\n $post_id = 135;\n\n // skips all uploads not associated with your page\n if ( empty( $_REQUEST['post_id'] ) || $_REQUEST['post_id'] != $post_id ) {\n return $param;\n }\n\n // set the name of your custom dir relative to WP root\n $mydir = 'awesome';\n\n $param['path'] = $param['basedir'] = ABSPATH . $mydir;\n $param['url'] = $param['baseurl'] = site_url('/') . $mydir;\n\n // ignore date-based sorting\n $param['subdir'] = '';\n\n return $param;\n}\n</code></pre>\n\n<p>Where <code>$mydir</code> corresponds to your custom directory in the WordPress install root. </p>\n"
},
{
"answer_id": 216660,
"author": "Jakir Hossain",
"author_id": 68472,
"author_profile": "https://wordpress.stackexchange.com/users/68472",
"pm_score": 2,
"selected": true,
"text": "<p>Try this</p>\n\n<pre><code>add_filter('upload_dir', 'upload_image_specific_calback');\nfunction upload_image_specific_calback( $param ){\n\n //$_GET['post'] which is your target post like 10 is post id.\n //After click update button.\n if(isset($_GET['post'])){\n if($_GET['post'] == 10){\n $param = array(\n 'path' => get_home_path().'logos',\n 'url' => home_url().'/logos',\n 'subdir' => '',\n 'basedir' => get_home_path(),\n 'baseurl' => home_url(),\n 'error' => false\n ); \n }\n }\n\n //$_POST['post_id'] which is your target post like 10 is post id.\n //instant upload time before save\n if(isset($_POST['post_id'])){ \n if($_POST['post_id'] == 10) {\n $param = array(\n 'path' => get_home_path().'logos',\n 'url' => home_url().'/logos',\n 'subdir' => '',\n 'basedir' => get_home_path(),\n 'baseurl' => home_url(),\n 'error' => false\n );\n } \n }\n\n error_log(\"path={$param['path']}\"); \n error_log(\"url={$param['url']}\");\n error_log(\"subdir={$param['subdir']}\");\n error_log(\"basedir={$param['basedir']}\");\n error_log(\"baseurl={$param['baseurl']}\");\n error_log(\"error={$param['error']}\"); \n return $param;\n}\n</code></pre>\n"
}
] |
2016/02/01
|
[
"https://wordpress.stackexchange.com/questions/216291",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87853/"
] |
I want to upload images in a specific folder like `http://example.com/custom_folder`.
Note: Not in `http://example.com/wp-content/uploads/custom_folder/image1.jpg`
|
Try this
```
add_filter('upload_dir', 'upload_image_specific_calback');
function upload_image_specific_calback( $param ){
//$_GET['post'] which is your target post like 10 is post id.
//After click update button.
if(isset($_GET['post'])){
if($_GET['post'] == 10){
$param = array(
'path' => get_home_path().'logos',
'url' => home_url().'/logos',
'subdir' => '',
'basedir' => get_home_path(),
'baseurl' => home_url(),
'error' => false
);
}
}
//$_POST['post_id'] which is your target post like 10 is post id.
//instant upload time before save
if(isset($_POST['post_id'])){
if($_POST['post_id'] == 10) {
$param = array(
'path' => get_home_path().'logos',
'url' => home_url().'/logos',
'subdir' => '',
'basedir' => get_home_path(),
'baseurl' => home_url(),
'error' => false
);
}
}
error_log("path={$param['path']}");
error_log("url={$param['url']}");
error_log("subdir={$param['subdir']}");
error_log("basedir={$param['basedir']}");
error_log("baseurl={$param['baseurl']}");
error_log("error={$param['error']}");
return $param;
}
```
|
216,337 |
<p>I have 2 custom post types: <code>software</code> and <code>hardware</code>. For SEO reasons I would like to have the permalinks of single <code>software</code> and <code>hardware</code> pages like: </p>
<pre><code>https://domain.com/custom-post-name/
</code></pre>
<p>But as default WordPress adds post-type slug on it like: </p>
<pre><code>https://domain.com/post-type-slug/custom-post-name/
</code></pre>
<p>I've removed the slug with <a href="http://www.markwarddesign.com/2014/02/remove-custom-post-type-slug-permalink/" rel="nofollow noreferrer">following script</a> that makes a replacement of the string. Now the single page is reachable with both urls described above and Google search console find 2 pages with the exact same content which is not good for SEO.
Is it possible to change the complete structure of a permalink and get rid of custom post type slug?</p>
<pre><code>register_post_type( 'hardware',
array (
'labels' => $labels,
'has_archive' => true,
'public' => true,
'supports' => array( 'title', 'editor', 'excerpt', 'custom-fields', 'thumbnail' ),
'taxonomies' => array( 'hardware-post_tag', 'hardware-category' ),
'exclude_from_search' => false,
'capability_type' => 'post',
'rewrite' => array( 'slug' => 'hardware' ),
)
);
</code></pre>
<hr>
|
[
{
"answer_id": 216470,
"author": "Rico",
"author_id": 63388,
"author_profile": "https://wordpress.stackexchange.com/users/63388",
"pm_score": 0,
"selected": false,
"text": "<p>SOLVED</p>\n\n<p>with usage of <code>$wp_rewrite</code> you can add a new permalink structure</p>\n\n<pre><code>add_action('init', 'my_custom_rewrite');\nfunction my_custom_rewrite() {\n global $wp_rewrite;\n $wp_rewrite->add_permastruct('hardware', '/%customname%/', false);\n $wp_rewrite->add_permastruct('produkt', '/%customname%/', false);\n $wp_rewrite->flush_rules();\n}\n</code></pre>\n\n<p>then you replace your custom tag with <code>str_replace</code> when you filter the link url </p>\n\n<pre><code>add_filter( 'post_type_link', 'my_custom_permalinks', 10, 2 );\nfunction my_custom_permalinks( $permalink, $post ) {\n return str_replace( '%customname%/', $post->post_name, $permalink );\n}\n</code></pre>\n\n<p><strong>NOTE: if you use this function the way is written (removing the post type slug from permalink) you can expect bad issues cause there is no control if you make a custom post permalink the same as a page or standard post</strong> </p>\n"
},
{
"answer_id": 253325,
"author": "Mikhail",
"author_id": 88888,
"author_profile": "https://wordpress.stackexchange.com/users/88888",
"pm_score": 3,
"selected": false,
"text": "<p>Note one Important thing to the above answer:</p>\n\n<p>While it'll work fine from the first sight it will cause performance problems.\nAll this code will be called on <code>init</code> hook so every page load will cause it to run and <code>flush_rules()</code> is very time expensive. </p>\n\n<p>So it's recomended to call flush rules upon theme\\plugin activation only. Also you can use <code>add_permastruct</code> functions without need to access <code>global $wp_rewrite</code></p>\n\n<p>Final improved solution would be:</p>\n\n<pre><code>add_action('init', 'my_custom_rewrite'); \nfunction my_custom_rewrite() {\n\n add_permastruct('hardware', '/%customname%/', false);\n add_permastruct('produkt', '/%customname%/', false);\n}\n\nadd_filter( 'post_type_link', 'my_custom_permalinks', 10, 2 );\nfunction my_custom_permalinks( $permalink, $post ) {\n return str_replace( '%customname%/', $post->post_name, $permalink );\n}\n\n /* in case for plugin */\nregister_activation_hook(__FILE__,'my_custom_plugin_activate');\nfunction my_custom_plugin_activate() {\n flush_rewrite_rules();\n}\n\n\n/* in case of custom Theme in Functions.php */\nadd_action('after_switch_theme', 'mytheme_setup');\nfunction mytheme_setup () {\n flush_rewrite_rules();\n}\n</code></pre>\n"
},
{
"answer_id": 381945,
"author": "joshjellel",
"author_id": 198534,
"author_profile": "https://wordpress.stackexchange.com/users/198534",
"pm_score": 0,
"selected": false,
"text": "<p>Anyone coming across this question who has encountered the dreaded link rot with the "following script" link mentioned in the question, here's the script <a href=\"https://web.archive.org/web/20200805071318/https://www.markwarddesign.com/2014/02/12/remove-custom-post-type-slug-permalink/\" rel=\"nofollow noreferrer\">courtesy of the Wayback Machine</a>, with a correction to what I believe was an error in the code:</p>\n<pre><code>/**\n * Remove the slug from published post permalinks. Only affect our CPT though.\n */\nfunction vipx_remove_cpt_slug( $post_link, $post, $leavename ) {\n if ( ! in_array( $post->post_type, array( 'your_post_type' ) ) || 'publish' != $post->post_status )\n return $post_link;\n $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );\n return $post_link;\n}\nadd_filter( 'post_type_link', 'vipx_remove_cpt_slug', 10, 3 );\n\nfunction vipx_parse_request_tricksy( $query ) {\n // Only noop the main query\n if ( ! $query->is_main_query() )\n return;\n // Only noop our very specific rewrite rule match\n if ( 2 != count( $query->query )\n || ! isset( $query->query['page'] ) )\n return;\n // 'name' will be set if post permalinks are just post_name, otherwise the page rule will match\n if ( ! empty( $query->query['name'] ) )\n $query->set( 'post_type', array( 'post', 'your_post_type', 'page' ) );\n}\nadd_action( 'pre_get_posts', 'vipx_parse_request_tricksy' );\n</code></pre>\n<p>Along with Mikhail's revision of 3ky's own solution, if like me it wasn't immediately obvious to you, I found it necessary to implement the <code>vipx_parse_request_tricksy()</code> function and corresponding action. But the <code>vipx_remove_cpt_slug()</code> function duplicates what <code>my_custom_permalinks()</code> does, so both aren't necessary—pick one?</p>\n"
},
{
"answer_id": 392526,
"author": "WoodrowShigeru",
"author_id": 143000,
"author_profile": "https://wordpress.stackexchange.com/users/143000",
"pm_score": 1,
"selected": false,
"text": "<p>I managed to solve it using <a href=\"https://developer.wordpress.org/reference/hooks/field_no_prefix_save_pre/\" rel=\"nofollow noreferrer\"><code>{$field_no_prefix}_save_pre</code></a> with <code>post_name</code>.</p>\n<pre><code>/**\n * Customize permalinks.\n *\n * @param string $post_name\n *\n * @return string\n * Returns a name-SKU combo for products, if all components are available.\n */\nfunction my_custom_permalinks( $post_name ) {\n\n if (\n ($_POST['post_type'] !== 'product')\n || ($_POST['post_status'] === 'auto-draft')\n ) {\n return $post_name;\n }\n\n $post_name = sanitize_title_with_dashes(\n { modify $_POST['post_title'] as you please }\n );\n\n return $post_name;\n}\nadd_filter('name_save_pre', 'my_custom_permalinks', 1, 1);\n</code></pre>\n"
}
] |
2016/02/01
|
[
"https://wordpress.stackexchange.com/questions/216337",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63388/"
] |
I have 2 custom post types: `software` and `hardware`. For SEO reasons I would like to have the permalinks of single `software` and `hardware` pages like:
```
https://domain.com/custom-post-name/
```
But as default WordPress adds post-type slug on it like:
```
https://domain.com/post-type-slug/custom-post-name/
```
I've removed the slug with [following script](http://www.markwarddesign.com/2014/02/remove-custom-post-type-slug-permalink/) that makes a replacement of the string. Now the single page is reachable with both urls described above and Google search console find 2 pages with the exact same content which is not good for SEO.
Is it possible to change the complete structure of a permalink and get rid of custom post type slug?
```
register_post_type( 'hardware',
array (
'labels' => $labels,
'has_archive' => true,
'public' => true,
'supports' => array( 'title', 'editor', 'excerpt', 'custom-fields', 'thumbnail' ),
'taxonomies' => array( 'hardware-post_tag', 'hardware-category' ),
'exclude_from_search' => false,
'capability_type' => 'post',
'rewrite' => array( 'slug' => 'hardware' ),
)
);
```
---
|
Note one Important thing to the above answer:
While it'll work fine from the first sight it will cause performance problems.
All this code will be called on `init` hook so every page load will cause it to run and `flush_rules()` is very time expensive.
So it's recomended to call flush rules upon theme\plugin activation only. Also you can use `add_permastruct` functions without need to access `global $wp_rewrite`
Final improved solution would be:
```
add_action('init', 'my_custom_rewrite');
function my_custom_rewrite() {
add_permastruct('hardware', '/%customname%/', false);
add_permastruct('produkt', '/%customname%/', false);
}
add_filter( 'post_type_link', 'my_custom_permalinks', 10, 2 );
function my_custom_permalinks( $permalink, $post ) {
return str_replace( '%customname%/', $post->post_name, $permalink );
}
/* in case for plugin */
register_activation_hook(__FILE__,'my_custom_plugin_activate');
function my_custom_plugin_activate() {
flush_rewrite_rules();
}
/* in case of custom Theme in Functions.php */
add_action('after_switch_theme', 'mytheme_setup');
function mytheme_setup () {
flush_rewrite_rules();
}
```
|
216,338 |
<p>I want to create a post type / format where I can create list type posts... For example... </p>
<pre><code>h1.Title: The List Post Title like "Best Salads..."
- Intro paragraph
h2. Best Veg Salads
- Intro
-- h3. Salad #1
-- h3. Salad #2
..
-- h3. Salad #X
h2. Best Non-Veg Salads
- Intro
-- h3. NV Salad #1
-- h3. NV Salad #2
..
-- h3. MV Salad #X
..
..
h2. Best XYZ Salads
- Intro
-- h3. Salad #1
-- h3. Salad #2
..
-- h3. Salad #X
Footer text...
</code></pre>
<p>Essentially each entry is a text field.
So I should be able to add any number of headings and subheadings in the post edit screen.</p>
<p>Note: I am not trying to create a post-type as salad. Salad is an example of one of the many published list posts. I am trying to create a site where I can post list type posts...</p>
<p>How can I achieve this.... Any ideas and suggestions would be great... </p>
|
[
{
"answer_id": 216340,
"author": "Peyman Mohamadpour",
"author_id": 75020,
"author_profile": "https://wordpress.stackexchange.com/users/75020",
"pm_score": 1,
"selected": false,
"text": "<p>You may simply use <code>register_post_type</code> and <code>register_taxonomy</code> to do so:</p>\n\n<pre><code>function add_cpt_salads(){\n $labels = array(\n 'name' => __( 'Salads', 'your-text-domain' ),\n 'singular_name' => __( 'Salad', 'your-text-domain' ),\n 'menu_name' => __( 'Salads', 'your-text-domain' ),\n 'all_items' => __( 'All Salads', 'your-text-domain' ),\n 'add_new' => _x( 'Add new', 'Salads', 'your-text-domain' ),\n 'add_new_item' => __( 'Add New Salad', 'your-text-domain' ),\n 'edit_item' => __( 'Edit Salad', 'your-text-domain' ),\n 'new_item' => __( 'New Salad', 'your-text-domain' ),\n 'view_item' => __( 'View Salad', 'your-text-domain' ),\n 'search_items' => __( 'Search Salad', 'your-text-domain' ),\n 'not_found' => __( 'Not found', 'your-text-domain' ),\n 'not_found_in_trash' => __( 'Not found in Trash', 'your-text-domain' )\n );\n $args = array(\n 'label' => __( 'Salads', 'your-text-domain' ),\n 'labels' => $labels,\n 'description' => __( 'Salad items', 'your-text-domain' ),\n 'public' => true,\n 'exclude_from_search' => false,\n 'publicly_queryable' => true,\n 'show_ui' => true,\n 'show_in_nav_menus' => true,\n 'show_in_menu' => true,\n 'show_in_admin_bar' => true,\n 'menu_position' => 5,\n 'capability_type' => 'post',\n 'map_meta_cap' => true,\n 'hierarchical' => false,\n 'supports' => array( 'title', 'editor', 'thumbnail' ),\n 'register_meta_box_cb' => 'fjn_salads_register_meta_box',\n 'taxonomies' => array( 'salads_category', 'salads_tag' ),\n 'has_archive' => true,\n 'query_var' => true,\n 'can_export' => true,\n );\n register_post_type( 'salads', $args );\n register_taxonomy(\n 'salads_category',\n 'salads',\n array(\n 'label' => __( 'Salads category', 'your-text-domain' ),\n 'rewrite' => array( 'slug' => 'salad_cat' ),\n 'hierarchical' => true\n )\n );\n}\nadd_action( 'init', 'add_cpt_salads', 0 );\n</code></pre>\n\n<h2>UPDATE</h2>\n\n<p>You should add the above snippet to your current theme's <code>functions.php</code> file.</p>\n\n<p>Then you should go to Wordpress admin and under <strong>Salads</strong> menu, add:</p>\n\n<ul>\n<li>Best Veg Salads</li>\n<li>Best Non-Veg Salads</li>\n<li>...</li>\n<li>Best XYZ Salads</li>\n</ul>\n\n<p>using <strong>Add Salad category</strong> submenu.</p>\n\n<p>Then add:</p>\n\n<ul>\n<li>Salad #1</li>\n<li>Salad #2</li>\n<li>...</li>\n<li>Salad #x</li>\n</ul>\n\n<p>using <strong>Add New Salad</strong> submenu, and choose categories for them.</p>\n\n<p>Now in the root directory of your current theme, create a new file named <code>page-salads.php</code> and put this in it:</p>\n\n<pre><code>$terms = get_terms( 'salads_category' );\nforeach( $terms as $term ){\n $posts = new WP_Query( \"taxonomy='salads_category'&term=$term->slug&posts_per_page=-1\" );\n if( $posts->have_posts() ){?>\n <h2><?php echo $term;?></h2><?php\n while( $posts->have_posts() ){\n $posts->the_post();\n $the_title();\n //Do you general query loop here ...\n } \n }\n}\n</code></pre>\n\n<p>Then in Wordpress admin, go to <strong>Pages</strong> and add a page, named <strong>Salads</strong>, and take care of the slug to be as:</p>\n\n<pre><code>http://{your-home-url}/salads\n</code></pre>\n\n<p>like:</p>\n\n<pre><code>http://localhost/mywebsite/salads\n</code></pre>\n\n<p>and save. Then go to <strong>Settings>Permalinks</strong> and hit the <strong>Save changes</strong> button and in your browser enter the following URL:</p>\n\n<pre><code>http://localhost/mywebsite/salads\n</code></pre>\n\n<p>That is all.</p>\n"
},
{
"answer_id": 216347,
"author": "Abad Rahman",
"author_id": 78440,
"author_profile": "https://wordpress.stackexchange.com/users/78440",
"pm_score": 0,
"selected": false,
"text": "<p>You could use the default blog posts / custom post type and make use of the <a href=\"https://codex.wordpress.org/Taxonomies\" rel=\"nofollow\">custom taxonomy</a> and create a hierarchy of your list types.</p>\n\n<p>You can then achieve your page by using a shortcode to pull in your categories ( Salads) and children (Best Non-Veg Salads) .</p>\n\n<p>Within your shortcode you could use <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow\"><code>get_terms()</code></a> </p>\n"
}
] |
2016/02/01
|
[
"https://wordpress.stackexchange.com/questions/216338",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17306/"
] |
I want to create a post type / format where I can create list type posts... For example...
```
h1.Title: The List Post Title like "Best Salads..."
- Intro paragraph
h2. Best Veg Salads
- Intro
-- h3. Salad #1
-- h3. Salad #2
..
-- h3. Salad #X
h2. Best Non-Veg Salads
- Intro
-- h3. NV Salad #1
-- h3. NV Salad #2
..
-- h3. MV Salad #X
..
..
h2. Best XYZ Salads
- Intro
-- h3. Salad #1
-- h3. Salad #2
..
-- h3. Salad #X
Footer text...
```
Essentially each entry is a text field.
So I should be able to add any number of headings and subheadings in the post edit screen.
Note: I am not trying to create a post-type as salad. Salad is an example of one of the many published list posts. I am trying to create a site where I can post list type posts...
How can I achieve this.... Any ideas and suggestions would be great...
|
You may simply use `register_post_type` and `register_taxonomy` to do so:
```
function add_cpt_salads(){
$labels = array(
'name' => __( 'Salads', 'your-text-domain' ),
'singular_name' => __( 'Salad', 'your-text-domain' ),
'menu_name' => __( 'Salads', 'your-text-domain' ),
'all_items' => __( 'All Salads', 'your-text-domain' ),
'add_new' => _x( 'Add new', 'Salads', 'your-text-domain' ),
'add_new_item' => __( 'Add New Salad', 'your-text-domain' ),
'edit_item' => __( 'Edit Salad', 'your-text-domain' ),
'new_item' => __( 'New Salad', 'your-text-domain' ),
'view_item' => __( 'View Salad', 'your-text-domain' ),
'search_items' => __( 'Search Salad', 'your-text-domain' ),
'not_found' => __( 'Not found', 'your-text-domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'your-text-domain' )
);
$args = array(
'label' => __( 'Salads', 'your-text-domain' ),
'labels' => $labels,
'description' => __( 'Salad items', 'your-text-domain' ),
'public' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_nav_menus' => true,
'show_in_menu' => true,
'show_in_admin_bar' => true,
'menu_position' => 5,
'capability_type' => 'post',
'map_meta_cap' => true,
'hierarchical' => false,
'supports' => array( 'title', 'editor', 'thumbnail' ),
'register_meta_box_cb' => 'fjn_salads_register_meta_box',
'taxonomies' => array( 'salads_category', 'salads_tag' ),
'has_archive' => true,
'query_var' => true,
'can_export' => true,
);
register_post_type( 'salads', $args );
register_taxonomy(
'salads_category',
'salads',
array(
'label' => __( 'Salads category', 'your-text-domain' ),
'rewrite' => array( 'slug' => 'salad_cat' ),
'hierarchical' => true
)
);
}
add_action( 'init', 'add_cpt_salads', 0 );
```
UPDATE
------
You should add the above snippet to your current theme's `functions.php` file.
Then you should go to Wordpress admin and under **Salads** menu, add:
* Best Veg Salads
* Best Non-Veg Salads
* ...
* Best XYZ Salads
using **Add Salad category** submenu.
Then add:
* Salad #1
* Salad #2
* ...
* Salad #x
using **Add New Salad** submenu, and choose categories for them.
Now in the root directory of your current theme, create a new file named `page-salads.php` and put this in it:
```
$terms = get_terms( 'salads_category' );
foreach( $terms as $term ){
$posts = new WP_Query( "taxonomy='salads_category'&term=$term->slug&posts_per_page=-1" );
if( $posts->have_posts() ){?>
<h2><?php echo $term;?></h2><?php
while( $posts->have_posts() ){
$posts->the_post();
$the_title();
//Do you general query loop here ...
}
}
}
```
Then in Wordpress admin, go to **Pages** and add a page, named **Salads**, and take care of the slug to be as:
```
http://{your-home-url}/salads
```
like:
```
http://localhost/mywebsite/salads
```
and save. Then go to **Settings>Permalinks** and hit the **Save changes** button and in your browser enter the following URL:
```
http://localhost/mywebsite/salads
```
That is all.
|
216,346 |
<p>At first I thought it was an ACF problem, but printing some values helped me to find out that somehow my Loop seems stuck on a single post, but only when some fields are concerned.</p>
<p>To sum up my setup: I have installed the Advanced Custom Fields plugin and defined some custom fields (mostly numerical ones), on which I built custom post types.</p>
<p>The first occurence of the problem apperead while I was developing an archive page for a custom post type: I got everything working but a few fields returned <em>always</em> the same values, those related to a specific post (post number 50). After some attempts to fix the code (which led to <a href="https://wordpress.stackexchange.com/questions/216336/acf-get-field-return-fields-of-wrong-post">this question</a>) I left the archive page behind and started working on the single page. Then, again, most of the fields worked fine, but a few (the <em>same</em> few of the archive page) kept returning always the same values (again, the values from post number 50). So I started printing out the post ID, and every time I call <code>get_the_ID()</code> I always get 50, even after I deleted said post, in a pretty useless attempt to get rid of its values.</p>
<p>I think it's a bit strange, but from the behaviour I'd say that the loop is somehow stuck on the same post, no matter where I call it.</p>
|
[
{
"answer_id": 216340,
"author": "Peyman Mohamadpour",
"author_id": 75020,
"author_profile": "https://wordpress.stackexchange.com/users/75020",
"pm_score": 1,
"selected": false,
"text": "<p>You may simply use <code>register_post_type</code> and <code>register_taxonomy</code> to do so:</p>\n\n<pre><code>function add_cpt_salads(){\n $labels = array(\n 'name' => __( 'Salads', 'your-text-domain' ),\n 'singular_name' => __( 'Salad', 'your-text-domain' ),\n 'menu_name' => __( 'Salads', 'your-text-domain' ),\n 'all_items' => __( 'All Salads', 'your-text-domain' ),\n 'add_new' => _x( 'Add new', 'Salads', 'your-text-domain' ),\n 'add_new_item' => __( 'Add New Salad', 'your-text-domain' ),\n 'edit_item' => __( 'Edit Salad', 'your-text-domain' ),\n 'new_item' => __( 'New Salad', 'your-text-domain' ),\n 'view_item' => __( 'View Salad', 'your-text-domain' ),\n 'search_items' => __( 'Search Salad', 'your-text-domain' ),\n 'not_found' => __( 'Not found', 'your-text-domain' ),\n 'not_found_in_trash' => __( 'Not found in Trash', 'your-text-domain' )\n );\n $args = array(\n 'label' => __( 'Salads', 'your-text-domain' ),\n 'labels' => $labels,\n 'description' => __( 'Salad items', 'your-text-domain' ),\n 'public' => true,\n 'exclude_from_search' => false,\n 'publicly_queryable' => true,\n 'show_ui' => true,\n 'show_in_nav_menus' => true,\n 'show_in_menu' => true,\n 'show_in_admin_bar' => true,\n 'menu_position' => 5,\n 'capability_type' => 'post',\n 'map_meta_cap' => true,\n 'hierarchical' => false,\n 'supports' => array( 'title', 'editor', 'thumbnail' ),\n 'register_meta_box_cb' => 'fjn_salads_register_meta_box',\n 'taxonomies' => array( 'salads_category', 'salads_tag' ),\n 'has_archive' => true,\n 'query_var' => true,\n 'can_export' => true,\n );\n register_post_type( 'salads', $args );\n register_taxonomy(\n 'salads_category',\n 'salads',\n array(\n 'label' => __( 'Salads category', 'your-text-domain' ),\n 'rewrite' => array( 'slug' => 'salad_cat' ),\n 'hierarchical' => true\n )\n );\n}\nadd_action( 'init', 'add_cpt_salads', 0 );\n</code></pre>\n\n<h2>UPDATE</h2>\n\n<p>You should add the above snippet to your current theme's <code>functions.php</code> file.</p>\n\n<p>Then you should go to Wordpress admin and under <strong>Salads</strong> menu, add:</p>\n\n<ul>\n<li>Best Veg Salads</li>\n<li>Best Non-Veg Salads</li>\n<li>...</li>\n<li>Best XYZ Salads</li>\n</ul>\n\n<p>using <strong>Add Salad category</strong> submenu.</p>\n\n<p>Then add:</p>\n\n<ul>\n<li>Salad #1</li>\n<li>Salad #2</li>\n<li>...</li>\n<li>Salad #x</li>\n</ul>\n\n<p>using <strong>Add New Salad</strong> submenu, and choose categories for them.</p>\n\n<p>Now in the root directory of your current theme, create a new file named <code>page-salads.php</code> and put this in it:</p>\n\n<pre><code>$terms = get_terms( 'salads_category' );\nforeach( $terms as $term ){\n $posts = new WP_Query( \"taxonomy='salads_category'&term=$term->slug&posts_per_page=-1\" );\n if( $posts->have_posts() ){?>\n <h2><?php echo $term;?></h2><?php\n while( $posts->have_posts() ){\n $posts->the_post();\n $the_title();\n //Do you general query loop here ...\n } \n }\n}\n</code></pre>\n\n<p>Then in Wordpress admin, go to <strong>Pages</strong> and add a page, named <strong>Salads</strong>, and take care of the slug to be as:</p>\n\n<pre><code>http://{your-home-url}/salads\n</code></pre>\n\n<p>like:</p>\n\n<pre><code>http://localhost/mywebsite/salads\n</code></pre>\n\n<p>and save. Then go to <strong>Settings>Permalinks</strong> and hit the <strong>Save changes</strong> button and in your browser enter the following URL:</p>\n\n<pre><code>http://localhost/mywebsite/salads\n</code></pre>\n\n<p>That is all.</p>\n"
},
{
"answer_id": 216347,
"author": "Abad Rahman",
"author_id": 78440,
"author_profile": "https://wordpress.stackexchange.com/users/78440",
"pm_score": 0,
"selected": false,
"text": "<p>You could use the default blog posts / custom post type and make use of the <a href=\"https://codex.wordpress.org/Taxonomies\" rel=\"nofollow\">custom taxonomy</a> and create a hierarchy of your list types.</p>\n\n<p>You can then achieve your page by using a shortcode to pull in your categories ( Salads) and children (Best Non-Veg Salads) .</p>\n\n<p>Within your shortcode you could use <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow\"><code>get_terms()</code></a> </p>\n"
}
] |
2016/02/01
|
[
"https://wordpress.stackexchange.com/questions/216346",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87900/"
] |
At first I thought it was an ACF problem, but printing some values helped me to find out that somehow my Loop seems stuck on a single post, but only when some fields are concerned.
To sum up my setup: I have installed the Advanced Custom Fields plugin and defined some custom fields (mostly numerical ones), on which I built custom post types.
The first occurence of the problem apperead while I was developing an archive page for a custom post type: I got everything working but a few fields returned *always* the same values, those related to a specific post (post number 50). After some attempts to fix the code (which led to [this question](https://wordpress.stackexchange.com/questions/216336/acf-get-field-return-fields-of-wrong-post)) I left the archive page behind and started working on the single page. Then, again, most of the fields worked fine, but a few (the *same* few of the archive page) kept returning always the same values (again, the values from post number 50). So I started printing out the post ID, and every time I call `get_the_ID()` I always get 50, even after I deleted said post, in a pretty useless attempt to get rid of its values.
I think it's a bit strange, but from the behaviour I'd say that the loop is somehow stuck on the same post, no matter where I call it.
|
You may simply use `register_post_type` and `register_taxonomy` to do so:
```
function add_cpt_salads(){
$labels = array(
'name' => __( 'Salads', 'your-text-domain' ),
'singular_name' => __( 'Salad', 'your-text-domain' ),
'menu_name' => __( 'Salads', 'your-text-domain' ),
'all_items' => __( 'All Salads', 'your-text-domain' ),
'add_new' => _x( 'Add new', 'Salads', 'your-text-domain' ),
'add_new_item' => __( 'Add New Salad', 'your-text-domain' ),
'edit_item' => __( 'Edit Salad', 'your-text-domain' ),
'new_item' => __( 'New Salad', 'your-text-domain' ),
'view_item' => __( 'View Salad', 'your-text-domain' ),
'search_items' => __( 'Search Salad', 'your-text-domain' ),
'not_found' => __( 'Not found', 'your-text-domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'your-text-domain' )
);
$args = array(
'label' => __( 'Salads', 'your-text-domain' ),
'labels' => $labels,
'description' => __( 'Salad items', 'your-text-domain' ),
'public' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_nav_menus' => true,
'show_in_menu' => true,
'show_in_admin_bar' => true,
'menu_position' => 5,
'capability_type' => 'post',
'map_meta_cap' => true,
'hierarchical' => false,
'supports' => array( 'title', 'editor', 'thumbnail' ),
'register_meta_box_cb' => 'fjn_salads_register_meta_box',
'taxonomies' => array( 'salads_category', 'salads_tag' ),
'has_archive' => true,
'query_var' => true,
'can_export' => true,
);
register_post_type( 'salads', $args );
register_taxonomy(
'salads_category',
'salads',
array(
'label' => __( 'Salads category', 'your-text-domain' ),
'rewrite' => array( 'slug' => 'salad_cat' ),
'hierarchical' => true
)
);
}
add_action( 'init', 'add_cpt_salads', 0 );
```
UPDATE
------
You should add the above snippet to your current theme's `functions.php` file.
Then you should go to Wordpress admin and under **Salads** menu, add:
* Best Veg Salads
* Best Non-Veg Salads
* ...
* Best XYZ Salads
using **Add Salad category** submenu.
Then add:
* Salad #1
* Salad #2
* ...
* Salad #x
using **Add New Salad** submenu, and choose categories for them.
Now in the root directory of your current theme, create a new file named `page-salads.php` and put this in it:
```
$terms = get_terms( 'salads_category' );
foreach( $terms as $term ){
$posts = new WP_Query( "taxonomy='salads_category'&term=$term->slug&posts_per_page=-1" );
if( $posts->have_posts() ){?>
<h2><?php echo $term;?></h2><?php
while( $posts->have_posts() ){
$posts->the_post();
$the_title();
//Do you general query loop here ...
}
}
}
```
Then in Wordpress admin, go to **Pages** and add a page, named **Salads**, and take care of the slug to be as:
```
http://{your-home-url}/salads
```
like:
```
http://localhost/mywebsite/salads
```
and save. Then go to **Settings>Permalinks** and hit the **Save changes** button and in your browser enter the following URL:
```
http://localhost/mywebsite/salads
```
That is all.
|
216,351 |
<p>I've been messing around with custom comments this week and I'm trying to figure out when I'd want to use a walker and when I'd use a callback... </p>
<p>There's some things I can't quite figure out how to change, but the one that's been driving me mad is how to add classes to the children <code><ul></code> tag:</p>
<p><code><ul class="children"></code></p>
<p>Are there certain things a comment walker can do that a comment callback can't?... or vice-versa? And is one of these "better" to use as a theme developer? For example, I know that a lot of menu plugins don't work when a theme is using a custom menu walker.</p>
<p>Anyway, here's an example of the <strong>exact same comments</strong>, but one is being output using a walker and one is using a callback... What am I missing here? Why the need for both of these?</p>
<h2>Comment Callback</h2>
<pre><code>wp_list_comments( array(
'callback' => 'bootstrap_comment_callback',
));
function bootstrap_comment_callback( $comment, $args, $depth ){
$GLOBALS['comment'] = $comment; ?>
<li id="comment-<?php comment_ID(); ?>" <?php comment_class( empty( $args['has_children'] ) ? '' : 'parent' ); ?>>
<?php if ( 0 != $args['avatar_size'] ): ?>
<div class="media-left">
<a href="<?php echo get_comment_author_url(); ?>" class="media-object"><?php echo get_avatar( $comment, $args['avatar_size'] ); ?></a>
</div>
<?php endif; ?>
<div class="media-body">
<?php printf( '<h4 class="media-heading">%s</h4>', get_comment_author_link() ); ?>
<div class="comment-metadata">
<a href="<?php echo esc_url( get_comment_link( $comment->comment_ID, $args ) ); ?>">
<time datetime="<?php comment_time( 'c' ); ?>">
<?php printf( _x( '%1$s at %2$s', '1: date, 2: time' ), get_comment_date(), get_comment_time() ); ?>
</time>
</a>
</div><!-- .comment-metadata -->
<?php if ( '0' == $comment->comment_approved ) : ?>
<p class="comment-awaiting-moderation label label-info"><?php _e( 'Your comment is awaiting moderation.' ); ?></p>
<?php endif; ?>
<div class="comment-content">
<?php comment_text(); ?>
</div>
<ul class="list-inline">
<?php edit_comment_link( __( 'Edit' ), '<li class="edit-link">', '</li>' ); ?>
<?php
comment_reply_link( array_merge( $args, array(
'add_below' => 'div-comment',
'depth' => $depth,
'max_depth' => $args['max_depth'],
'before' => '<li class="reply-link">',
'after' => '</li>'
) ) );
?>
</ul>
</div>
<?php
}
</code></pre>
<hr>
<h2>Comment Walker</h2>
<pre><code>wp_list_comments( array(
'walker' => new Bootstrap_Comment_Walker(),
));
class Bootstrap_Comment_Walker extends Walker_Comment {
protected function html5_comment( $comment, $depth, $args ) {
?><li id="comment-<?php comment_ID(); ?>" <?php comment_class( empty( $args['has_children'] ) ? '' : 'parent' ); ?>>
<?php if ( 0 != $args['avatar_size'] ): ?>
<div class="media-left">
<a href="<?php echo get_comment_author_url(); ?>" class="media-object"><?php echo get_avatar( $comment, $args['avatar_size'] ); ?></a>
</div>
<?php endif; ?>
<div class="media-body">
<?php printf( '<h4 class="media-heading">%s</h4>', get_comment_author_link() ); ?>
<div class="comment-metadata">
<a href="<?php echo esc_url( get_comment_link( $comment->comment_ID, $args ) ); ?>">
<time datetime="<?php comment_time( 'c' ); ?>">
<?php printf( _x( '%1$s at %2$s', '1: date, 2: time' ), get_comment_date(), get_comment_time() ); ?>
</time>
</a>
</div><!-- .comment-metadata -->
<?php if ( '0' == $comment->comment_approved ) : ?>
<p class="comment-awaiting-moderation label label-info"><?php _e( 'Your comment is awaiting moderation.' ); ?></p>
<?php endif; ?>
<div class="comment-content">
<?php comment_text(); ?>
</div>
<ul class="list-inline">
<?php edit_comment_link( __( 'Edit' ), '<li class="edit-link">', '</li>' ); ?>
<?php
comment_reply_link( array_merge( $args, array(
'add_below' => 'div-comment',
'depth' => $depth,
'max_depth' => $args['max_depth'],
'before' => '<li class="reply-link">',
'after' => '</li>'
) ) );
?>
</ul>
</div>
<?php
}
}
</code></pre>
|
[
{
"answer_id": 216362,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>We could rewrite:</p>\n\n<pre><code>wp_list_comments( array(\n 'callback' => 'bootstrap_comment_callback',\n ));\n</code></pre>\n\n<p>with the null <code>walker</code> parameter:</p>\n\n<pre><code> wp_list_comments( array(\n 'walker' => null,\n 'callback' => 'bootstrap_comment_callback',\n ));\n</code></pre>\n\n<p>which means we are using the default <code>Walker_Comment</code> class:</p>\n\n<pre><code> wp_list_comments( array(\n 'walker' => new Walker_Comment,\n 'callback' => 'bootstrap_comment_callback',\n ));\n</code></pre>\n\n<p>The <code>Walker_Comment::start_el()</code> method is just a wrapper for one of these <em>protected</em> methods:</p>\n\n<pre><code>Walker_Comment::comment()\nWalker_Comment::html5_comment()\nWalker_Comment::ping()\n</code></pre>\n\n<p>that, depending on the context, append each comment to the output string when walking along the comment tree.</p>\n\n<p>Using a <em>custom walker</em> class, that extends the <code>Walker_Comment</code> class, gives us the ability to override these <em>public</em> methods:</p>\n\n<pre><code>Walker_Comment::start_el()\nWalker_Comment::end_el()\nWalker_Comment::start_lvl()\nWalker_Comment::end_lvl()\nWalker_Comment::display_element()\n</code></pre>\n\n<p>in addition to the protected ones above.</p>\n\n<p>If we only need to modify the output of the <code>start_el()</code> method, we would only need to use the <code>callback</code> parameter in <code>wp_list_comments()</code>.</p>\n"
},
{
"answer_id": 220025,
"author": "darrinb",
"author_id": 6304,
"author_profile": "https://wordpress.stackexchange.com/users/6304",
"pm_score": 1,
"selected": false,
"text": "<p>In the simplest of explanations, the <code>callback</code> argument for <code>wp_list_comments()</code> is used to reference a function that will build the beginning of an <strong>individual</strong> comment. (The <code>end-callback</code> argument references a function that will close an individual comment.)</p>\n\n<p>So, you can use your own custom function to output an individual comment while still using the core <code>Walker_Comment</code> class to build the <strong>entire</strong> comment list.</p>\n\n<p>Conversely, you could also use your own class to override either all, or parts of, the core <code>Walker_Comment</code> class.</p>\n\n<p>In your example above, you defined a custom walker class with one method defined: <code>html5_comment()</code>. Since you're extending the core <code>Walker_Comment</code> class, but only overriding one method (<code>html_comment()</code>), WP will use the rest of the methods defined in <code>Walker_Comment</code> to build out the remainder of the comment list.</p>\n\n<p>Essentially, use <code>callback</code>/<code>end-callback</code> to build out an individual comment, and use a custom Walker class to build out the entire comment list. You don't need both, it's one or the other.</p>\n\n<p>Incidentally I just wrote an article outlining this in greater detail based on a plugin I released relating to Bootstrap comments for WordPress. You can find it here: <a href=\"http://darrinb.com/wp-bootstrap-comments/\" rel=\"nofollow\">http://darrinb.com/wp-bootstrap-comments/</a></p>\n"
},
{
"answer_id": 401977,
"author": "amarinediary",
"author_id": 190376,
"author_profile": "https://wordpress.stackexchange.com/users/190376",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n<p>There's some things I can't quite figure out how to change, but the one that's been driving me mad is how to add classes to the children <code><ul class="children"></code> ...</p>\n</blockquote>\n<p>Beside using Walkers and Callbacks, a straight to the point fix would be to do a <code>preg_replace</code> before <code>echo</code>ing-it-out.</p>\n<pre><code><?php\n\n$buffer = wp_list_comments(\n array (\n //...\n 'echo' => false,\n ),\n //...\n);\n\n$buffer = preg_replace( '/class="children"/', 'class="list-unstyled"', $buffer );\n\necho $buffer;\n</code></pre>\n"
}
] |
2016/02/01
|
[
"https://wordpress.stackexchange.com/questions/216351",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38123/"
] |
I've been messing around with custom comments this week and I'm trying to figure out when I'd want to use a walker and when I'd use a callback...
There's some things I can't quite figure out how to change, but the one that's been driving me mad is how to add classes to the children `<ul>` tag:
`<ul class="children">`
Are there certain things a comment walker can do that a comment callback can't?... or vice-versa? And is one of these "better" to use as a theme developer? For example, I know that a lot of menu plugins don't work when a theme is using a custom menu walker.
Anyway, here's an example of the **exact same comments**, but one is being output using a walker and one is using a callback... What am I missing here? Why the need for both of these?
Comment Callback
----------------
```
wp_list_comments( array(
'callback' => 'bootstrap_comment_callback',
));
function bootstrap_comment_callback( $comment, $args, $depth ){
$GLOBALS['comment'] = $comment; ?>
<li id="comment-<?php comment_ID(); ?>" <?php comment_class( empty( $args['has_children'] ) ? '' : 'parent' ); ?>>
<?php if ( 0 != $args['avatar_size'] ): ?>
<div class="media-left">
<a href="<?php echo get_comment_author_url(); ?>" class="media-object"><?php echo get_avatar( $comment, $args['avatar_size'] ); ?></a>
</div>
<?php endif; ?>
<div class="media-body">
<?php printf( '<h4 class="media-heading">%s</h4>', get_comment_author_link() ); ?>
<div class="comment-metadata">
<a href="<?php echo esc_url( get_comment_link( $comment->comment_ID, $args ) ); ?>">
<time datetime="<?php comment_time( 'c' ); ?>">
<?php printf( _x( '%1$s at %2$s', '1: date, 2: time' ), get_comment_date(), get_comment_time() ); ?>
</time>
</a>
</div><!-- .comment-metadata -->
<?php if ( '0' == $comment->comment_approved ) : ?>
<p class="comment-awaiting-moderation label label-info"><?php _e( 'Your comment is awaiting moderation.' ); ?></p>
<?php endif; ?>
<div class="comment-content">
<?php comment_text(); ?>
</div>
<ul class="list-inline">
<?php edit_comment_link( __( 'Edit' ), '<li class="edit-link">', '</li>' ); ?>
<?php
comment_reply_link( array_merge( $args, array(
'add_below' => 'div-comment',
'depth' => $depth,
'max_depth' => $args['max_depth'],
'before' => '<li class="reply-link">',
'after' => '</li>'
) ) );
?>
</ul>
</div>
<?php
}
```
---
Comment Walker
--------------
```
wp_list_comments( array(
'walker' => new Bootstrap_Comment_Walker(),
));
class Bootstrap_Comment_Walker extends Walker_Comment {
protected function html5_comment( $comment, $depth, $args ) {
?><li id="comment-<?php comment_ID(); ?>" <?php comment_class( empty( $args['has_children'] ) ? '' : 'parent' ); ?>>
<?php if ( 0 != $args['avatar_size'] ): ?>
<div class="media-left">
<a href="<?php echo get_comment_author_url(); ?>" class="media-object"><?php echo get_avatar( $comment, $args['avatar_size'] ); ?></a>
</div>
<?php endif; ?>
<div class="media-body">
<?php printf( '<h4 class="media-heading">%s</h4>', get_comment_author_link() ); ?>
<div class="comment-metadata">
<a href="<?php echo esc_url( get_comment_link( $comment->comment_ID, $args ) ); ?>">
<time datetime="<?php comment_time( 'c' ); ?>">
<?php printf( _x( '%1$s at %2$s', '1: date, 2: time' ), get_comment_date(), get_comment_time() ); ?>
</time>
</a>
</div><!-- .comment-metadata -->
<?php if ( '0' == $comment->comment_approved ) : ?>
<p class="comment-awaiting-moderation label label-info"><?php _e( 'Your comment is awaiting moderation.' ); ?></p>
<?php endif; ?>
<div class="comment-content">
<?php comment_text(); ?>
</div>
<ul class="list-inline">
<?php edit_comment_link( __( 'Edit' ), '<li class="edit-link">', '</li>' ); ?>
<?php
comment_reply_link( array_merge( $args, array(
'add_below' => 'div-comment',
'depth' => $depth,
'max_depth' => $args['max_depth'],
'before' => '<li class="reply-link">',
'after' => '</li>'
) ) );
?>
</ul>
</div>
<?php
}
}
```
|
We could rewrite:
```
wp_list_comments( array(
'callback' => 'bootstrap_comment_callback',
));
```
with the null `walker` parameter:
```
wp_list_comments( array(
'walker' => null,
'callback' => 'bootstrap_comment_callback',
));
```
which means we are using the default `Walker_Comment` class:
```
wp_list_comments( array(
'walker' => new Walker_Comment,
'callback' => 'bootstrap_comment_callback',
));
```
The `Walker_Comment::start_el()` method is just a wrapper for one of these *protected* methods:
```
Walker_Comment::comment()
Walker_Comment::html5_comment()
Walker_Comment::ping()
```
that, depending on the context, append each comment to the output string when walking along the comment tree.
Using a *custom walker* class, that extends the `Walker_Comment` class, gives us the ability to override these *public* methods:
```
Walker_Comment::start_el()
Walker_Comment::end_el()
Walker_Comment::start_lvl()
Walker_Comment::end_lvl()
Walker_Comment::display_element()
```
in addition to the protected ones above.
If we only need to modify the output of the `start_el()` method, we would only need to use the `callback` parameter in `wp_list_comments()`.
|
216,359 |
<p>I want to show/hide contents by using radio buttons on a WordPress page. When a user clicks on the radio button with label "red", the corresponding div with the class "red" needs to show up.</p>
<p>Here's the (working) example I'm trying to integrate: <a href="http://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-show-hide-div-using-radio-button" rel="nofollow">http://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-show-hide-div-using-radio-button</a></p>
<p>In WordPress, I've placed this in the custom CSS of my theme:</p>
<pre><code>.box
{
padding: 20px;
display: none;
margin-top: 20px;
border: 1px solid #000;
}
.red { background: #ff0000; }
.green { background: #00ff00; }
.blue { background: #0000ff; }
</code></pre>
<p>I've placed this in an external script (script-pricing.js). That file was copied to the child-theme folder:</p>
<pre><code>$(document).ready(function(){
$('input[type="radio"]').click(function(){
if($(this).attr("value")=="red"){
$(".box").not(".red").hide();
$(".red").show();
}
if($(this).attr("value")=="green"){
$(".box").not(".green").hide();
$(".green").show();
}
if($(this).attr("value")=="blue"){
$(".box").not(".blue").hide();
$(".blue").show();
}
});
</code></pre>
<p>I've enqueued that script with this code in functions.php:</p>
<pre><code>//add a custom jQuery script to Wordpress
function add_pricing() {
wp_register_script('pricing',
get_stylesheet_directory_uri() . '/script-pricing.js',
array('jquery'),
'1.0' );
wp_enqueue_script('pricing');
}
add_action('wp_enqueue_scripts', 'add_pricing');
</code></pre>
<p>I've placed this in a WordPress page:</p>
<pre><code><div><label><input name="colorRadio" type="radio" value="red" /> One- year</label>
<label><input name="colorRadio" type="radio" value="green" /> Two-year</label>
<label><input name="colorRadio" type="radio" value="blue" /> Three-year</label></div>
<div class="red box">You have selected red</div>
<div class="green box">You have selected green</div>
<div class="blue box">You have selected blue</div>
</code></pre>
<p>The page displays the three radio buttons.
The CSS hides the three 'You have selected" lines.
But when a radio button is clicked the respective line isn't showing up.</p>
<p>What have I missed and what needs to be improved? Thanks in advance for your response!</p>
|
[
{
"answer_id": 216362,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>We could rewrite:</p>\n\n<pre><code>wp_list_comments( array(\n 'callback' => 'bootstrap_comment_callback',\n ));\n</code></pre>\n\n<p>with the null <code>walker</code> parameter:</p>\n\n<pre><code> wp_list_comments( array(\n 'walker' => null,\n 'callback' => 'bootstrap_comment_callback',\n ));\n</code></pre>\n\n<p>which means we are using the default <code>Walker_Comment</code> class:</p>\n\n<pre><code> wp_list_comments( array(\n 'walker' => new Walker_Comment,\n 'callback' => 'bootstrap_comment_callback',\n ));\n</code></pre>\n\n<p>The <code>Walker_Comment::start_el()</code> method is just a wrapper for one of these <em>protected</em> methods:</p>\n\n<pre><code>Walker_Comment::comment()\nWalker_Comment::html5_comment()\nWalker_Comment::ping()\n</code></pre>\n\n<p>that, depending on the context, append each comment to the output string when walking along the comment tree.</p>\n\n<p>Using a <em>custom walker</em> class, that extends the <code>Walker_Comment</code> class, gives us the ability to override these <em>public</em> methods:</p>\n\n<pre><code>Walker_Comment::start_el()\nWalker_Comment::end_el()\nWalker_Comment::start_lvl()\nWalker_Comment::end_lvl()\nWalker_Comment::display_element()\n</code></pre>\n\n<p>in addition to the protected ones above.</p>\n\n<p>If we only need to modify the output of the <code>start_el()</code> method, we would only need to use the <code>callback</code> parameter in <code>wp_list_comments()</code>.</p>\n"
},
{
"answer_id": 220025,
"author": "darrinb",
"author_id": 6304,
"author_profile": "https://wordpress.stackexchange.com/users/6304",
"pm_score": 1,
"selected": false,
"text": "<p>In the simplest of explanations, the <code>callback</code> argument for <code>wp_list_comments()</code> is used to reference a function that will build the beginning of an <strong>individual</strong> comment. (The <code>end-callback</code> argument references a function that will close an individual comment.)</p>\n\n<p>So, you can use your own custom function to output an individual comment while still using the core <code>Walker_Comment</code> class to build the <strong>entire</strong> comment list.</p>\n\n<p>Conversely, you could also use your own class to override either all, or parts of, the core <code>Walker_Comment</code> class.</p>\n\n<p>In your example above, you defined a custom walker class with one method defined: <code>html5_comment()</code>. Since you're extending the core <code>Walker_Comment</code> class, but only overriding one method (<code>html_comment()</code>), WP will use the rest of the methods defined in <code>Walker_Comment</code> to build out the remainder of the comment list.</p>\n\n<p>Essentially, use <code>callback</code>/<code>end-callback</code> to build out an individual comment, and use a custom Walker class to build out the entire comment list. You don't need both, it's one or the other.</p>\n\n<p>Incidentally I just wrote an article outlining this in greater detail based on a plugin I released relating to Bootstrap comments for WordPress. You can find it here: <a href=\"http://darrinb.com/wp-bootstrap-comments/\" rel=\"nofollow\">http://darrinb.com/wp-bootstrap-comments/</a></p>\n"
},
{
"answer_id": 401977,
"author": "amarinediary",
"author_id": 190376,
"author_profile": "https://wordpress.stackexchange.com/users/190376",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n<p>There's some things I can't quite figure out how to change, but the one that's been driving me mad is how to add classes to the children <code><ul class="children"></code> ...</p>\n</blockquote>\n<p>Beside using Walkers and Callbacks, a straight to the point fix would be to do a <code>preg_replace</code> before <code>echo</code>ing-it-out.</p>\n<pre><code><?php\n\n$buffer = wp_list_comments(\n array (\n //...\n 'echo' => false,\n ),\n //...\n);\n\n$buffer = preg_replace( '/class="children"/', 'class="list-unstyled"', $buffer );\n\necho $buffer;\n</code></pre>\n"
}
] |
2016/02/01
|
[
"https://wordpress.stackexchange.com/questions/216359",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87912/"
] |
I want to show/hide contents by using radio buttons on a WordPress page. When a user clicks on the radio button with label "red", the corresponding div with the class "red" needs to show up.
Here's the (working) example I'm trying to integrate: <http://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-show-hide-div-using-radio-button>
In WordPress, I've placed this in the custom CSS of my theme:
```
.box
{
padding: 20px;
display: none;
margin-top: 20px;
border: 1px solid #000;
}
.red { background: #ff0000; }
.green { background: #00ff00; }
.blue { background: #0000ff; }
```
I've placed this in an external script (script-pricing.js). That file was copied to the child-theme folder:
```
$(document).ready(function(){
$('input[type="radio"]').click(function(){
if($(this).attr("value")=="red"){
$(".box").not(".red").hide();
$(".red").show();
}
if($(this).attr("value")=="green"){
$(".box").not(".green").hide();
$(".green").show();
}
if($(this).attr("value")=="blue"){
$(".box").not(".blue").hide();
$(".blue").show();
}
});
```
I've enqueued that script with this code in functions.php:
```
//add a custom jQuery script to Wordpress
function add_pricing() {
wp_register_script('pricing',
get_stylesheet_directory_uri() . '/script-pricing.js',
array('jquery'),
'1.0' );
wp_enqueue_script('pricing');
}
add_action('wp_enqueue_scripts', 'add_pricing');
```
I've placed this in a WordPress page:
```
<div><label><input name="colorRadio" type="radio" value="red" /> One- year</label>
<label><input name="colorRadio" type="radio" value="green" /> Two-year</label>
<label><input name="colorRadio" type="radio" value="blue" /> Three-year</label></div>
<div class="red box">You have selected red</div>
<div class="green box">You have selected green</div>
<div class="blue box">You have selected blue</div>
```
The page displays the three radio buttons.
The CSS hides the three 'You have selected" lines.
But when a radio button is clicked the respective line isn't showing up.
What have I missed and what needs to be improved? Thanks in advance for your response!
|
We could rewrite:
```
wp_list_comments( array(
'callback' => 'bootstrap_comment_callback',
));
```
with the null `walker` parameter:
```
wp_list_comments( array(
'walker' => null,
'callback' => 'bootstrap_comment_callback',
));
```
which means we are using the default `Walker_Comment` class:
```
wp_list_comments( array(
'walker' => new Walker_Comment,
'callback' => 'bootstrap_comment_callback',
));
```
The `Walker_Comment::start_el()` method is just a wrapper for one of these *protected* methods:
```
Walker_Comment::comment()
Walker_Comment::html5_comment()
Walker_Comment::ping()
```
that, depending on the context, append each comment to the output string when walking along the comment tree.
Using a *custom walker* class, that extends the `Walker_Comment` class, gives us the ability to override these *public* methods:
```
Walker_Comment::start_el()
Walker_Comment::end_el()
Walker_Comment::start_lvl()
Walker_Comment::end_lvl()
Walker_Comment::display_element()
```
in addition to the protected ones above.
If we only need to modify the output of the `start_el()` method, we would only need to use the `callback` parameter in `wp_list_comments()`.
|
216,376 |
<p>I need a page template to be used with my plugin. I don't need to replace a theme template such as single or archive.</p>
<p>Normally I'd use</p>
<pre><code>/*
* Template Name: Blah Blah Blah
*/
</code></pre>
<p>to add a template to the page options, however, this isn't working in the plugin, as expected. I know how to add a template for a custom post type in a plugin. However, I need this to be an option the templates dropdown in the page options.</p>
|
[
{
"answer_id": 216382,
"author": "тнє Sufi",
"author_id": 28744,
"author_profile": "https://wordpress.stackexchange.com/users/28744",
"pm_score": 1,
"selected": false,
"text": "<p>There is no straight forward way to this, as per my knowledge. I have tried to search as well, and did not find any better solution than the below one.</p>\n\n<p>Below codes will provide you exactly what you are looking for:</p>\n\n<pre><code>class PageTemplater {\n\n /**\n * A Unique Identifier\n */\n protected $plugin_slug;\n\n /**\n * A reference to an instance of this class.\n */\n private static $instance;\n\n /**\n * The array of templates that this plugin tracks.\n */\n protected $templates;\n\n\n /**\n * Returns an instance of this class. \n */\n public static function get_instance() {\n\n if( null == self::$instance ) {\n self::$instance = new PageTemplater();\n } \n\n return self::$instance;\n\n } \n\n /**\n * Initializes the plugin by setting filters and administration functions.\n */\n private function __construct() {\n\n $this->templates = array();\n\n\n // Add a filter to the attributes metabox to inject template into the cache.\n add_filter(\n 'page_attributes_dropdown_pages_args',\n array( $this, 'register_project_templates' ) \n );\n\n\n // Add a filter to the save post to inject out template into the page cache\n add_filter(\n 'wp_insert_post_data', \n array( $this, 'register_project_templates' ) \n );\n\n\n // Add a filter to the template include to determine if the page has our \n // template assigned and return it's path\n add_filter(\n 'template_include', \n array( $this, 'view_project_template') \n );\n\n\n // Add your templates to this array.\n $this->templates = array(\n 'goodtobebad-template.php' => 'It\\'s Good to Be Bad',\n );\n\n } \n\n\n /**\n * Adds our template to the pages cache in order to trick WordPress\n * into thinking the template file exists where it doens't really exist.\n *\n */\n\n public function register_project_templates( $atts ) {\n\n // Create the key used for the themes cache\n $cache_key = 'page_templates-' . md5( get_theme_root() . '/' . get_stylesheet() );\n\n // Retrieve the cache list. \n // If it doesn't exist, or it's empty prepare an array\n $templates = wp_get_theme()->get_page_templates();\n if ( empty( $templates ) ) {\n $templates = array();\n } \n\n // New cache, therefore remove the old one\n wp_cache_delete( $cache_key , 'themes');\n\n // Now add our template to the list of templates by merging our templates\n // with the existing templates array from the cache.\n $templates = array_merge( $templates, $this->templates );\n\n // Add the modified cache to allow WordPress to pick it up for listing\n // available templates\n wp_cache_add( $cache_key, $templates, 'themes', 1800 );\n\n return $atts;\n\n } \n\n /**\n * Checks if the template is assigned to the page\n */\n public function view_project_template( $template ) {\n\n global $post;\n\n if (!isset($this->templates[get_post_meta( \n $post->ID, '_wp_page_template', true \n )] ) ) {\n\n return $template;\n\n } \n\n $file = plugin_dir_path(__FILE__). get_post_meta( \n $post->ID, '_wp_page_template', true \n );\n\n // Just to be safe, we check if the file exist first\n if( file_exists( $file ) ) {\n return $file;\n } \n else { echo $file; }\n\n return $template;\n\n } \n\n\n}\nadd_action( 'plugins_loaded', array( 'PageTemplater', 'get_instance' ) );\n</code></pre>\n\n<p><a href=\"http://www.wpexplorer.com/wordpress-page-templates-plugin/\" rel=\"nofollow\">Here is the full tutorial</a> with details of what is happening and why.</p>\n"
},
{
"answer_id": 216498,
"author": "Welcher",
"author_id": 27210,
"author_profile": "https://wordpress.stackexchange.com/users/27210",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the <code>theme_page_templates</code> filter to inject your page template.</p>\n\n<p>For example:</p>\n\n<pre><code>add_filter( 'theme_page_templates', 'filter_inject_page_templates' );\n\nfilter_inject_page_templates( $templates ) {\n $path = 'path/to/the/template/relative/to/the/theme/folder';\n $templates[ $path ] = 'Name of the template that displays in dropdown;\n return $templates;\n}\n</code></pre>\n\n<p>You may have to play around with the <code>$path</code> value to get it correct but that should work.</p>\n\n<p>Hope it helps!</p>\n"
},
{
"answer_id": 253059,
"author": "jg314",
"author_id": 26202,
"author_profile": "https://wordpress.stackexchange.com/users/26202",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a fairly simple approach I was able to get working within a plugin. You'll want to reference <a href=\"https://developer.wordpress.org/reference/hooks/theme_page_templates/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/theme_page_templates/</a> and <a href=\"https://developer.wordpress.org/reference/hooks/template_include/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/template_include/</a> as you review the code below.</p>\n\n<pre><code><?php\n//Add our custom template to the admin's templates dropdown\nadd_filter( 'theme_page_templates', 'pluginname_template_as_option', 10, 3 );\nfunction pluginname_template_as_option( $page_templates, $theme, $post ){\n\n $page_templates['template-landing.php'] = 'Example Landing Page';\n\n return $page_templates;\n\n}\n\n//When our custom template has been chosen then display it for the page\nadd_filter( 'template_include', 'pluginname_load_template', 99 );\nfunction pluginname_load_template( $template ) {\n\n global $post;\n $custom_template_slug = 'template-landing.php';\n $page_template_slug = get_page_template_slug( $post->ID );\n\n if( $page_template_slug == $custom_template_slug ){\n return plugin_dir_path( __FILE__ ) . $custom_template_slug;\n }\n\n return $template;\n\n}\n</code></pre>\n"
}
] |
2016/02/01
|
[
"https://wordpress.stackexchange.com/questions/216376",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8278/"
] |
I need a page template to be used with my plugin. I don't need to replace a theme template such as single or archive.
Normally I'd use
```
/*
* Template Name: Blah Blah Blah
*/
```
to add a template to the page options, however, this isn't working in the plugin, as expected. I know how to add a template for a custom post type in a plugin. However, I need this to be an option the templates dropdown in the page options.
|
Here is a fairly simple approach I was able to get working within a plugin. You'll want to reference <https://developer.wordpress.org/reference/hooks/theme_page_templates/> and <https://developer.wordpress.org/reference/hooks/template_include/> as you review the code below.
```
<?php
//Add our custom template to the admin's templates dropdown
add_filter( 'theme_page_templates', 'pluginname_template_as_option', 10, 3 );
function pluginname_template_as_option( $page_templates, $theme, $post ){
$page_templates['template-landing.php'] = 'Example Landing Page';
return $page_templates;
}
//When our custom template has been chosen then display it for the page
add_filter( 'template_include', 'pluginname_load_template', 99 );
function pluginname_load_template( $template ) {
global $post;
$custom_template_slug = 'template-landing.php';
$page_template_slug = get_page_template_slug( $post->ID );
if( $page_template_slug == $custom_template_slug ){
return plugin_dir_path( __FILE__ ) . $custom_template_slug;
}
return $template;
}
```
|
216,397 |
<p>My permalinks are like mydomain.com/post and have to be like that, but because I use non-English characters (which need to be in the URL and make it really long and weird) for posting in social networks I need to have an extra permalink like mydomain.com/?p=123 (or something like that but with my exact domain).</p>
<p>P.S: I searched and came across yourls.org which is great but I'm not sure if I can have in the same directory as Wordpress!?</p>
|
[
{
"answer_id": 216400,
"author": "alex",
"author_id": 87934,
"author_profile": "https://wordpress.stackexchange.com/users/87934",
"pm_score": 0,
"selected": false,
"text": "<p>It's not a good idea to have two links pointing to the same Page or Post.there are two approaches: </p>\n\n<ol>\n<li>Install SEO for Yoast plugin and use its Canonical url ability</li>\n<li>choose page/post slug to a short elegant one (recommended)</li>\n</ol>\n"
},
{
"answer_id": 216404,
"author": "flomei",
"author_id": 65455,
"author_profile": "https://wordpress.stackexchange.com/users/65455",
"pm_score": 2,
"selected": true,
"text": "<p>You can always use the post ID to link to a page, like this:</p>\n\n<pre>http://yourdomain.tld/?p=1234</pre>\n\n<p>You can find out the Post ID right from the post overview screen. If you hover over the \"Edit\" or \"Delete\" link, you can see that the URL has a parameter <code>post=</code>. The number behind that is your page ID.</p>\n\n<p>It could happen, that WordPress redirects your \"post ID permalink\" to the \"real\" version with the slug, but you are good to use the numeric one for linking.</p>\n"
}
] |
2016/02/02
|
[
"https://wordpress.stackexchange.com/questions/216397",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87933/"
] |
My permalinks are like mydomain.com/post and have to be like that, but because I use non-English characters (which need to be in the URL and make it really long and weird) for posting in social networks I need to have an extra permalink like mydomain.com/?p=123 (or something like that but with my exact domain).
P.S: I searched and came across yourls.org which is great but I'm not sure if I can have in the same directory as Wordpress!?
|
You can always use the post ID to link to a page, like this:
```
http://yourdomain.tld/?p=1234
```
You can find out the Post ID right from the post overview screen. If you hover over the "Edit" or "Delete" link, you can see that the URL has a parameter `post=`. The number behind that is your page ID.
It could happen, that WordPress redirects your "post ID permalink" to the "real" version with the slug, but you are good to use the numeric one for linking.
|
216,417 |
<p>I want to check if a WordPress installation is working from a subdirectory.</p>
<p>Common methods to achieve this are listed here:
<a href="https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory" rel="nofollow">https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory</a></p>
<p>these usually involve changing an index file and requiring WordPress main file from there, perhaps changing rules in htaccess if using Apache - there's no setting up constants from what I can see</p>
<p>so, how would you detect reliably if WordPress is not running from a directory root?</p>
|
[
{
"answer_id": 216420,
"author": "fischi",
"author_id": 15680,
"author_profile": "https://wordpress.stackexchange.com/users/15680",
"pm_score": 3,
"selected": true,
"text": "<p>You need to check if the siteurl differs from the home URL:</p>\n\n<pre><code>if ( get_option( 'siteurl' ) !== get_option( 'home' ) ) { // whatever\n</code></pre>\n\n<p>This also works if <code>home</code> is a subdirectory of the root, with WordPress installed in yet another subdirectory. For example: domain.com/blog (URL) and domain.com/blog/wordpress (siteurl).</p>\n"
},
{
"answer_id": 287888,
"author": "Gkiokan",
"author_id": 77189,
"author_profile": "https://wordpress.stackexchange.com/users/77189",
"pm_score": 0,
"selected": false,
"text": "<p>I just came across for the same question and found another way to figure it out. You can also use the defined Constants from the wp-config.php file.\n<strong>SUBDOMAIN_INSTALL</strong> would be the key.</p>\n<h3>Example wp-config excerpt for Multisite settings would be</h3>\n<pre><code>define('WP_ALLOW_MULTISITE', true );\ndefine('MULTISITE', true);\ndefine('SUBDOMAIN_INSTALL', false);\ndefine('DOMAIN_CURRENT_SITE', 'intern.cc.dev');\ndefine('PATH_CURRENT_SITE', '/');\n</code></pre>\n<h3>In your code</h3>\n<pre><code>// only run condition, when we are in MS\nif( is_multisite() ):\n\n // check for subfolder installation flag\n if( SUBDOMAIN_INSTALL === false):\n\n // optional, check if you are on the home WP or a sub WP\n if( get_current_blog_id() > 1):\n\n // do whatever you need to to here\n\n\n endif; // end blog id check\n endif; // end subfolder installation \nendif; // end multisite check\n</code></pre>\n"
}
] |
2016/02/02
|
[
"https://wordpress.stackexchange.com/questions/216417",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8421/"
] |
I want to check if a WordPress installation is working from a subdirectory.
Common methods to achieve this are listed here:
<https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory>
these usually involve changing an index file and requiring WordPress main file from there, perhaps changing rules in htaccess if using Apache - there's no setting up constants from what I can see
so, how would you detect reliably if WordPress is not running from a directory root?
|
You need to check if the siteurl differs from the home URL:
```
if ( get_option( 'siteurl' ) !== get_option( 'home' ) ) { // whatever
```
This also works if `home` is a subdirectory of the root, with WordPress installed in yet another subdirectory. For example: domain.com/blog (URL) and domain.com/blog/wordpress (siteurl).
|
216,427 |
<p>Just installed WP in Ubuntu 15.10 desktop on my local, home PC. It's the first time I install this CMS in Linux.</p>
<p>After install I came to delete the two native plugins, Aksimet & Hello Dolly.</p>
<p>In the first time I did so I was (strangely) asked to fill in FTP credentials. Since I have no FTP I ran the FTP problem in Google and after some reading added <code>define('FS_METHOD', 'direct');</code> in the end of wp-config.php ... It solved this prob, but then came another - an error this time, occuring when I try to remove these two plugins:</p>
<blockquote>
<p>Plugin could not be deleted due to an error: Could not fully remove
the plugin(s) akismet/akismet.php, hello.php.</p>
</blockquote>
<p>did <code>sudo chown benwork -R .</code> and also <code>sudo chgrp www-data -R .</code></p>
<p>Nothing seems to help. Will thank you for your help,</p>
|
[
{
"answer_id": 216432,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>Simple solution to this kind of mess that I use, is to have a local FTP server but limit it to the local machine.</p>\n\n<p>Your problem is probably due to still some bad permissions, but I really don't like the idea of reducing security just to have nicer update experience. (If you set properly the direct access setting then every security flow in plugins themes might be used to write to your disk out side of the uploads directory)</p>\n"
},
{
"answer_id": 216433,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": -1,
"selected": false,
"text": "<p>This issue probably seems due to permissions of the <code>wp-contents/plugins</code> folder. BTY, check below plugin for remove unwanted plugins call <a href=\"https://wordpress.org/plugins/unwanted-plugins-remover/\" rel=\"nofollow\">Unwanted Plugins Remover</a>. With this plugin you can remove unwanted plugins on a WordPress core upgrade process. Unwanted plugins are for example Akismet or Hello Dolly.</p>\n\n<p>There is the plugin <a href=\"https://wordpress.org/plugins/unwanted-plugins-remover/\" rel=\"nofollow\">Unwanted Plugins Remover</a>. It will remove the plugins <em>Akismet</em> and <em>Hello Dolly</em> on every upgrade. You can filter the plugin list to match only one of those plugins or to add more.</p>\n\n<p><strong>NOTE:</strong> </p>\n\n<blockquote>\n <p>This plugin hasn’t been updated in over 2 years. It may no longer be\n maintained or supported and may have compatibility issues when used\n with more recent versions of WordPress.</p>\n</blockquote>\n"
},
{
"answer_id": 300482,
"author": "Eugene Kardash",
"author_id": 141592,
"author_profile": "https://wordpress.stackexchange.com/users/141592",
"pm_score": 2,
"selected": true,
"text": "<p>You need to make sure that the folder permissions/ownership are correct.\nRun this command to set ownership:</p>\n\n<pre><code>chown -R apache:apache /var/www/wordpress/\n</code></pre>\n"
}
] |
2016/02/02
|
[
"https://wordpress.stackexchange.com/questions/216427",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
Just installed WP in Ubuntu 15.10 desktop on my local, home PC. It's the first time I install this CMS in Linux.
After install I came to delete the two native plugins, Aksimet & Hello Dolly.
In the first time I did so I was (strangely) asked to fill in FTP credentials. Since I have no FTP I ran the FTP problem in Google and after some reading added `define('FS_METHOD', 'direct');` in the end of wp-config.php ... It solved this prob, but then came another - an error this time, occuring when I try to remove these two plugins:
>
> Plugin could not be deleted due to an error: Could not fully remove
> the plugin(s) akismet/akismet.php, hello.php.
>
>
>
did `sudo chown benwork -R .` and also `sudo chgrp www-data -R .`
Nothing seems to help. Will thank you for your help,
|
You need to make sure that the folder permissions/ownership are correct.
Run this command to set ownership:
```
chown -R apache:apache /var/www/wordpress/
```
|
216,445 |
<p>Per default, the way to disable autosaving and post revisions, is to modify <code>wp-config.php</code>. Is there a way, to do that from within a <strong>plugin</strong> or a themes <code>functions.php</code>?</p>
|
[
{
"answer_id": 216447,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 1,
"selected": false,
"text": "<p>i have found this code:</p>\n\n<pre><code>define('my_revisions_amount', 1); // let keep only one revision\ndefine('my_autosave_interval', 600); // 600 minutes is enough\n\nif (is_admin()){ \n add_filter( 'wp_revisions_to_keep', function(){\n return my_revisions_amount;\n } );\n add_filter( 'wp_print_scripts', function(){\n wp_localize_script( 'autosave', 'autosaveL10n', \n array(\n 'autosaveInterval'=> my_autosave_interval,\n 'blog_id' => get_current_blog_id(),\n ) \n ); \n }, 11 ); \n}\n</code></pre>\n"
},
{
"answer_id": 223198,
"author": "marikamitsos",
"author_id": 17797,
"author_profile": "https://wordpress.stackexchange.com/users/17797",
"pm_score": 1,
"selected": false,
"text": "<p>You mentioned: </p>\n\n<blockquote>\n <p>Is there a way, to do that from within a plugin or a themes functions.php?</p>\n</blockquote>\n\n<p>You may want to try the following code. Just place it inside your theme's functions.php file. Using it, you do NOT have to alter the wp-config.php file. </p>\n\n<pre><code>define('WP_POST_REVISIONS', false);\nfunction disable_autosave() {\n wp_deregister_script('autosave');\n}\nadd_action('wp_print_scripts', 'disable_autosave');\n</code></pre>\n"
},
{
"answer_id": 258389,
"author": "tpaksu",
"author_id": 14452,
"author_profile": "https://wordpress.stackexchange.com/users/14452",
"pm_score": 0,
"selected": false,
"text": "<p>This is my way of disabling autosave. It can be improved:</p>\n\n<pre><code>jQuery(document).ajaxSend(function( event, jqxhr, settings) {\n if(settings && settings.data && settings.data.indexOf(\"wp_autosave\") > 0) {\n jqxhr.abort();\n }\n});\n</code></pre>\n\n<p>Just checks the ajax request before it's sent to the server, and then cancels it if it's data contains <code>wp_autosave</code> string.</p>\n"
},
{
"answer_id": 380308,
"author": "Intelligent Web Solution",
"author_id": 166953,
"author_profile": "https://wordpress.stackexchange.com/users/166953",
"pm_score": 0,
"selected": false,
"text": "<p>For guys who use WordPress 5.0+ version with Gutenberg Editor, the below code snippet works to disable auto drafting/saving.</p>\n<pre><code>/**\n * Disables auto-saving feature for Gutenberg Editor (set interval by 3600s)\n */\nadd_filter( 'block_editor_settings', 'rsm0128_block_editor_settings', 10, 2 );\nfunction rsm0128_block_editor_settings( $editor_settings, $post ) {\n $editor_settings['autosaveInterval'] = 3600;\n return $editor_settings;\n}\n</code></pre>\n"
}
] |
2016/02/02
|
[
"https://wordpress.stackexchange.com/questions/216445",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33667/"
] |
Per default, the way to disable autosaving and post revisions, is to modify `wp-config.php`. Is there a way, to do that from within a **plugin** or a themes `functions.php`?
|
i have found this code:
```
define('my_revisions_amount', 1); // let keep only one revision
define('my_autosave_interval', 600); // 600 minutes is enough
if (is_admin()){
add_filter( 'wp_revisions_to_keep', function(){
return my_revisions_amount;
} );
add_filter( 'wp_print_scripts', function(){
wp_localize_script( 'autosave', 'autosaveL10n',
array(
'autosaveInterval'=> my_autosave_interval,
'blog_id' => get_current_blog_id(),
)
);
}, 11 );
}
```
|
216,468 |
<p>So I have this in my functions file - it defines the products that are not eligible for free shipping. It works everything is fine. </p>
<pre><code>//functions.php
function my_free_shipping( $is_available ) {
global $woocommerce;
// set the product ids that are $product_notfree_ship
$product_notfree_ship = array( '1', '2', '3', '4', '5' );
// get cart contents
$cart_items = $woocommerce->cart->get_cart();
// loop through the items looking for one in the ineligible array
foreach ( $cart_items as $key => $item ) {
if( in_array( $item['product_id'], $product_notfree_ship ) ) {
return false;
}
}
// nothing found return the default value
return $is_available;
}
add_filter( 'woocommerce_shipping_free_shipping_is_available', 'my_free_shipping', 20 );
</code></pre>
<p>All of the product ID's that I have entered into the array <code>$product_notfree_ship</code> are denied free shipping.</p>
<p>Now I want to call those product IDs on the product pages to check and see if they should receive a "Free shipping applies" message or an "Additional shipping charge applies" </p>
<p>so in my theme/woocommerce/single-product/product-image.php (I want it after the main img) file I have</p>
<pre><code>//theme/woocommerce/single-product/template.php
$product_notfree_ship = array( '1', '2', '3', '4', '5' );
// this is commented because it didn't work,
// global $product_notfree_ship;
if ( is_single($product_notfree_ship) ) {
echo 'Additional Shipping Charges Apply';
} else {
echo 'FREE SHIPPING on This Product';
}
</code></pre>
<p>Now, this is working, it just feels stupid to have to edit both arrays, in the event that a new product id needs to be added to the "Not-free-shipping-product-array"</p>
<p>So based on the answer <a href="https://stackoverflow.com/questions/12638734/how-do-i-declare-a-global-variable-in-php-i-can-use-across-templates">here</a></p>
<p>I thought if called <code>global $product_notfree_ship;</code> before the <code>if</code> the proper code would run, however it did not. </p>
<p>Is this because I am using <code>is_single()</code> ?
Is this because its an array and it needs to be called differently?</p>
<p>Any help is appreciated. Thank you. </p>
|
[
{
"answer_id": 216471,
"author": "DHRUV GUPTA",
"author_id": 76422,
"author_profile": "https://wordpress.stackexchange.com/users/76422",
"pm_score": 0,
"selected": false,
"text": "<p>Declare it as </p>\n\n<pre><code>global $product_notfree_ship\n</code></pre>\n\n<p>as you are doing, just access it via this </p>\n\n<pre><code>$GLOBALS['product_notfree_ship'];\n</code></pre>\n"
},
{
"answer_id": 216472,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 2,
"selected": true,
"text": "<p>It is all fine. You just need to declare variable global first then you can set the value of this and access globally.</p>\n\n<pre><code>function my_free_shipping( $is_available ) {\nglobal $woocommerce, $product_notfree_ship;\n\n// set the product ids that are $product_notfree_ship\n$product_notfree_ship = array( '1', '2', '3', '4', '5' );\n</code></pre>\n\n<p>Then again declare it globally when using again in another file</p>\n\n<pre><code>global $product_notfree_ship;\n\nif ( is_single($product_notfree_ship) ) {\n echo 'Additional Shipping Charges Apply';\n} else {\n echo 'FREE SHIPPING on This Product';\n}\n</code></pre>\n\n<p>This is how global variable works.</p>\n"
}
] |
2016/02/02
|
[
"https://wordpress.stackexchange.com/questions/216468",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85437/"
] |
So I have this in my functions file - it defines the products that are not eligible for free shipping. It works everything is fine.
```
//functions.php
function my_free_shipping( $is_available ) {
global $woocommerce;
// set the product ids that are $product_notfree_ship
$product_notfree_ship = array( '1', '2', '3', '4', '5' );
// get cart contents
$cart_items = $woocommerce->cart->get_cart();
// loop through the items looking for one in the ineligible array
foreach ( $cart_items as $key => $item ) {
if( in_array( $item['product_id'], $product_notfree_ship ) ) {
return false;
}
}
// nothing found return the default value
return $is_available;
}
add_filter( 'woocommerce_shipping_free_shipping_is_available', 'my_free_shipping', 20 );
```
All of the product ID's that I have entered into the array `$product_notfree_ship` are denied free shipping.
Now I want to call those product IDs on the product pages to check and see if they should receive a "Free shipping applies" message or an "Additional shipping charge applies"
so in my theme/woocommerce/single-product/product-image.php (I want it after the main img) file I have
```
//theme/woocommerce/single-product/template.php
$product_notfree_ship = array( '1', '2', '3', '4', '5' );
// this is commented because it didn't work,
// global $product_notfree_ship;
if ( is_single($product_notfree_ship) ) {
echo 'Additional Shipping Charges Apply';
} else {
echo 'FREE SHIPPING on This Product';
}
```
Now, this is working, it just feels stupid to have to edit both arrays, in the event that a new product id needs to be added to the "Not-free-shipping-product-array"
So based on the answer [here](https://stackoverflow.com/questions/12638734/how-do-i-declare-a-global-variable-in-php-i-can-use-across-templates)
I thought if called `global $product_notfree_ship;` before the `if` the proper code would run, however it did not.
Is this because I am using `is_single()` ?
Is this because its an array and it needs to be called differently?
Any help is appreciated. Thank you.
|
It is all fine. You just need to declare variable global first then you can set the value of this and access globally.
```
function my_free_shipping( $is_available ) {
global $woocommerce, $product_notfree_ship;
// set the product ids that are $product_notfree_ship
$product_notfree_ship = array( '1', '2', '3', '4', '5' );
```
Then again declare it globally when using again in another file
```
global $product_notfree_ship;
if ( is_single($product_notfree_ship) ) {
echo 'Additional Shipping Charges Apply';
} else {
echo 'FREE SHIPPING on This Product';
}
```
This is how global variable works.
|
216,474 |
<p>I'm new and getting stuck into to WordPress and really like the Elegant Theme Divi option, however I have a few questions I was hoping someone could help with.</p>
<p>I do require that the site I build can offer the following functionality</p>
<p>The ability to compare products</p>
<p>Ability to register</p>
<p>Online forms that you can complete with your requirements, drop down, text box and icon selections</p>
<p>Those requirements can then be sent to various vendors ominously via the site</p>
<p>The ability for vendors to respond with a quote</p>
<p>The user to be able to review, then select the quote they like and then contact vendor to complete the transaction</p>
<p>All of this to look and remain consistent within the theme of the site</p>
<p>Will Divi theme be able to facilitate this? Or is there another theme that may be more suitable to this type of thing</p>
<p>Sorry if I sound a bit green but a newbie giving it a go and would appreciate some advice</p>
<p>Thanks</p>
<p><a href="http://www.elegantthemes.com/gallery/divi/" rel="nofollow">http://www.elegantthemes.com/gallery/divi/</a></p>
|
[
{
"answer_id": 216471,
"author": "DHRUV GUPTA",
"author_id": 76422,
"author_profile": "https://wordpress.stackexchange.com/users/76422",
"pm_score": 0,
"selected": false,
"text": "<p>Declare it as </p>\n\n<pre><code>global $product_notfree_ship\n</code></pre>\n\n<p>as you are doing, just access it via this </p>\n\n<pre><code>$GLOBALS['product_notfree_ship'];\n</code></pre>\n"
},
{
"answer_id": 216472,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 2,
"selected": true,
"text": "<p>It is all fine. You just need to declare variable global first then you can set the value of this and access globally.</p>\n\n<pre><code>function my_free_shipping( $is_available ) {\nglobal $woocommerce, $product_notfree_ship;\n\n// set the product ids that are $product_notfree_ship\n$product_notfree_ship = array( '1', '2', '3', '4', '5' );\n</code></pre>\n\n<p>Then again declare it globally when using again in another file</p>\n\n<pre><code>global $product_notfree_ship;\n\nif ( is_single($product_notfree_ship) ) {\n echo 'Additional Shipping Charges Apply';\n} else {\n echo 'FREE SHIPPING on This Product';\n}\n</code></pre>\n\n<p>This is how global variable works.</p>\n"
}
] |
2016/02/02
|
[
"https://wordpress.stackexchange.com/questions/216474",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87988/"
] |
I'm new and getting stuck into to WordPress and really like the Elegant Theme Divi option, however I have a few questions I was hoping someone could help with.
I do require that the site I build can offer the following functionality
The ability to compare products
Ability to register
Online forms that you can complete with your requirements, drop down, text box and icon selections
Those requirements can then be sent to various vendors ominously via the site
The ability for vendors to respond with a quote
The user to be able to review, then select the quote they like and then contact vendor to complete the transaction
All of this to look and remain consistent within the theme of the site
Will Divi theme be able to facilitate this? Or is there another theme that may be more suitable to this type of thing
Sorry if I sound a bit green but a newbie giving it a go and would appreciate some advice
Thanks
<http://www.elegantthemes.com/gallery/divi/>
|
It is all fine. You just need to declare variable global first then you can set the value of this and access globally.
```
function my_free_shipping( $is_available ) {
global $woocommerce, $product_notfree_ship;
// set the product ids that are $product_notfree_ship
$product_notfree_ship = array( '1', '2', '3', '4', '5' );
```
Then again declare it globally when using again in another file
```
global $product_notfree_ship;
if ( is_single($product_notfree_ship) ) {
echo 'Additional Shipping Charges Apply';
} else {
echo 'FREE SHIPPING on This Product';
}
```
This is how global variable works.
|
216,480 |
<p>I am trying to output the latest 5 posts from my blog. I would like each post thumbnail to populate divs in the following format.</p>
<pre><code><div class="row full">
<div class="large-6 medium-6 small-12 columns"></div>
<div class="large-6 medium-6 small-12 columns"></div>
</div>
<div class="row full">
<div class="large-4 medium-4 small-12 columns"></div>
<div class="large-4 medium-4 small-12 columns"></div>
<div class="large-4 medium-4 small-12 columns"></div>
</div>
</code></pre>
<p>I've obtained this code from another post with a few edits but I'm not hitting the mark. </p>
<pre><code><?php
// Let's get all posts with thumbnail set in some category
$args = [
'posts_per_page' => 5,
'orderby' => 'date',
'order' => 'DESC'
];
// Fetch posts
$query = new WP_Query( $args );
if( $query->have_posts() )
{
while ( $query->have_posts() )
{
$query->the_post();
// Collect all items into a temp array
$tmp[] = sprintf(
'<div class="small-12 medium-6 large-6 columns"><a href="%s">%s</a></div>',
get_permalink(),
get_the_post_thumbnail( get_the_ID(), 'large' )
);
}
$tmpp[] = sprintf(
'<div class="small-12 medium-4 large-4 columns"><a href="%s">%s</a></div>',
get_permalink(),
get_the_post_thumbnail( get_the_ID(), 'large' )
);
}
// Split the divs into rows of 2 items
$rows = array_chunk( $tmp, 2 );
// Split the second chunk of divs into rows of 3 items
$rowss = array_chunk ($tmpp, 3);
// Housecleaning
unset( $tmp );
unset( $tmpp);
wp_reset_postdata();
// Output the rows
foreach( $rows as $row ){
printf( '<div class="row full">%s</div>', join( '', $row ) );
}
foreach( $rowss as $roww ){
printf( '<div class="row full">%s</div>', join( '', $roww ) );
}
?>
</code></pre>
<p>Unfortunately it's not working correctly. What it's outputting is this:</p>
<pre><code><div class="row full">
<div class="small-12 medium-6 large-6 columns"><a href="http://localhost:8888/myoshdiy/2015/12/15/5-decorating-tips-for-every-living-room/"><img width="1024" height="640" src="http://localhost:8888/myoshdiy/wp-content/uploads/2015/12/living-room-pictures-1024x640.jpg" class="attachment-large wp-post-image" alt="living-room-pictures"></a></div>
<div class="small-12 medium-6 large-6 columns"><a href="http://localhost:8888/myoshdiy/2014/03/26/excepteur-sint/"><img width="800" height="533" src="http://localhost:8888/myoshdiy/wp-content/uploads/2014/03/LED-flushmount.jpg" class="attachment-large wp-post-image" alt="LED-flushmount"></a></div>
</div>
<div class="row full">
<div class="small-12 medium-6 large-6 columns"><a href="http://localhost:8888/myoshdiy/2014/03/26/post-template-2/"><img width="576" height="384" src="http://localhost:8888/myoshdiy/wp-content/uploads/2014/03/165912.jpg" class="attachment-large wp-post-image" alt="165912"></a></div>
<div class="small-12 medium-6 large-6 columns"><a href="http://localhost:8888/myoshdiy/2014/03/26/left-sidebar-post/"><img width="800" height="534" src="http://localhost:8888/myoshdiy/wp-content/uploads/2014/03/165961.jpg" class="attachment-large wp-post-image" alt="165961"></a></div>
</div>
<div class="row full">
<div class="small-12 medium-6 large-6 columns"><a href="http://localhost:8888/myoshdiy/2014/03/26/wine-101-essential-wine-tips-and-information/"><img width="1024" height="682" src="http://localhost:8888/myoshdiy/wp-content/uploads/2014/03/IMG_9944-1300x866-1024x682.jpg" class="attachment-large wp-post-image" alt="IMG_9944-1300x866"></a></div>
</div>
<div class="row full">
<div class="small-12 medium-4 large-4 columns"><a href="http://localhost:8888/myoshdiy/2014/03/26/wine-101-essential-wine-tips-and-information/"><img width="1024" height="682" src="http://localhost:8888/myoshdiy/wp-content/uploads/2014/03/IMG_9944-1300x866-1024x682.jpg" class="attachment-large wp-post-image" alt="IMG_9944-1300x866"></a></div>
</div>
</code></pre>
|
[
{
"answer_id": 238883,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>That's a pretty complicated approach you're taking. Why not simply add a counter? Like this: </p>\n\n<pre><code>$i=1;\necho '<div class=\"row full\">';\nif( $query->have_posts() ) {\n while ( $query->have_posts() ) {\n $query->the_post();\n if ($i < 3)\n $class = \"large-6 medium-6 small-12 columns\"\n else\n \"large-4 medium-4 small-12 columns\";\n echo '<div class=\"' . $class . '\">'\n ... output your post ...\n echo '</div>'\n if ($i=2) echo '</div><div class=\"row full\">';\n $i = $i+1;\n }\n }\necho '</div>';\n</code></pre>\n"
},
{
"answer_id": 238890,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p>Here's an alternative suggestion:</p>\n\n<pre><code>if( $query->have_posts() )\n{\n while ( $query->have_posts() )\n {\n $query->the_post(); \n\n // Collect all items into a temp array \n $tmp[] = sprintf( \n '<a href=\"%s\">%s</a>',\n get_permalink(),\n get_the_post_thumbnail( get_the_ID(), 'large' )\n );\n } \n\n wp_reset_postdata();\n\n // Display rows 1-2\n the_wpse_rows( \n $tmp, \n $from = 0, \n $number = 2, \n $outer_class = 'row full', \n $inner_class = 'large-6 medium-6 small-12 columns' \n );\n\n // Display rows 3-5\n the_wpse_rows( \n $tmp, \n $from = 2, \n $number = 3, \n $outer_class = 'row full', \n $inner_class = 'large-4 medium-4 small-12 columns'\n );\n\n unset( $tmp );\n} \n</code></pre>\n\n<p>where we define our helper function as:</p>\n\n<pre><code>function the_wpse_rows( Array $data, $from, $number, $outer_class, $inner_class )\n{\n $inner_class = esc_attr( $inner_class );\n $outer_class = esc_attr( $outer_class );\n\n if( $rows = array_slice( (array) $data, $from, $number ) )\n printf( \n \"<div class='{$outer_class}'><div class='{$inner_class}'>%s</div></div>\", \n join( \"</div><div class='{$inner_class}'>\", $rows ) \n ); \n}\n</code></pre>\n\n<p>were we use <code>array_slice()</code> instead of <code>array_chunk()</code>.</p>\n"
}
] |
2016/02/02
|
[
"https://wordpress.stackexchange.com/questions/216480",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84666/"
] |
I am trying to output the latest 5 posts from my blog. I would like each post thumbnail to populate divs in the following format.
```
<div class="row full">
<div class="large-6 medium-6 small-12 columns"></div>
<div class="large-6 medium-6 small-12 columns"></div>
</div>
<div class="row full">
<div class="large-4 medium-4 small-12 columns"></div>
<div class="large-4 medium-4 small-12 columns"></div>
<div class="large-4 medium-4 small-12 columns"></div>
</div>
```
I've obtained this code from another post with a few edits but I'm not hitting the mark.
```
<?php
// Let's get all posts with thumbnail set in some category
$args = [
'posts_per_page' => 5,
'orderby' => 'date',
'order' => 'DESC'
];
// Fetch posts
$query = new WP_Query( $args );
if( $query->have_posts() )
{
while ( $query->have_posts() )
{
$query->the_post();
// Collect all items into a temp array
$tmp[] = sprintf(
'<div class="small-12 medium-6 large-6 columns"><a href="%s">%s</a></div>',
get_permalink(),
get_the_post_thumbnail( get_the_ID(), 'large' )
);
}
$tmpp[] = sprintf(
'<div class="small-12 medium-4 large-4 columns"><a href="%s">%s</a></div>',
get_permalink(),
get_the_post_thumbnail( get_the_ID(), 'large' )
);
}
// Split the divs into rows of 2 items
$rows = array_chunk( $tmp, 2 );
// Split the second chunk of divs into rows of 3 items
$rowss = array_chunk ($tmpp, 3);
// Housecleaning
unset( $tmp );
unset( $tmpp);
wp_reset_postdata();
// Output the rows
foreach( $rows as $row ){
printf( '<div class="row full">%s</div>', join( '', $row ) );
}
foreach( $rowss as $roww ){
printf( '<div class="row full">%s</div>', join( '', $roww ) );
}
?>
```
Unfortunately it's not working correctly. What it's outputting is this:
```
<div class="row full">
<div class="small-12 medium-6 large-6 columns"><a href="http://localhost:8888/myoshdiy/2015/12/15/5-decorating-tips-for-every-living-room/"><img width="1024" height="640" src="http://localhost:8888/myoshdiy/wp-content/uploads/2015/12/living-room-pictures-1024x640.jpg" class="attachment-large wp-post-image" alt="living-room-pictures"></a></div>
<div class="small-12 medium-6 large-6 columns"><a href="http://localhost:8888/myoshdiy/2014/03/26/excepteur-sint/"><img width="800" height="533" src="http://localhost:8888/myoshdiy/wp-content/uploads/2014/03/LED-flushmount.jpg" class="attachment-large wp-post-image" alt="LED-flushmount"></a></div>
</div>
<div class="row full">
<div class="small-12 medium-6 large-6 columns"><a href="http://localhost:8888/myoshdiy/2014/03/26/post-template-2/"><img width="576" height="384" src="http://localhost:8888/myoshdiy/wp-content/uploads/2014/03/165912.jpg" class="attachment-large wp-post-image" alt="165912"></a></div>
<div class="small-12 medium-6 large-6 columns"><a href="http://localhost:8888/myoshdiy/2014/03/26/left-sidebar-post/"><img width="800" height="534" src="http://localhost:8888/myoshdiy/wp-content/uploads/2014/03/165961.jpg" class="attachment-large wp-post-image" alt="165961"></a></div>
</div>
<div class="row full">
<div class="small-12 medium-6 large-6 columns"><a href="http://localhost:8888/myoshdiy/2014/03/26/wine-101-essential-wine-tips-and-information/"><img width="1024" height="682" src="http://localhost:8888/myoshdiy/wp-content/uploads/2014/03/IMG_9944-1300x866-1024x682.jpg" class="attachment-large wp-post-image" alt="IMG_9944-1300x866"></a></div>
</div>
<div class="row full">
<div class="small-12 medium-4 large-4 columns"><a href="http://localhost:8888/myoshdiy/2014/03/26/wine-101-essential-wine-tips-and-information/"><img width="1024" height="682" src="http://localhost:8888/myoshdiy/wp-content/uploads/2014/03/IMG_9944-1300x866-1024x682.jpg" class="attachment-large wp-post-image" alt="IMG_9944-1300x866"></a></div>
</div>
```
|
That's a pretty complicated approach you're taking. Why not simply add a counter? Like this:
```
$i=1;
echo '<div class="row full">';
if( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
if ($i < 3)
$class = "large-6 medium-6 small-12 columns"
else
"large-4 medium-4 small-12 columns";
echo '<div class="' . $class . '">'
... output your post ...
echo '</div>'
if ($i=2) echo '</div><div class="row full">';
$i = $i+1;
}
}
echo '</div>';
```
|
216,493 |
<p>I want to use the following code multiple times in the same page template, however the template gets too big when it comes to lines of code and therefore size. Every time I use it I change only one parameter and 99% remains the same. The parameter I change is <strong><code>'terms'=>'pop'</code></strong>. I know I can display all posts and all taxonomy terms (taxonomies posts under each taxonomy) with a relatively small piece of code but that will not work as I want since I want to order taxonomies in a custom way, not by title or term (ASC/DSC). What I am thinking is maybe add the code to a fuction and each time I call the function I just pass the parameter which changes.</p>
<p>The code:</p>
<pre><code>$query = new WP_Query( array(
'post_type' => 'stations',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => 'genres',
'field' => 'name',
'terms' => 'pop' // THIS IS WHAT CHANGES
)
)
) );
</code></pre>
|
[
{
"answer_id": 216495,
"author": "LukeWarm",
"author_id": 87806,
"author_profile": "https://wordpress.stackexchange.com/users/87806",
"pm_score": 0,
"selected": false,
"text": "<p>Create a new function, put all the code in it and replace 'pop' with $genre. Then call it like this:</p>\n\n<pre><code>get_stations_query( $genre );\n</code></pre>\n\n<p>the return of your function should be</p>\n\n<pre><code>return $query;\n</code></pre>\n"
},
{
"answer_id": 216501,
"author": "david_nash",
"author_id": 63888,
"author_profile": "https://wordpress.stackexchange.com/users/63888",
"pm_score": 2,
"selected": true,
"text": "<p>To expand on the answer by Global:</p>\n\n<p>Paste this into your theme's functions.php:</p>\n\n<pre><code>function get_stations_query( $terms ) {\n //create new query object\n $query = new WP_Query( array(\n 'post_type' => 'stations',\n 'post_status' => 'publish',\n 'posts_per_page' => -1,\n 'orderby' => 'title',\n 'order' => 'ASC',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'genres',\n 'field' => 'name',\n 'terms' => $terms\n )\n )\n ) );\n return $query; //return the object\n}\n</code></pre>\n\n<p>Then in your template files you can use:</p>\n\n<pre><code>$query = get_stations_query('pop');\n</code></pre>\n"
}
] |
2016/02/02
|
[
"https://wordpress.stackexchange.com/questions/216493",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/15801/"
] |
I want to use the following code multiple times in the same page template, however the template gets too big when it comes to lines of code and therefore size. Every time I use it I change only one parameter and 99% remains the same. The parameter I change is **`'terms'=>'pop'`**. I know I can display all posts and all taxonomy terms (taxonomies posts under each taxonomy) with a relatively small piece of code but that will not work as I want since I want to order taxonomies in a custom way, not by title or term (ASC/DSC). What I am thinking is maybe add the code to a fuction and each time I call the function I just pass the parameter which changes.
The code:
```
$query = new WP_Query( array(
'post_type' => 'stations',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => 'genres',
'field' => 'name',
'terms' => 'pop' // THIS IS WHAT CHANGES
)
)
) );
```
|
To expand on the answer by Global:
Paste this into your theme's functions.php:
```
function get_stations_query( $terms ) {
//create new query object
$query = new WP_Query( array(
'post_type' => 'stations',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => 'genres',
'field' => 'name',
'terms' => $terms
)
)
) );
return $query; //return the object
}
```
Then in your template files you can use:
```
$query = get_stations_query('pop');
```
|
216,497 |
<p>I'm trying to make a custom permalink structure for my posts.</p>
<pre><code>www.example.com / post / %post_id% / %posttitle% /
</code></pre>
<p>In this permalink, the post's ID comes first, then the post's title after it.</p>
<hr />
<h2>Things I know until now</h2>
<p><code>postname</code> is usually stored in the <code>wp_posts</code> table in the <code>post_name</code> row, and it controlles the post's URL. ie: if the post's <code>post_name</code> is <code>my-post-name</code>, it's default URL will be <code>www.example.com/post/my-post-name</code>.</p>
<p>post names are stored in the database in a way such that every post has a unique post name. If two posts have the same title (for example <code>new-advanced-topic</code>), the first post's name will be <code>new-advanced-topic</code> and the second post's name will be <code>new-advanced-topic-2</code>. And so there URLs will differ from each other.</p>
<hr />
<h2>What I want</h2>
<p>But I don't want the post's URL to depend on the post's name stored in the database.</p>
<p>The structure I want is similar to</p>
<pre><code>www.example.com / post / %post_id% / %posttitle% /
</code></pre>
<p>Suppose that There is 2 posts stored in the database with these values</p>
<pre><code>╔════╦════════════════════╦═════════════════════╗
║ ID ║ post_title ║ post_name ║
╠════╬════════════════════╬═════════════════════╣
║ 25 ║ new-advanced-topic ║ new-advanced-topic ║
║ 26 ║ new-advanced-topic ║ new-advanced-topic2 ║
╚════╩════════════════════╩═════════════════════╝
</code></pre>
<ul>
<li>I want the post's URL to depend only on the post's ID. So if the user requested <code>www.example.com/post/25/pla-pla-pla</code>, The post that will be displayed is the one which it's id is 25.</li>
<li>When a user requests the link <code>www.example.com/post/{%post_id%}/pla-pla-pla</code>, I want WordPress to redirect him to <code>www.example.com/post/{%post_id%}/{%post_title%}</code>.</li>
</ul>
<p>So if user requested <code>www.example.com/post/25/pla-pla-pla</code>, WordPress will redirect him to <code>www.example.com/post/25/new-advanced-topic</code> and display the post with <code>ID=25</code>.</p>
<p>And if user requested <code>www.example.com/post/26/new-advanced-topic2</code>, WordPress will redirect him to <code>www.example.com/post/26/new-advanced-topic</code> and display the post with <code>ID=26</code>.</p>
<p>And if user requested <code>www.example.com/post/100/new-advanced-topic</code>, a 404 error should appear to him since there's no post stored in the database with <code>ID=100</code>.</p>
<p>I tried to write a new rewrite_rule to do this but I couldn't figer any way to write it's regex.</p>
<p>How can I do this using the <code>wp_rewrite</code> rules.</p>
|
[
{
"answer_id": 216521,
"author": "heshamhussain",
"author_id": 86130,
"author_profile": "https://wordpress.stackexchange.com/users/86130",
"pm_score": 1,
"selected": false,
"text": "<p>What I understand that you want to use <strong>post ID</strong> instead of <strong>Post Title</strong> .</p>\n\n<p>and you have trouble because of the same titles name .</p>\n\n<p>If that's right , the solution will be like following :</p>\n\n<p>1 - change <strong>permalink</strong> to <strong>custom structure</strong> like the following figure</p>\n\n<p><a href=\"https://i.stack.imgur.com/RfYGJ.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RfYGJ.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>2- go to <strong>phpmyadmin</strong> and change your <strong>posts name</strong> like following figure</p>\n\n<p><a href=\"https://i.stack.imgur.com/vpECp.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vpECp.jpg\" alt=\"enter image description here\"></a> </p>\n"
},
{
"answer_id": 217248,
"author": "тнє Sufi",
"author_id": 28744,
"author_profile": "https://wordpress.stackexchange.com/users/28744",
"pm_score": 3,
"selected": true,
"text": "<p>We have to do this keeping <code>post_name</code> unique. Otherwise, it might cause many troubles. We can use <code>post_title</code> with <code>sanitize_title</code>. In this way, you can keep your URL nice and clean, and your <code>post_name</code> will remain unique as well.</p>\n\n<p>First we will need to write custom permalink structure.</p>\n\n<pre><code>function my_awesome_permalink( $url, $post, $leavename ) {\n $url= trailingslashit( home_url('/post/'. $post->ID .'/'. sanitize_title($post->post_title) .'/' ) );\n return $url;\n}\nadd_filter( 'post_link', 'my_awesome_permalink', 10, 3 );\n</code></pre>\n\n<p>Now, our custom permalink structure is ready. It will become <code>www.example.com/post/{%post_id%}/{%post_title%}</code> e.g.: <code>www.example.com/post/25/my-awesome-post-title</code> . We will need to add proper rewrite rule to make WP understand and return the right post.</p>\n\n<pre><code>add_action('generate_rewrite_rules', 'custom_rewrite_rules');\nfunction custom_rewrite_rules( $wp_rewrite ) {\n $new_rules['^post/([0-9]+)/([^/]+)/?'] = 'index.php?p=$matches[1]';\n $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;\n return $wp_rewrite;\n}\n</code></pre>\n\n<p>With above code, you will be able to make your post permalink structure to <code>www.example.com/post/25/my-awesome-post-title</code> and it will show correct post.</p>\n\n<p>One problem with above code is, you won't be able to edit post slug from post editor. But your post url now comes from post title, which is editable!</p>\n"
}
] |
2016/02/02
|
[
"https://wordpress.stackexchange.com/questions/216497",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86145/"
] |
I'm trying to make a custom permalink structure for my posts.
```
www.example.com / post / %post_id% / %posttitle% /
```
In this permalink, the post's ID comes first, then the post's title after it.
---
Things I know until now
-----------------------
`postname` is usually stored in the `wp_posts` table in the `post_name` row, and it controlles the post's URL. ie: if the post's `post_name` is `my-post-name`, it's default URL will be `www.example.com/post/my-post-name`.
post names are stored in the database in a way such that every post has a unique post name. If two posts have the same title (for example `new-advanced-topic`), the first post's name will be `new-advanced-topic` and the second post's name will be `new-advanced-topic-2`. And so there URLs will differ from each other.
---
What I want
-----------
But I don't want the post's URL to depend on the post's name stored in the database.
The structure I want is similar to
```
www.example.com / post / %post_id% / %posttitle% /
```
Suppose that There is 2 posts stored in the database with these values
```
╔════╦════════════════════╦═════════════════════╗
║ ID ║ post_title ║ post_name ║
╠════╬════════════════════╬═════════════════════╣
║ 25 ║ new-advanced-topic ║ new-advanced-topic ║
║ 26 ║ new-advanced-topic ║ new-advanced-topic2 ║
╚════╩════════════════════╩═════════════════════╝
```
* I want the post's URL to depend only on the post's ID. So if the user requested `www.example.com/post/25/pla-pla-pla`, The post that will be displayed is the one which it's id is 25.
* When a user requests the link `www.example.com/post/{%post_id%}/pla-pla-pla`, I want WordPress to redirect him to `www.example.com/post/{%post_id%}/{%post_title%}`.
So if user requested `www.example.com/post/25/pla-pla-pla`, WordPress will redirect him to `www.example.com/post/25/new-advanced-topic` and display the post with `ID=25`.
And if user requested `www.example.com/post/26/new-advanced-topic2`, WordPress will redirect him to `www.example.com/post/26/new-advanced-topic` and display the post with `ID=26`.
And if user requested `www.example.com/post/100/new-advanced-topic`, a 404 error should appear to him since there's no post stored in the database with `ID=100`.
I tried to write a new rewrite\_rule to do this but I couldn't figer any way to write it's regex.
How can I do this using the `wp_rewrite` rules.
|
We have to do this keeping `post_name` unique. Otherwise, it might cause many troubles. We can use `post_title` with `sanitize_title`. In this way, you can keep your URL nice and clean, and your `post_name` will remain unique as well.
First we will need to write custom permalink structure.
```
function my_awesome_permalink( $url, $post, $leavename ) {
$url= trailingslashit( home_url('/post/'. $post->ID .'/'. sanitize_title($post->post_title) .'/' ) );
return $url;
}
add_filter( 'post_link', 'my_awesome_permalink', 10, 3 );
```
Now, our custom permalink structure is ready. It will become `www.example.com/post/{%post_id%}/{%post_title%}` e.g.: `www.example.com/post/25/my-awesome-post-title` . We will need to add proper rewrite rule to make WP understand and return the right post.
```
add_action('generate_rewrite_rules', 'custom_rewrite_rules');
function custom_rewrite_rules( $wp_rewrite ) {
$new_rules['^post/([0-9]+)/([^/]+)/?'] = 'index.php?p=$matches[1]';
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
return $wp_rewrite;
}
```
With above code, you will be able to make your post permalink structure to `www.example.com/post/25/my-awesome-post-title` and it will show correct post.
One problem with above code is, you won't be able to edit post slug from post editor. But your post url now comes from post title, which is editable!
|
216,506 |
<p>My ultimate goal is to list the latest 5 posts, regardless of category.</p>
<p>I would first like to make a <code>WP_Query</code> to get the latest two posts and insert them in to a specific HTML structure.</p>
<p>Then I would like to make another <code>WP_Query</code> to get the next three posts and insert them in to a differing HTML structure.</p>
<p>I've tried a few code snippets and what happens is each <code>WP_Query</code> starts from the latest post in both HTML structures. Is there an arg that I can use to specifically tell the second query to skip the first two posts?</p>
|
[
{
"answer_id": 216507,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters\" rel=\"nofollow\"><code>WP_Query</code>'s pagination paramters</a>. </p>\n\n<p>However, using two queries to accomplish this objective is inefficient. A better solution it to use one query and alter your markup based on the value of <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Methods_and_Properties\" rel=\"nofollow\"><code>WP_Query</code>'s <code>$current_post</code> property</a>, which (when used in the loop) reflects the index of the post currently being processed within the current page of results.</p>\n"
},
{
"answer_id": 216546,
"author": "Prakash Rao",
"author_id": 86448,
"author_profile": "https://wordpress.stackexchange.com/users/86448",
"pm_score": 3,
"selected": false,
"text": "<p>Run one wp_query for post_per_page = 2 and get the IDs of these 2 posts in an array to be excluded in the next 3 posts needed </p>\n\n<pre><code><?php\n\n // The Query\n $next_args = array(\n 'post_type' => '<your_post_type>',\n 'post_status' => 'publish',\n 'posts_per_page'=>2,\n 'order'=>'DESC',\n 'orderby'=>'ID',\n );\n\n $the_query = new WP_Query( $args );\n\n // The Loop\n if ( $the_query->have_posts() ) {\n $not_in_next_three = array();\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n //your html here for latest 2\n $not_in_next_three[] = get_the_ID();\n }\n\n } else {\n // no posts found\n }\n /* Restore original Post Data */\n wp_reset_postdata();\n</code></pre>\n\n<p>Now the array created above to be excluded in the wp_query fetching the next 3 posts</p>\n\n<pre><code>// The Query\n$next_args = array(\n 'post_type' => '<your_post_type>',\n 'post_status' => 'publish',\n 'posts_per_page'=>3,\n 'order'=>'DESC',\n 'orderby'=>'ID',\n 'post__not_in'=>$not_in_next_three\n );\n$next_the_query = new WP_Query( $next_args );\n\n// The Loop\nif ( $next_the_query->have_posts() ) {\n while ( $next_the_query->have_posts() ) {\n $next_the_query->the_post();\n //your html here fir latest next 3\n\n }\n\n} else {\n // no posts found\n}\n/* Restore original Post Data */\nwp_reset_postdata();\n\n?>\n</code></pre>\n"
}
] |
2016/02/02
|
[
"https://wordpress.stackexchange.com/questions/216506",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84666/"
] |
My ultimate goal is to list the latest 5 posts, regardless of category.
I would first like to make a `WP_Query` to get the latest two posts and insert them in to a specific HTML structure.
Then I would like to make another `WP_Query` to get the next three posts and insert them in to a differing HTML structure.
I've tried a few code snippets and what happens is each `WP_Query` starts from the latest post in both HTML structures. Is there an arg that I can use to specifically tell the second query to skip the first two posts?
|
Run one wp\_query for post\_per\_page = 2 and get the IDs of these 2 posts in an array to be excluded in the next 3 posts needed
```
<?php
// The Query
$next_args = array(
'post_type' => '<your_post_type>',
'post_status' => 'publish',
'posts_per_page'=>2,
'order'=>'DESC',
'orderby'=>'ID',
);
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
$not_in_next_three = array();
while ( $the_query->have_posts() ) {
$the_query->the_post();
//your html here for latest 2
$not_in_next_three[] = get_the_ID();
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
```
Now the array created above to be excluded in the wp\_query fetching the next 3 posts
```
// The Query
$next_args = array(
'post_type' => '<your_post_type>',
'post_status' => 'publish',
'posts_per_page'=>3,
'order'=>'DESC',
'orderby'=>'ID',
'post__not_in'=>$not_in_next_three
);
$next_the_query = new WP_Query( $next_args );
// The Loop
if ( $next_the_query->have_posts() ) {
while ( $next_the_query->have_posts() ) {
$next_the_query->the_post();
//your html here fir latest next 3
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
?>
```
|
216,515 |
<p>everyone!</p>
<p>I was wondering if anyone would be able to tell me how the content in my center column is able to expand its allowed container size and push my right column/widget area to the bottom?</p>
<p>Here's a link to the page where I'm having this problem: <a href="https://goo.gl/XFnmnD" rel="nofollow">https://goo.gl/XFnmnD</a></p>
<p>Here's a screenshot to show exactly where on the page the problem is: <a href="http://snag.gy/3A0Sg.jpg" rel="nofollow">http://snag.gy/3A0Sg.jpg</a>. </p>
<p>This only happens with the plugin I'm using. I tried practically changing every container width % to 96%, which didn't work. The problem only happens when the user is logged out. When the user logs in, everything fits fine. If I remove the plugin and put something else there, there's no problem either. Any ideas? </p>
<p>Thanks!</p>
<p>P.S. I just joined today, so go easy on me, please. </p>
|
[
{
"answer_id": 216517,
"author": "Cheffheid",
"author_id": 64470,
"author_profile": "https://wordpress.stackexchange.com/users/64470",
"pm_score": 1,
"selected": false,
"text": "<p>As far as I can tell, the most right column is being nested within the middle reviews column.</p>\n\n<p>I imagine that somewhere in the code (template, sidebar, or widget) there is a conditional statement causing your middle column to not get closed off before the right column starts.</p>\n\n<p>To illustrate what is happening, this is how it currently gets rendered:</p>\n\n<pre><code><div class=\"fl-col fl-col-small fl-node-569586b0f1e9e\" style=\"width: 39.94%;\" data-node=\"569586b0f1e9e\">\n ...middle column content...\n\n <div class=\"fl-col fl-col-small fl-node-569586b0f1ee5\" style=\"width: 20.02%;\" data-node=\"569586b0f1ee5\">\n ...right column content...\n </div>\n</div>\n</code></pre>\n\n<p>But what it should be:</p>\n\n<pre><code><div class=\"fl-col fl-col-small fl-node-569586b0f1e9e\" style=\"width: 39.94%;\" data-node=\"569586b0f1e9e\">\n ...middle column content...\n</div>\n<div class=\"fl-col fl-col-small fl-node-569586b0f1ee5\" style=\"width: 20.02%;\" data-node=\"569586b0f1ee5\">\n ...right column content...\n</div>\n</code></pre>\n"
},
{
"answer_id": 216523,
"author": "andrewf12",
"author_id": 88003,
"author_profile": "https://wordpress.stackexchange.com/users/88003",
"pm_score": -1,
"selected": false,
"text": "<p>So that was a wonderful idea! I decided to inspect the HTML elements and removed the pieces of code that had a matching pair. I realized they all had a matching pair; however, for some reason, the second column's container was enveloping the third column's container to make it a sub-container if that makes sense?</p>\n\n<p>Here's the code snippet I managed to parse out:</p>\n\n<p><a href=\"http://snag.gy/oDJB4.jpg\" rel=\"nofollow\">http://snag.gy/oDJB4.jpg</a></p>\n\n<p>It's a screenshot since I can't figure out how to select the whole selection and and copy and paste. I put red square brackets to show the third container's location.</p>\n\n<p>So thanks for helping solve the first problem. I guess the second now is: Does anyone know what code I should look for to figure out how the second container/plugin I'm using is making the third container a child container?</p>\n\n<p>Thanks again, everyone!</p>\n"
}
] |
2016/02/03
|
[
"https://wordpress.stackexchange.com/questions/216515",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88003/"
] |
everyone!
I was wondering if anyone would be able to tell me how the content in my center column is able to expand its allowed container size and push my right column/widget area to the bottom?
Here's a link to the page where I'm having this problem: <https://goo.gl/XFnmnD>
Here's a screenshot to show exactly where on the page the problem is: <http://snag.gy/3A0Sg.jpg>.
This only happens with the plugin I'm using. I tried practically changing every container width % to 96%, which didn't work. The problem only happens when the user is logged out. When the user logs in, everything fits fine. If I remove the plugin and put something else there, there's no problem either. Any ideas?
Thanks!
P.S. I just joined today, so go easy on me, please.
|
As far as I can tell, the most right column is being nested within the middle reviews column.
I imagine that somewhere in the code (template, sidebar, or widget) there is a conditional statement causing your middle column to not get closed off before the right column starts.
To illustrate what is happening, this is how it currently gets rendered:
```
<div class="fl-col fl-col-small fl-node-569586b0f1e9e" style="width: 39.94%;" data-node="569586b0f1e9e">
...middle column content...
<div class="fl-col fl-col-small fl-node-569586b0f1ee5" style="width: 20.02%;" data-node="569586b0f1ee5">
...right column content...
</div>
</div>
```
But what it should be:
```
<div class="fl-col fl-col-small fl-node-569586b0f1e9e" style="width: 39.94%;" data-node="569586b0f1e9e">
...middle column content...
</div>
<div class="fl-col fl-col-small fl-node-569586b0f1ee5" style="width: 20.02%;" data-node="569586b0f1ee5">
...right column content...
</div>
```
|
216,555 |
<p>So I have a URL which has a tracking link applied to the end. For some reason WordPress is removing the <code>&</code> which is causing the tracking to fail. You can see the URL example here:</p>
<blockquote>
<p><a href="http://www.domain.co.uk/internalpage/?&mkwid=smWfvaLGf_dm" rel="nofollow noreferrer">http://www.domain.co.uk/internalpage/?&mkwid=smWfvaLGf_dm</a></p>
</blockquote>
<p>When you go through this, you then get <strong>redirected</strong> in a way to:</p>
<blockquote>
<p><a href="http://www.domain.co.uk/internalpage/?mkwid=smWfvaLGf_dm" rel="nofollow noreferrer">http://www.domain.co.uk/internalpage/?mkwid=smWfvaLGf_dm</a></p>
</blockquote>
<p>Note the <code>&</code> has been removed. Also, this only happens on internal pages. Does anyone know how to stop this?</p>
|
[
{
"answer_id": 216563,
"author": "Arpita Hunka",
"author_id": 86864,
"author_profile": "https://wordpress.stackexchange.com/users/86864",
"pm_score": 0,
"selected": false,
"text": "<p>You can use here rawurlencode() function. First pass \"?&mkwid=smWfvaLGf_dm\" this url into the function then you will get \"%3F%26mkwid%3DsmWfvaLGf_dm\" encoded value.</p>\n\n<p>Now go on the functions.php and put this code there (But this code will run on every call of you site)</p>\n\n<pre><code>//for accessing current url\n$accessUrl = get_site_url() .$_SERVER['REQUEST_URI'];\n\n$pos = strpos($accessUrl, \"%\");\nif ($pos !== false) \n{\n $accessString = rawurldecode($accessUrl);\n wp_redirect($accessString);\n exit();\n}\n</code></pre>\n\n<p>I feel this will help you.\nThanks</p>\n"
},
{
"answer_id": 216565,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p>Here's the <em>why</em> part:</p>\n\n<p><a href=\"https://github.com/WordPress/WordPress/blob/72c6f7f86f133a0d5ec669526eeb29ca024c0c19/wp-includes/canonical.php#L358-L359\" rel=\"nofollow\">This part</a> of the <code>redirect_canonical()</code> is removing the leading <code>&</code> in the <em>redirect query</em> part:</p>\n\n<pre><code>// tack on any additional query vars\n$redirect['query'] = preg_replace( '#^\\??&*?#', '', $redirect['query'] );\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>example.tld/?&a=1&b=2&c=3 \n</code></pre>\n\n<p>is redirected to </p>\n\n<pre><code>example.tld/?a=1&b=2&c=3 \n</code></pre>\n\n<p>If you must have the leading <code>&</code> you might try to adjust it through the <code>redirect_canonical</code> filter:</p>\n\n<pre><code>/**\n * Filter the canonical redirect URL.\n *\n * Returning false to this filter will cancel the redirect.\n *\n * @since 2.3.0\n *\n * @param string $redirect_url The redirect URL.\n * @param string $requested_url The requested URL.\n */\n$redirect_url = apply_filters( 'redirect_canonical', $redirect_url, $requested_url );\n</code></pre>\n"
}
] |
2016/02/03
|
[
"https://wordpress.stackexchange.com/questions/216555",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88030/"
] |
So I have a URL which has a tracking link applied to the end. For some reason WordPress is removing the `&` which is causing the tracking to fail. You can see the URL example here:
>
> <http://www.domain.co.uk/internalpage/?&mkwid=smWfvaLGf_dm>
>
>
>
When you go through this, you then get **redirected** in a way to:
>
> <http://www.domain.co.uk/internalpage/?mkwid=smWfvaLGf_dm>
>
>
>
Note the `&` has been removed. Also, this only happens on internal pages. Does anyone know how to stop this?
|
Here's the *why* part:
[This part](https://github.com/WordPress/WordPress/blob/72c6f7f86f133a0d5ec669526eeb29ca024c0c19/wp-includes/canonical.php#L358-L359) of the `redirect_canonical()` is removing the leading `&` in the *redirect query* part:
```
// tack on any additional query vars
$redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
```
Example:
```
example.tld/?&a=1&b=2&c=3
```
is redirected to
```
example.tld/?a=1&b=2&c=3
```
If you must have the leading `&` you might try to adjust it through the `redirect_canonical` filter:
```
/**
* Filter the canonical redirect URL.
*
* Returning false to this filter will cancel the redirect.
*
* @since 2.3.0
*
* @param string $redirect_url The redirect URL.
* @param string $requested_url The requested URL.
*/
$redirect_url = apply_filters( 'redirect_canonical', $redirect_url, $requested_url );
```
|
216,573 |
<p>This is more of a 'Is it possible question" I have a home page which has a full width header and a transparent Navbar, when you scroll this Navbar changes to white. On all my other pages I want this Navbar to start white and stay white as you scroll. </p>
<p>At the moment Im using jQuery to make the Navbar turn white which works fine of course. But does anyone know how I can achieve what I have described? </p>
<p>Any Answers/Suggestions appreciated and welcome! </p>
|
[
{
"answer_id": 216563,
"author": "Arpita Hunka",
"author_id": 86864,
"author_profile": "https://wordpress.stackexchange.com/users/86864",
"pm_score": 0,
"selected": false,
"text": "<p>You can use here rawurlencode() function. First pass \"?&mkwid=smWfvaLGf_dm\" this url into the function then you will get \"%3F%26mkwid%3DsmWfvaLGf_dm\" encoded value.</p>\n\n<p>Now go on the functions.php and put this code there (But this code will run on every call of you site)</p>\n\n<pre><code>//for accessing current url\n$accessUrl = get_site_url() .$_SERVER['REQUEST_URI'];\n\n$pos = strpos($accessUrl, \"%\");\nif ($pos !== false) \n{\n $accessString = rawurldecode($accessUrl);\n wp_redirect($accessString);\n exit();\n}\n</code></pre>\n\n<p>I feel this will help you.\nThanks</p>\n"
},
{
"answer_id": 216565,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p>Here's the <em>why</em> part:</p>\n\n<p><a href=\"https://github.com/WordPress/WordPress/blob/72c6f7f86f133a0d5ec669526eeb29ca024c0c19/wp-includes/canonical.php#L358-L359\" rel=\"nofollow\">This part</a> of the <code>redirect_canonical()</code> is removing the leading <code>&</code> in the <em>redirect query</em> part:</p>\n\n<pre><code>// tack on any additional query vars\n$redirect['query'] = preg_replace( '#^\\??&*?#', '', $redirect['query'] );\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>example.tld/?&a=1&b=2&c=3 \n</code></pre>\n\n<p>is redirected to </p>\n\n<pre><code>example.tld/?a=1&b=2&c=3 \n</code></pre>\n\n<p>If you must have the leading <code>&</code> you might try to adjust it through the <code>redirect_canonical</code> filter:</p>\n\n<pre><code>/**\n * Filter the canonical redirect URL.\n *\n * Returning false to this filter will cancel the redirect.\n *\n * @since 2.3.0\n *\n * @param string $redirect_url The redirect URL.\n * @param string $requested_url The requested URL.\n */\n$redirect_url = apply_filters( 'redirect_canonical', $redirect_url, $requested_url );\n</code></pre>\n"
}
] |
2016/02/03
|
[
"https://wordpress.stackexchange.com/questions/216573",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85362/"
] |
This is more of a 'Is it possible question" I have a home page which has a full width header and a transparent Navbar, when you scroll this Navbar changes to white. On all my other pages I want this Navbar to start white and stay white as you scroll.
At the moment Im using jQuery to make the Navbar turn white which works fine of course. But does anyone know how I can achieve what I have described?
Any Answers/Suggestions appreciated and welcome!
|
Here's the *why* part:
[This part](https://github.com/WordPress/WordPress/blob/72c6f7f86f133a0d5ec669526eeb29ca024c0c19/wp-includes/canonical.php#L358-L359) of the `redirect_canonical()` is removing the leading `&` in the *redirect query* part:
```
// tack on any additional query vars
$redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] );
```
Example:
```
example.tld/?&a=1&b=2&c=3
```
is redirected to
```
example.tld/?a=1&b=2&c=3
```
If you must have the leading `&` you might try to adjust it through the `redirect_canonical` filter:
```
/**
* Filter the canonical redirect URL.
*
* Returning false to this filter will cancel the redirect.
*
* @since 2.3.0
*
* @param string $redirect_url The redirect URL.
* @param string $requested_url The requested URL.
*/
$redirect_url = apply_filters( 'redirect_canonical', $redirect_url, $requested_url );
```
|
216,595 |
<p>I use events manager pro plugin to show an eventslist. These event-list is showing their thumbnail image in the new (wordpress 4.4) wordpress image size "medium_large" (width 768px). I need an image size of 600x255px which is cropped from the center.</p>
<p>How can i update these image size in my functions.php?</p>
|
[
{
"answer_id": 216597,
"author": "denis.stoyanov",
"author_id": 76287,
"author_profile": "https://wordpress.stackexchange.com/users/76287",
"pm_score": 1,
"selected": false,
"text": "<p>You can call <code>add_image_size()</code> again to update the existing image size. Assuming it is called <code>medium_large</code> (Events Manager Pro is a paid plugin so not very much people have it) you can do something like:</p>\n\n<pre><code><?php\nfunction update_medium_large_size_wpse216595() {\n add_image_size( 'medium_large', 600, 255, array( 'center', 'top' ) );\n}\nadd_action( 'init', 'update_medium_large_size_wpse216595', 11 );\n</code></pre>\n\n<p>Then you will need to <a href=\"https://wordpress.org/plugins/regenerate-thumbnails/\" rel=\"nofollow noreferrer\">regenerate the thumbnails</a>. Although I am not 100% sure that <code>init</code> is the right hook for the job.</p>\n\n<p><strong>p.s.</strong> You can check <a href=\"https://wordpress.stackexchange.com/questions/74934/remove-or-update-add-image-size\">this</a> if you are using a child theme.</p>\n\n<p><strong>p.s.</strong> 2. I am not sure that I understand the center cropping correctly. You many need to <a href=\"https://developer.wordpress.org/reference/functions/add_image_size/\" rel=\"nofollow noreferrer\">play with it a bit</a>. <code>array( 'center', 'top' )</code> will crop the picture in the center ('trimming' the right and left part).</p>\n"
},
{
"answer_id": 216671,
"author": "public9nf",
"author_id": 81609,
"author_profile": "https://wordpress.stackexchange.com/users/81609",
"pm_score": 0,
"selected": false,
"text": "<p>I tried to update the image size with:</p>\n\n<pre><code>add_image_size( 'medium_large', 600, 255, array( 'center', 'top' ) );\n</code></pre>\n\n<p>But when i update the image size with height, width and crop, wordpress is just using the \"large\" image-size. When i just use add_image_size with the width argument:</p>\n\n<pre><code>add_image_size('medium_large', 600, '', true);\n</code></pre>\n\n<p>The image size gets updatet to 600px. Any idea what the problem could be?</p>\n"
},
{
"answer_id": 274401,
"author": "Ajay Tank",
"author_id": 115567,
"author_profile": "https://wordpress.stackexchange.com/users/115567",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to get image to specific size, first you must add image size</p>\n\n<pre><code>add_image_size( 'medium_large', 600, 255, array( 'center', 'top' ) );\n</code></pre>\n\n<p>You have already upload image before add image size code, You must be regenerate image. You can use <a href=\"https://wordpress.org/plugins/regenerate-thumbnails/\" rel=\"nofollow noreferrer\">Regenerate Thumbnails</a> plugin. </p>\n"
},
{
"answer_id": 329156,
"author": "kanlukasz",
"author_id": 133615,
"author_profile": "https://wordpress.stackexchange.com/users/133615",
"pm_score": 1,
"selected": false,
"text": "<p>According to what has been written in the documentation about responsive images in WP:</p>\n<p><em><a href=\"https://make.wordpress.org/core/2015/11/10/responsive-images-in-wordpress-4-4/\" rel=\"nofollow noreferrer\">https://make.wordpress.org/core/2015/11/10/responsive-images-in-wordpress-4-4/</a></em></p>\n<p>you should use <code>update_option</code> (<a href=\"https://developer.wordpress.org/reference/functions/update_option/\" rel=\"nofollow noreferrer\">doc here</a>) to change size <strong>medium_large</strong> images</p>\n<p>For example:</p>\n<p><code>update_option('medium_large_size_w',444)</code></p>\n<p><code>update_option('medium_large_size_h',444)</code></p>\n"
}
] |
2016/02/03
|
[
"https://wordpress.stackexchange.com/questions/216595",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81609/"
] |
I use events manager pro plugin to show an eventslist. These event-list is showing their thumbnail image in the new (wordpress 4.4) wordpress image size "medium\_large" (width 768px). I need an image size of 600x255px which is cropped from the center.
How can i update these image size in my functions.php?
|
You can call `add_image_size()` again to update the existing image size. Assuming it is called `medium_large` (Events Manager Pro is a paid plugin so not very much people have it) you can do something like:
```
<?php
function update_medium_large_size_wpse216595() {
add_image_size( 'medium_large', 600, 255, array( 'center', 'top' ) );
}
add_action( 'init', 'update_medium_large_size_wpse216595', 11 );
```
Then you will need to [regenerate the thumbnails](https://wordpress.org/plugins/regenerate-thumbnails/). Although I am not 100% sure that `init` is the right hook for the job.
**p.s.** You can check [this](https://wordpress.stackexchange.com/questions/74934/remove-or-update-add-image-size) if you are using a child theme.
**p.s.** 2. I am not sure that I understand the center cropping correctly. You many need to [play with it a bit](https://developer.wordpress.org/reference/functions/add_image_size/). `array( 'center', 'top' )` will crop the picture in the center ('trimming' the right and left part).
|
216,681 |
<p>I have been searching google but I am really confused. I am trying to display the terms of the taxonomy assigned to the post. I am using <code>the_terms($post->ID, 'locations');</code>. The custom taxonomy is hierarchical.</p>
<p>Example: 3 terms assigned to post: <code>USA(parent) > FL(direct child of "USA") > Miami(direct child of "FL")</code>. What I get: <code>FL, Miami, USA</code> which means the terms are being displayed in alphabetical order. I want them to be displayed like: <code>Miami, FL, USA</code>. Can this be achieved? I would also like to remove the anchors from the terms and <code>strip_tags(the_terms($post->ID, 'locations'))</code> doesn't seem to work.</p>
<p>While searching google some people use <code>get_terms()</code> some other <code>get_the_terms</code> and others <code>the_terms</code> which is what I use and seems to work - output the terms. What is the difference between those functions? Am I using the right one?</p>
|
[
{
"answer_id": 216687,
"author": "Optimum Creative",
"author_id": 71641,
"author_profile": "https://wordpress.stackexchange.com/users/71641",
"pm_score": -1,
"selected": false,
"text": "<p>You should use </p>\n\n<pre><code>get_the_terms(int|object $post, string $taxonomy)\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_the_terms/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_the_terms/</a>\n or</p>\n\n<pre><code>get_terms(array|string $args = array(), array $deprecated = '')\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_terms/</a> </p>\n\n<p>because</p>\n\n<pre><code>the_terms()\n</code></pre>\n\n<p>echo/prints the results</p>\n\n<p>and</p>\n\n<pre><code> get_the_terms() //or\n get_terms() \n</code></pre>\n\n<p>only get value and save it to variable or memory.</p>\n\n<p>A possible example is</p>\n\n<pre><code>foreach($posts as $post){\n $term= get_the_terms($post->ID, 'category' );\n echo 'Category: '.$term;\n}\n</code></pre>\n\n<p>You may need to use another loop to handle $terms if there or more than 1 object in any case.</p>\n"
},
{
"answer_id": 216689,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>To answer your first question </p>\n\n<blockquote>\n <p>What is the difference between those functions</p>\n</blockquote>\n\n<ul>\n<li><p><a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow\"><code>get_terms()</code></a> returns an array of terms objects that belongs to a specific taxonomy</p></li>\n<li><p><a href=\"https://developer.wordpress.org/reference/functions/get_the_terms/\" rel=\"nofollow\"><code>get_the_terms()</code></a> returns an array of terms belonging to a post</p></li>\n<li><p><a href=\"https://developer.wordpress.org/reference/functions/the_terms/\" rel=\"nofollow\"><code>the_terms()</code></a> displays an HTML formatting string of term names belonging to a post</p></li>\n</ul>\n\n<p>Because you need your terms not hyperlinked and ordered according to parent, I believe <a href=\"https://developer.wordpress.org/reference/functions/wp_get_object_terms/\" rel=\"nofollow\"><code>wp_get_object_terms()</code></a> will be a better option here. <code>wp_get_object_terms()</code> also returns an array of terms belonging to a post, but is more flexible. You do pay for this flexibility though as you make an extra db call per post.</p>\n\n<p>With this all in mind, you can try the following: (<em>All code is untested</em>)</p>\n\n<pre><code>$args = [\n 'orderby' => 'parent', \n 'order' => 'DESC' \n];\n$terms = wp_get_object_terms( $post->ID, 'locations', $args );\n$names = wp_list_pluck( $terms, 'name' );\n$output = implode( ', ', $names );\necho $output;\n</code></pre>\n"
}
] |
2016/02/04
|
[
"https://wordpress.stackexchange.com/questions/216681",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/15801/"
] |
I have been searching google but I am really confused. I am trying to display the terms of the taxonomy assigned to the post. I am using `the_terms($post->ID, 'locations');`. The custom taxonomy is hierarchical.
Example: 3 terms assigned to post: `USA(parent) > FL(direct child of "USA") > Miami(direct child of "FL")`. What I get: `FL, Miami, USA` which means the terms are being displayed in alphabetical order. I want them to be displayed like: `Miami, FL, USA`. Can this be achieved? I would also like to remove the anchors from the terms and `strip_tags(the_terms($post->ID, 'locations'))` doesn't seem to work.
While searching google some people use `get_terms()` some other `get_the_terms` and others `the_terms` which is what I use and seems to work - output the terms. What is the difference between those functions? Am I using the right one?
|
To answer your first question
>
> What is the difference between those functions
>
>
>
* [`get_terms()`](https://developer.wordpress.org/reference/functions/get_terms/) returns an array of terms objects that belongs to a specific taxonomy
* [`get_the_terms()`](https://developer.wordpress.org/reference/functions/get_the_terms/) returns an array of terms belonging to a post
* [`the_terms()`](https://developer.wordpress.org/reference/functions/the_terms/) displays an HTML formatting string of term names belonging to a post
Because you need your terms not hyperlinked and ordered according to parent, I believe [`wp_get_object_terms()`](https://developer.wordpress.org/reference/functions/wp_get_object_terms/) will be a better option here. `wp_get_object_terms()` also returns an array of terms belonging to a post, but is more flexible. You do pay for this flexibility though as you make an extra db call per post.
With this all in mind, you can try the following: (*All code is untested*)
```
$args = [
'orderby' => 'parent',
'order' => 'DESC'
];
$terms = wp_get_object_terms( $post->ID, 'locations', $args );
$names = wp_list_pluck( $terms, 'name' );
$output = implode( ', ', $names );
echo $output;
```
|
216,694 |
<p>So today I've decided to implement a search form onto my site that obviously returns a result when the user searches for it, but I've run into a little problem.</p>
<p><strong>My Problem</strong></p>
<p>When the user searches for a result without inputting anything into the search form for some reason it returns 5 Pages whereas I would like it to return a Message that says something along the lines of 'Search Fields was empty - Search Again'.</p>
<p>How would I go about making this happen? I've inserted my code below that controls my <code>searchform</code> button and the content it outputs when search.</p>
<p><strong>Code Controlling the Search Form</strong></p>
<p><strong>searchform.php</strong> This is the Search form which is where the user inputs what they want (I have a feeling I need to enter some code here to check if it is empty)</p>
<pre><code><form role="search" method="get" id="searchform" action="<?php echo home_url('/'); ?>">
<div>
<label class="screen-reader-text" for="s">Search: </label>
<input type="text" value="" name="s" id="s" placeholder="<?php the_search_query(); ?>" />
<input type="submit" id="searchsubmit" value="Search" />
</div>
</form>
</code></pre>
<p><strong>search.php</strong> This is showing the user what they have searched for and the getting the template <code>content-search</code> to show the Page name(s).</p>
<pre><code><div class="search-result">
<div class="container">
<div class="row">
<div class="search">
<?php if (have_posts()) : ?>
<h2>Search Result For: <?php the_search_query(); ?></h2>
<div class="light-separator small center"></div>
<?php
while (have_posts()) : the_post();
get_template_part('content-search', get_post_format());
endwhile;
else :
echo '
<div class="no-content">
<h3>Ooopss, looks like nothing matches your result.</h3>
</div>';
endif;
?>
<div class="search-form"><?php get_search_form(); ?></div>
</div>
</div>
</div>
</div>
</code></pre>
<p><strong>content-search.php</strong> - This displays the Pages Title and the Permalink for the Page</p>
<pre><code><div class="searchs">
<h4>Pages - <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
</div>
</code></pre>
|
[
{
"answer_id": 216722,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": false,
"text": "<p>I'm not sure if this is an intended bug or just a bug that was never anticipated, but it is definitely a flaw in design. </p>\n\n<p>This behavior exists in the following cases that I took note of before</p>\n\n<ul>\n<li><p>Setting an empty array to <code>post__in</code> returns all posts</p></li>\n<li><p>Passing an invalid term to a <code>tax_query</code> or using the <code>name</code> field with a name with special characters or more than one word removes the join clause from the SQL query which also results in all posts being returned. I did an <a href=\"https://wordpress.stackexchange.com/q/180651/31545\">answer regarding this issue</a></p></li>\n</ul>\n\n<p>So what happens here is that when we pass a valid string to our search function, the <code>WHERE</code> clause is altered to include our search terms. Normally this is how the <code>WHERE</code> clause looks when we enter a search term called <code>search</code></p>\n\n<pre><code>AND (((wp_posts.post_title LIKE \\'%search%\\') \nOR (wp_posts.post_content LIKE \\'%search%\\'))) \nAND wp_posts.post_type IN (\\'post\\', \\'page\\', \\'attachment\\', \\'information\\', \\'event_type\\', \\'cameras\\') \nAND (wp_posts.post_status = \\'publish\\' \nOR wp_posts.post_author = 1 \nAND wp_posts.post_status = \\'private\\')\n</code></pre>\n\n<p>When we pass an empty string, the search clause is removed from the <code>WHERE</code> clause which causes all posts to be returned. This is how the <code>WHERE</code> clause looks like when we pass an empty string</p>\n\n<pre><code>AND wp_posts.post_type IN (\\'post\\', \\'page\\', \\'attachment\\', \\'information\\', \\'event_type\\', \\'cameras\\') \nAND (wp_posts.post_status = \\'publish\\' OR wp_posts.post_author = 1 \nAND wp_posts.post_status = \\'private\\')\n</code></pre>\n\n<p>This is the section in <code>WP_Query</code> which is responsible for this</p>\n\n<pre><code>if ( ! empty( $q['s'] ) ) {\n $search = $this->parse_search( $q );\n}\n</code></pre>\n\n<p>The easiest way to get out of this is to return a 404 whenever we pass an empty string as search terms. For this we need to check if we have a valid search string or not, and then set a 404 according to that. You can try the following</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $q )\n{\n if( !is_admin() // Only target the front end\n && $q->is_main_query() // Only target the main query\n && $q->is_search() // Only target the search page\n ) {\n // Get the search terms\n $search_terms = $q->get( 's' );\n\n // Set a 404 if s is empty\n if ( !$search_terms ) {\n add_action( 'wp', function () use ( $q )\n {\n $q->set_404();\n status_header(404);\n nocache_headers();\n });\n }\n }\n});\n</code></pre>\n"
},
{
"answer_id": 216734,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<p>Just an alternative to the informative answer by @PieterGoosen.</p>\n\n<p>After Pieter posted this part:</p>\n\n<pre><code>if ( ! empty( $q['s'] ) ) {\n $search = $this->parse_search( $q );\n}\n</code></pre>\n\n<p>it came to mind that it might be possible to re-parse the search query, within the <code>posts_search</code> filter, for empty search string. But the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/parse_search/\" rel=\"noreferrer\"><code>parse_search()</code></a> method is protected and even if we could access it, the empty search would just give us:</p>\n\n<pre><code>AND (((wp_posts.post_title LIKE '%%') OR (wp_posts.post_content LIKE '%%'))) \n</code></pre>\n\n<p>and that would just search for everything. So that path wasn't fruitful ;-)</p>\n\n<p>In WordPress 4.5 it has changed to </p>\n\n<pre><code>if ( strlen( $q['s'] ) ) {\n $search = $this->parse_search( $q );\n}\n</code></pre>\n\n<p>Instead we could try to halt the main query, in the case of an empty search:</p>\n\n<pre><code>/**\n * Halt the main query in the case of an empty search \n */\nadd_filter( 'posts_search', function( $search, \\WP_Query $q )\n{\n if( ! is_admin() && empty( $search ) && $q->is_search() && $q->is_main_query() )\n $search .=\" AND 0=1 \";\n\n return $search;\n}, 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 359024,
"author": "Thomas Buegel",
"author_id": 182996,
"author_profile": "https://wordpress.stackexchange.com/users/182996",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to exclude search strings with shorter than a defined length and the empty search string too, you can use this altered function of birgire's solution. In this example empty and search phrases with only one letter give no results:</p>\n\n<pre><code> add_filter( 'posts_search', function( $search, \\WP_Query $q )\n {\n $sphrase = get_search_query();\n $slen = strlen($sphrase);\n $minlen = 2;\n if( ! is_admin() && $slen < $minlen && $q->is_search() && $q->is_main_query() ){\n $search .=\" AND 0=1 \";\n }\n return $search;\n }, 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 370843,
"author": "Wordpress Dev-lover",
"author_id": 191328,
"author_profile": "https://wordpress.stackexchange.com/users/191328",
"pm_score": 0,
"selected": false,
"text": "<p>To exclude search strings with shorter than a defined length and the empty search string too, you can use this altered function of birgire's solution:</p>\n<pre><code>add_filter( 'posts_search', function( $search, \\WP_Query $q )\n{\n $sphrase = get_search_query();\n $slen = strlen($sphrase);\n $minlen = 2;\n if( ! is_admin() && $slen < $minlen && $q->is_search() && $q->is_main_query() ){\n $search .=" AND 0=1 ";\n }\n return $search;\n}, 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 381321,
"author": "Chad Reitsma",
"author_id": 160601,
"author_profile": "https://wordpress.stackexchange.com/users/160601",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using the standard search.php file, it's a lot easier to just add logic in the if ( have_posts()) conditional...</p>\n<pre><code>if ( have_posts() && $_GET['s'] != '' )\n</code></pre>\n<p>That way if the search parameter is empty, it doesn't perform the content loop.</p>\n"
},
{
"answer_id": 408706,
"author": "jfaMan",
"author_id": 225026,
"author_profile": "https://wordpress.stackexchange.com/users/225026",
"pm_score": 0,
"selected": false,
"text": "<p>Adding onto Chad's answer, you can also make it prevent searches with just spaces, which for me was also returning results:</p>\n<pre><code>if ( have_posts() && $_GET['s'] !== '' && !ctype_space($_GET['s']) )\n</code></pre>\n"
}
] |
2016/02/04
|
[
"https://wordpress.stackexchange.com/questions/216694",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85776/"
] |
So today I've decided to implement a search form onto my site that obviously returns a result when the user searches for it, but I've run into a little problem.
**My Problem**
When the user searches for a result without inputting anything into the search form for some reason it returns 5 Pages whereas I would like it to return a Message that says something along the lines of 'Search Fields was empty - Search Again'.
How would I go about making this happen? I've inserted my code below that controls my `searchform` button and the content it outputs when search.
**Code Controlling the Search Form**
**searchform.php** This is the Search form which is where the user inputs what they want (I have a feeling I need to enter some code here to check if it is empty)
```
<form role="search" method="get" id="searchform" action="<?php echo home_url('/'); ?>">
<div>
<label class="screen-reader-text" for="s">Search: </label>
<input type="text" value="" name="s" id="s" placeholder="<?php the_search_query(); ?>" />
<input type="submit" id="searchsubmit" value="Search" />
</div>
</form>
```
**search.php** This is showing the user what they have searched for and the getting the template `content-search` to show the Page name(s).
```
<div class="search-result">
<div class="container">
<div class="row">
<div class="search">
<?php if (have_posts()) : ?>
<h2>Search Result For: <?php the_search_query(); ?></h2>
<div class="light-separator small center"></div>
<?php
while (have_posts()) : the_post();
get_template_part('content-search', get_post_format());
endwhile;
else :
echo '
<div class="no-content">
<h3>Ooopss, looks like nothing matches your result.</h3>
</div>';
endif;
?>
<div class="search-form"><?php get_search_form(); ?></div>
</div>
</div>
</div>
</div>
```
**content-search.php** - This displays the Pages Title and the Permalink for the Page
```
<div class="searchs">
<h4>Pages - <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
</div>
```
|
Just an alternative to the informative answer by @PieterGoosen.
After Pieter posted this part:
```
if ( ! empty( $q['s'] ) ) {
$search = $this->parse_search( $q );
}
```
it came to mind that it might be possible to re-parse the search query, within the `posts_search` filter, for empty search string. But the [`parse_search()`](https://developer.wordpress.org/reference/classes/wp_query/parse_search/) method is protected and even if we could access it, the empty search would just give us:
```
AND (((wp_posts.post_title LIKE '%%') OR (wp_posts.post_content LIKE '%%')))
```
and that would just search for everything. So that path wasn't fruitful ;-)
In WordPress 4.5 it has changed to
```
if ( strlen( $q['s'] ) ) {
$search = $this->parse_search( $q );
}
```
Instead we could try to halt the main query, in the case of an empty search:
```
/**
* Halt the main query in the case of an empty search
*/
add_filter( 'posts_search', function( $search, \WP_Query $q )
{
if( ! is_admin() && empty( $search ) && $q->is_search() && $q->is_main_query() )
$search .=" AND 0=1 ";
return $search;
}, 10, 2 );
```
|
216,741 |
<p>I wonder if anyone can help me with this little complex query with ACF.</p>
<p>I have the following so far which should display: </p>
<ul>
<li><p>Pages, </p></li>
<li><p>News Articles, </p></li>
<li><p>About Articles and </p></li>
<li><p>Involved Articles.</p></li>
<li><p>Show: only 4.</p></li>
</ul>
<p>Only display if: the ACF/Meta Key ‘home_page’ is selected ‘yes’</p>
<p>AND</p>
<p>Order by the numeric value of the ACF/Meta Key ‘home_order’ i/e 1,2,3 first, second, third etc</p>
<pre><code> $args = array(
'post_type' => array( 'page', 'news-articles', 'about-articles’,'involved-articles' ),
'showposts' => 4,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'home_page',
'value' => 'yes',
'compare' => 'IN',
),
array(
'orderby' => 'meta_value_num',
'meta_key' => 'home_order’,
),
),
);
</code></pre>
<p>I think something is going wrong with the ‘compare’ and ‘relation'</p>
|
[
{
"answer_id": 216761,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>You should really read the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow noreferrer\">documentation on <code>meta_query</code>'s</a></p>\n<p>Here is what is allowed in a <code>meta_query</code></p>\n<ul>\n<li><p>key (string) - Custom field key.</p>\n</li>\n<li><p>value (string|array) - Custom field value. It can be an array only when compare is <code>'IN'</code>, <code>'NOT IN'</code>, <code>'BETWEEN'</code>, or <code>'NOT BETWEEN'</code>. You don't have to specify a value when using the <code>'EXISTS'</code> or <code>'NOT EXISTS'</code> comparisons in WordPress 3.9 and up.</p>\n<p>(Note: Due to bug #23268, value is required for <code>NOT EXISTS</code> comparisons to work correctly prior to 3.9. You must supply some string for the value parameter. An empty string or <code>NULL</code> will NOT work. However, any other string will do the trick and will NOT show up in your SQL when using <code>NOT EXISTS</code>. Need inspiration? How about 'bug #23268'.)</p>\n</li>\n<li><p>compare (string) - Operator to test. Possible values are <code>'='</code>, <code>'!='</code>, <code>'>'</code>, <code>'>='</code>, <code>'<'</code>, <code>'<='</code>, <code>'LIKE'</code>, <code>'NOT LIKE'</code>, <code>'IN'</code>, <code>'NOT IN'</code>, <code>'BETWEEN'</code>, <code>'NOT BETWEEN'</code>, <code>'EXISTS'</code> and <code>'NOT EXISTS'</code>. Default value is <code>'='</code>.</p>\n</li>\n<li><p>type (string) - Custom field type. Possible values are <code>'NUMERIC'</code>, <code>'BINARY'</code>, <code>'CHAR'</code>, <code>'DATE'</code>, <code>'DATETIME'</code>, <code>'DECIMAL'</code>, <code>'SIGNED'</code>, <code>'TIME'</code>, <code>'UNSIGNED'</code>. Default value is <code>'CHAR'</code>.</p>\n</li>\n</ul>\n<p>Your ordering needs to take place outside your <code>meta_query</code>. You can try the following</p>\n<pre><code>$args = [\n 'post_type' => ['page', 'news-articles', 'about-articles', 'involved-articles'],\n 'posts_per_page' => 4,\n 'meta_key' => 'home_order',\n 'orderby' => 'meta_value_num',\n 'meta_query' => [\n [\n 'key' => 'home_page',\n 'value' => 'yes',\n ]\n ],\n];\n</code></pre>\n<p>Additional notes:</p>\n<ul>\n<li><p>As from PHP 5.4 you can use short array syntax, ie, you can use <code>[]</code> instead of <code>array()</code>. If you still running any version before PHP 5.6, you should seriously consider upgrading.</p>\n</li>\n<li><p><code>showposts</code> is dropped in favor of <code>posts_per_page</code>, so rather use <code>posts_per_page</code></p>\n</li>\n</ul>\n"
},
{
"answer_id": 216784,
"author": "user4630",
"author_id": 4630,
"author_profile": "https://wordpress.stackexchange.com/users/4630",
"pm_score": -1,
"selected": false,
"text": "<pre><code>$args = array(\n 'posts_per_page' => 4,\n 'post_type' => array( 'page', 'news-articles', 'about-gorilla','involved' ),\n 'orderby' => 'meta_value_num',\n 'meta_key' => 'home_order',\n 'order' => 'ASC',\n 'meta_query' => array(\n array(\n 'key' => 'home_page',\n 'value' => 'yes',\n 'compare' => '=',\n ),\n ),\n );\n</code></pre>\n"
}
] |
2016/02/04
|
[
"https://wordpress.stackexchange.com/questions/216741",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/4630/"
] |
I wonder if anyone can help me with this little complex query with ACF.
I have the following so far which should display:
* Pages,
* News Articles,
* About Articles and
* Involved Articles.
* Show: only 4.
Only display if: the ACF/Meta Key ‘home\_page’ is selected ‘yes’
AND
Order by the numeric value of the ACF/Meta Key ‘home\_order’ i/e 1,2,3 first, second, third etc
```
$args = array(
'post_type' => array( 'page', 'news-articles', 'about-articles’,'involved-articles' ),
'showposts' => 4,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'home_page',
'value' => 'yes',
'compare' => 'IN',
),
array(
'orderby' => 'meta_value_num',
'meta_key' => 'home_order’,
),
),
);
```
I think something is going wrong with the ‘compare’ and ‘relation'
|
You should really read the [documentation on `meta_query`'s](https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters)
Here is what is allowed in a `meta_query`
* key (string) - Custom field key.
* value (string|array) - Custom field value. It can be an array only when compare is `'IN'`, `'NOT IN'`, `'BETWEEN'`, or `'NOT BETWEEN'`. You don't have to specify a value when using the `'EXISTS'` or `'NOT EXISTS'` comparisons in WordPress 3.9 and up.
(Note: Due to bug #23268, value is required for `NOT EXISTS` comparisons to work correctly prior to 3.9. You must supply some string for the value parameter. An empty string or `NULL` will NOT work. However, any other string will do the trick and will NOT show up in your SQL when using `NOT EXISTS`. Need inspiration? How about 'bug #23268'.)
* compare (string) - Operator to test. Possible values are `'='`, `'!='`, `'>'`, `'>='`, `'<'`, `'<='`, `'LIKE'`, `'NOT LIKE'`, `'IN'`, `'NOT IN'`, `'BETWEEN'`, `'NOT BETWEEN'`, `'EXISTS'` and `'NOT EXISTS'`. Default value is `'='`.
* type (string) - Custom field type. Possible values are `'NUMERIC'`, `'BINARY'`, `'CHAR'`, `'DATE'`, `'DATETIME'`, `'DECIMAL'`, `'SIGNED'`, `'TIME'`, `'UNSIGNED'`. Default value is `'CHAR'`.
Your ordering needs to take place outside your `meta_query`. You can try the following
```
$args = [
'post_type' => ['page', 'news-articles', 'about-articles', 'involved-articles'],
'posts_per_page' => 4,
'meta_key' => 'home_order',
'orderby' => 'meta_value_num',
'meta_query' => [
[
'key' => 'home_page',
'value' => 'yes',
]
],
];
```
Additional notes:
* As from PHP 5.4 you can use short array syntax, ie, you can use `[]` instead of `array()`. If you still running any version before PHP 5.6, you should seriously consider upgrading.
* `showposts` is dropped in favor of `posts_per_page`, so rather use `posts_per_page`
|
216,743 |
<p>I'm trying to find all users that are logged in to WordPress. </p>
<p>I can detect myself, but I want to be able to find the other admins. Here is my current code to find myself.</p>
<pre><code>if (user_can( $current_user, 'administrator' )) {
echo '<div class="admin"> User currently logged in "'
. $current_user->user_login . '"</div>';
}
</code></pre>
|
[
{
"answer_id": 216751,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Wordpress do not have a true concept of \"logged in\". Although the labels all around use the term, in the code the closest you get is something that might be called \"authenticated users\". The difference is that the authenticated user might be one that has his browser closed and therefor he is not \"logged in\".</p>\n\n<p>To do what you want you will first need to define what does it mean for you to be \"logged in\" and implement some logic to detect it. For example you might use ajax to update that a user is still connected and remove the user from the \"logged in\" list if it didn't update for lets say 5 minutes.</p>\n\n<p>It is not trivial but not very complex to implement.</p>\n"
},
{
"answer_id": 216767,
"author": "LukeWarm",
"author_id": 87806,
"author_profile": "https://wordpress.stackexchange.com/users/87806",
"pm_score": 0,
"selected": false,
"text": "<p>On init set a transient for, say, 5 min that keeps updating as long as the current user (in this case, any admin) is poking around. Dump a list of those active transients from a shortcode into a page. That should do it. </p>\n"
},
{
"answer_id": 216794,
"author": "flomei",
"author_id": 65455,
"author_profile": "https://wordpress.stackexchange.com/users/65455",
"pm_score": 0,
"selected": false,
"text": "<p>Adding to what Mark Kaplun said, you could probably have a look at <a href=\"https://developer.wordpress.org/reference/classes/wp_user_meta_session_tokens/\" rel=\"nofollow\">User Meta Sessions Tokens</a>. They can tell you, if there is an active session for a specific user. But that does not mean, that the user is active on the site and doing something, just that he logged in successfully.</p>\n\n<p>Anyway, don´t trust anyone that tells you to use <code>is_user_logged_in()</code>! That´s not how that function works.</p>\n"
}
] |
2016/02/04
|
[
"https://wordpress.stackexchange.com/questions/216743",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88140/"
] |
I'm trying to find all users that are logged in to WordPress.
I can detect myself, but I want to be able to find the other admins. Here is my current code to find myself.
```
if (user_can( $current_user, 'administrator' )) {
echo '<div class="admin"> User currently logged in "'
. $current_user->user_login . '"</div>';
}
```
|
Wordpress do not have a true concept of "logged in". Although the labels all around use the term, in the code the closest you get is something that might be called "authenticated users". The difference is that the authenticated user might be one that has his browser closed and therefor he is not "logged in".
To do what you want you will first need to define what does it mean for you to be "logged in" and implement some logic to detect it. For example you might use ajax to update that a user is still connected and remove the user from the "logged in" list if it didn't update for lets say 5 minutes.
It is not trivial but not very complex to implement.
|
216,752 |
<p>The WP site I am creating requires creating diff posts for diff categories.</p>
<p>What I like is that if someone chose to post under category A, i have a bunch of pre-set settings (tags, banner image etc) in that post.</p>
<p>If the person posts under category B, there will be a diff set of settings?</p>
<p>Does anyone know if there's a plugin that can do this? I can hack the php code if i have to but i prefer a plugin where it is easier to manage.</p>
<p>The closest plugin I can find is ACF.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 216754,
"author": "Rituparna sonowal",
"author_id": 71232,
"author_profile": "https://wordpress.stackexchange.com/users/71232",
"pm_score": -1,
"selected": false,
"text": "<p>As per your description ACF will be enough and easiest way to do that. Create custom fields group based on your requirements (per category) then restrict them to specific post category with ACF rules.</p>\n\n<p>Hope it will help you!</p>\n"
},
{
"answer_id": 217318,
"author": "BigRedDog",
"author_id": 65697,
"author_profile": "https://wordpress.stackexchange.com/users/65697",
"pm_score": 0,
"selected": false,
"text": "<p>After scouring on the net and bouncing around, I figured out how to fix my problem.</p>\n\n<ol>\n<li>Install ACF and create your own post types.</li>\n<li><p>In Functions.php, add the following codes to default category for that post type.</p>\n\n<pre><code>function add_pastorheart_category_automatically($post_ID) {\n global $wpdb;\n if(!wp_is_post_revision($post_ID)) {\n $pastorheartcat = array (15);\n wp_set_object_terms( $post_ID, $pastorheartcat, 'category');\n\n }\n}\nadd_action('publish_pastors-heart', 'add_pastorheart_category_automatically');\n</code></pre></li>\n<li><p>Also add this function to include the post type in the category. </p>\n\n<pre><code>function namespace_add_custom_types( $query ) {\n if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {\n $query->set( 'post_type', array(\n 'post', 'nav_menu_item', 'pastors-heart'\n ));\n return $query;\n }\n}\nadd_filter( 'pre_get_posts', 'namespace_add_custom_types' );\n</code></pre></li>\n<li><p>For default thumbnail image, I put this code in the content-excerpt.php. Instead of checking for post types, I check for category.</p></li>\n</ol>\n\n<p>It might not be the most elegant way of doing it. But it works for me.</p>\n"
}
] |
2016/02/05
|
[
"https://wordpress.stackexchange.com/questions/216752",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65697/"
] |
The WP site I am creating requires creating diff posts for diff categories.
What I like is that if someone chose to post under category A, i have a bunch of pre-set settings (tags, banner image etc) in that post.
If the person posts under category B, there will be a diff set of settings?
Does anyone know if there's a plugin that can do this? I can hack the php code if i have to but i prefer a plugin where it is easier to manage.
The closest plugin I can find is ACF.
Thanks!
|
After scouring on the net and bouncing around, I figured out how to fix my problem.
1. Install ACF and create your own post types.
2. In Functions.php, add the following codes to default category for that post type.
```
function add_pastorheart_category_automatically($post_ID) {
global $wpdb;
if(!wp_is_post_revision($post_ID)) {
$pastorheartcat = array (15);
wp_set_object_terms( $post_ID, $pastorheartcat, 'category');
}
}
add_action('publish_pastors-heart', 'add_pastorheart_category_automatically');
```
3. Also add this function to include the post type in the category.
```
function namespace_add_custom_types( $query ) {
if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set( 'post_type', array(
'post', 'nav_menu_item', 'pastors-heart'
));
return $query;
}
}
add_filter( 'pre_get_posts', 'namespace_add_custom_types' );
```
4. For default thumbnail image, I put this code in the content-excerpt.php. Instead of checking for post types, I check for category.
It might not be the most elegant way of doing it. But it works for me.
|
216,756 |
<p>I wanted to use the site URL change in the general settings page of the admin panel to remove the trailing /wp from my privately hosted wordpress site. After submitting these changes, I am locked out by errors every time I attempt to log in--from a log-in page where the CSS is gone. I have attempted to update the config.php file with </p>
<pre><code>define('WP_HOME','example.com');
define('WP_SITEURL','example.com');
</code></pre>
<p>But this did nothing. The Relocation function also did nothing, and I have no functions.php file. According to the codex, that leaves me only with editing the database directly. How can I undo the damage and achieve my desired result of landing on my wordpress site with just example.com instead of example.com/wp?</p>
|
[
{
"answer_id": 216758,
"author": "techsharez.com",
"author_id": 88148,
"author_profile": "https://wordpress.stackexchange.com/users/88148",
"pm_score": 0,
"selected": false,
"text": "<p>Have you checked this one? If no just check this post. Hope this will help you to solve your problem <a href=\"http://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow\">http://codex.wordpress.org/Changing_The_Site_URL</a></p>\n"
},
{
"answer_id": 216783,
"author": "Jeffrey Ponsen",
"author_id": 80453,
"author_profile": "https://wordpress.stackexchange.com/users/80453",
"pm_score": 0,
"selected": false,
"text": "<p>The best way to move an WordPress website to another URL is by exporting, replacing and importing the database. Try doing this by using PHPMyAdmin or another database management tool. For phpmyadmin just select your database and click on export.</p>\n\n<p>After downloading the export of your database, open it in a simple texteditor (Notepad++, Textwrangler) and fire up the search and replace screen. Replace <code>//example.com/wp</code> with <code>//example.com</code>.</p>\n\n<p>Just to be sure, search the file again for <code>//example.com/wp</code>, no results should be found. Then save the file.</p>\n\n<p>Now open up phpmyadmin again, and create another export as an backup. Then delete all tables, and import your replaced SQL file. Now your database should be updated, and the rules in wp-config.php are not needed anymore.</p>\n\n<p>Your site should be working on the other domain now.</p>\n\n<p>Don't forget to re-save your permalinks afterwards. </p>\n"
},
{
"answer_id": 261019,
"author": "Akankha Ahmed",
"author_id": 116024,
"author_profile": "https://wordpress.stackexchange.com/users/116024",
"pm_score": 1,
"selected": false,
"text": "<p>Follow the steps below:</p>\n\n<ol>\n<li>Move your file to new folder </li>\n<li>Go to your phpmyadmin desire database</li>\n<li>Find wp-option change the site url only here to your desire url</li>\n<li>Then login to back-end go to general and change both url here to new url</li>\n<li>Hit save</li>\n</ol>\n\n<p>It will work perfectly if you want to move WordPress into new location. </p>\n"
},
{
"answer_id": 268751,
"author": "Sam",
"author_id": 115586,
"author_profile": "https://wordpress.stackexchange.com/users/115586",
"pm_score": 0,
"selected": false,
"text": "<p>Check you .htaccess file</p>\n\n<pre><code># BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n</code></pre>\n\n<p>You can always delete your .htaccess and then once logged back in go to permalink and change it from what you have to another option save page then select your desired permalink and save again this should force wordpress to recreate .htaccess</p>\n"
},
{
"answer_id": 314619,
"author": "Leonardo Soares",
"author_id": 144989,
"author_profile": "https://wordpress.stackexchange.com/users/144989",
"pm_score": 2,
"selected": false,
"text": "<p>Best way</p>\n\n<blockquote>\n <p>If you have access to the site via FTP, then this method will help you quickly get a site back up and running, if you changed those values incorrectly.</p>\n \n <ol>\n <li><p>FTP to the site, and get a copy of the active theme's functions.php file. You're going to edit it in a simple text editor and upload it back to the site.</p></li>\n <li><p>Add these two lines to the file, immediately after the initial <code><?php</code> line:</p></li>\n </ol>\n \n <p></p>\n\n<pre><code>update_option('siteurl', 'http://example.com');\nupdate_option('home', 'http://example.com');\n</code></pre>\n \n <p>Use your own URL instead of example.com, obviously.</p>\n \n <ol start=\"3\">\n <li><p>Upload the file back to your site, in the same location. FileZilla offers a handy \"edit file\" function to do all of the above rapidly; if you can use that, do so.</p></li>\n <li><p>Load the login or admin page a couple of times. The site should come back up.\n Important! Do not leave those lines in the functions.php file. Remove them after the site is up and running again.</p></li>\n </ol>\n \n <p>Note: If your theme doesn't have a functions.php file create a new one with a text editor. Add the php tags and the two lines using your own URL instead of example.com:.</p>\n\n<pre><code><?php\nupdate_option('siteurl','http://example.com');\nupdate_option('home','http://example.com');\n</code></pre>\n \n <p>Upload that to your theme directory. Remove the lines or the remove the file after the site is up and running again. </p>\n</blockquote>\n\n<p><a href=\"https://wordpress.org/support/article/changing-the-site-url/\" rel=\"nofollow noreferrer\">Source: WordPress.org - Changing The Site URL</a></p>\n"
}
] |
2016/02/05
|
[
"https://wordpress.stackexchange.com/questions/216756",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88146/"
] |
I wanted to use the site URL change in the general settings page of the admin panel to remove the trailing /wp from my privately hosted wordpress site. After submitting these changes, I am locked out by errors every time I attempt to log in--from a log-in page where the CSS is gone. I have attempted to update the config.php file with
```
define('WP_HOME','example.com');
define('WP_SITEURL','example.com');
```
But this did nothing. The Relocation function also did nothing, and I have no functions.php file. According to the codex, that leaves me only with editing the database directly. How can I undo the damage and achieve my desired result of landing on my wordpress site with just example.com instead of example.com/wp?
|
Best way
>
> If you have access to the site via FTP, then this method will help you quickly get a site back up and running, if you changed those values incorrectly.
>
>
> 1. FTP to the site, and get a copy of the active theme's functions.php file. You're going to edit it in a simple text editor and upload it back to the site.
> 2. Add these two lines to the file, immediately after the initial `<?php` line:
>
>
>
>
> ```
> update_option('siteurl', 'http://example.com');
> update_option('home', 'http://example.com');
>
> ```
>
> Use your own URL instead of example.com, obviously.
>
>
> 3. Upload the file back to your site, in the same location. FileZilla offers a handy "edit file" function to do all of the above rapidly; if you can use that, do so.
> 4. Load the login or admin page a couple of times. The site should come back up.
> Important! Do not leave those lines in the functions.php file. Remove them after the site is up and running again.
>
>
> Note: If your theme doesn't have a functions.php file create a new one with a text editor. Add the php tags and the two lines using your own URL instead of example.com:.
>
>
>
> ```
> <?php
> update_option('siteurl','http://example.com');
> update_option('home','http://example.com');
>
> ```
>
> Upload that to your theme directory. Remove the lines or the remove the file after the site is up and running again.
>
>
>
[Source: WordPress.org - Changing The Site URL](https://wordpress.org/support/article/changing-the-site-url/)
|
216,759 |
<p>I want to create and set a custom taxonomy site-wide based on the users location so that I can call <code>taxonomy_exists( $country )</code> to determine if a user is located in a specific country.</p>
<p>I've installed the GeoIP plugin that lets me get the user's country code from <code>$userInfo->country->isoCode</code>.</p>
<p>To register the custom taxonomy, I have the following function. But what should 'object type' be if I want to apply the taxonomy to the entire site?</p>
<pre><code>add_action( 'init', 'create_country_taxonomy' );
function create_country_taxonomy() {
register_taxonomy(
'country',
$object_type, // Set to what?
array(
'label' => __( 'Country' ),
'rewrite' => array( 'slug' => 'location' ),
)
);
}
</code></pre>
<p>Finally, how can I set the user's country taxonomy to <code>$userInfo->country->isoCode</code>?</p>
|
[
{
"answer_id": 216758,
"author": "techsharez.com",
"author_id": 88148,
"author_profile": "https://wordpress.stackexchange.com/users/88148",
"pm_score": 0,
"selected": false,
"text": "<p>Have you checked this one? If no just check this post. Hope this will help you to solve your problem <a href=\"http://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow\">http://codex.wordpress.org/Changing_The_Site_URL</a></p>\n"
},
{
"answer_id": 216783,
"author": "Jeffrey Ponsen",
"author_id": 80453,
"author_profile": "https://wordpress.stackexchange.com/users/80453",
"pm_score": 0,
"selected": false,
"text": "<p>The best way to move an WordPress website to another URL is by exporting, replacing and importing the database. Try doing this by using PHPMyAdmin or another database management tool. For phpmyadmin just select your database and click on export.</p>\n\n<p>After downloading the export of your database, open it in a simple texteditor (Notepad++, Textwrangler) and fire up the search and replace screen. Replace <code>//example.com/wp</code> with <code>//example.com</code>.</p>\n\n<p>Just to be sure, search the file again for <code>//example.com/wp</code>, no results should be found. Then save the file.</p>\n\n<p>Now open up phpmyadmin again, and create another export as an backup. Then delete all tables, and import your replaced SQL file. Now your database should be updated, and the rules in wp-config.php are not needed anymore.</p>\n\n<p>Your site should be working on the other domain now.</p>\n\n<p>Don't forget to re-save your permalinks afterwards. </p>\n"
},
{
"answer_id": 261019,
"author": "Akankha Ahmed",
"author_id": 116024,
"author_profile": "https://wordpress.stackexchange.com/users/116024",
"pm_score": 1,
"selected": false,
"text": "<p>Follow the steps below:</p>\n\n<ol>\n<li>Move your file to new folder </li>\n<li>Go to your phpmyadmin desire database</li>\n<li>Find wp-option change the site url only here to your desire url</li>\n<li>Then login to back-end go to general and change both url here to new url</li>\n<li>Hit save</li>\n</ol>\n\n<p>It will work perfectly if you want to move WordPress into new location. </p>\n"
},
{
"answer_id": 268751,
"author": "Sam",
"author_id": 115586,
"author_profile": "https://wordpress.stackexchange.com/users/115586",
"pm_score": 0,
"selected": false,
"text": "<p>Check you .htaccess file</p>\n\n<pre><code># BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n</code></pre>\n\n<p>You can always delete your .htaccess and then once logged back in go to permalink and change it from what you have to another option save page then select your desired permalink and save again this should force wordpress to recreate .htaccess</p>\n"
},
{
"answer_id": 314619,
"author": "Leonardo Soares",
"author_id": 144989,
"author_profile": "https://wordpress.stackexchange.com/users/144989",
"pm_score": 2,
"selected": false,
"text": "<p>Best way</p>\n\n<blockquote>\n <p>If you have access to the site via FTP, then this method will help you quickly get a site back up and running, if you changed those values incorrectly.</p>\n \n <ol>\n <li><p>FTP to the site, and get a copy of the active theme's functions.php file. You're going to edit it in a simple text editor and upload it back to the site.</p></li>\n <li><p>Add these two lines to the file, immediately after the initial <code><?php</code> line:</p></li>\n </ol>\n \n <p></p>\n\n<pre><code>update_option('siteurl', 'http://example.com');\nupdate_option('home', 'http://example.com');\n</code></pre>\n \n <p>Use your own URL instead of example.com, obviously.</p>\n \n <ol start=\"3\">\n <li><p>Upload the file back to your site, in the same location. FileZilla offers a handy \"edit file\" function to do all of the above rapidly; if you can use that, do so.</p></li>\n <li><p>Load the login or admin page a couple of times. The site should come back up.\n Important! Do not leave those lines in the functions.php file. Remove them after the site is up and running again.</p></li>\n </ol>\n \n <p>Note: If your theme doesn't have a functions.php file create a new one with a text editor. Add the php tags and the two lines using your own URL instead of example.com:.</p>\n\n<pre><code><?php\nupdate_option('siteurl','http://example.com');\nupdate_option('home','http://example.com');\n</code></pre>\n \n <p>Upload that to your theme directory. Remove the lines or the remove the file after the site is up and running again. </p>\n</blockquote>\n\n<p><a href=\"https://wordpress.org/support/article/changing-the-site-url/\" rel=\"nofollow noreferrer\">Source: WordPress.org - Changing The Site URL</a></p>\n"
}
] |
2016/02/05
|
[
"https://wordpress.stackexchange.com/questions/216759",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81557/"
] |
I want to create and set a custom taxonomy site-wide based on the users location so that I can call `taxonomy_exists( $country )` to determine if a user is located in a specific country.
I've installed the GeoIP plugin that lets me get the user's country code from `$userInfo->country->isoCode`.
To register the custom taxonomy, I have the following function. But what should 'object type' be if I want to apply the taxonomy to the entire site?
```
add_action( 'init', 'create_country_taxonomy' );
function create_country_taxonomy() {
register_taxonomy(
'country',
$object_type, // Set to what?
array(
'label' => __( 'Country' ),
'rewrite' => array( 'slug' => 'location' ),
)
);
}
```
Finally, how can I set the user's country taxonomy to `$userInfo->country->isoCode`?
|
Best way
>
> If you have access to the site via FTP, then this method will help you quickly get a site back up and running, if you changed those values incorrectly.
>
>
> 1. FTP to the site, and get a copy of the active theme's functions.php file. You're going to edit it in a simple text editor and upload it back to the site.
> 2. Add these two lines to the file, immediately after the initial `<?php` line:
>
>
>
>
> ```
> update_option('siteurl', 'http://example.com');
> update_option('home', 'http://example.com');
>
> ```
>
> Use your own URL instead of example.com, obviously.
>
>
> 3. Upload the file back to your site, in the same location. FileZilla offers a handy "edit file" function to do all of the above rapidly; if you can use that, do so.
> 4. Load the login or admin page a couple of times. The site should come back up.
> Important! Do not leave those lines in the functions.php file. Remove them after the site is up and running again.
>
>
> Note: If your theme doesn't have a functions.php file create a new one with a text editor. Add the php tags and the two lines using your own URL instead of example.com:.
>
>
>
> ```
> <?php
> update_option('siteurl','http://example.com');
> update_option('home','http://example.com');
>
> ```
>
> Upload that to your theme directory. Remove the lines or the remove the file after the site is up and running again.
>
>
>
[Source: WordPress.org - Changing The Site URL](https://wordpress.org/support/article/changing-the-site-url/)
|
216,765 |
<p>I have a custom ACF field set on all posts, called <code>event_date</code>, I would like to grab all posts within a given <code>category</code>, but have posts that have <code>event_date</code> defined put first in DESC order of <code>event_date</code>. The <code>args</code> I'm using for <code>query_posts</code> are as follows:</p>
<pre><code>$args = array(
'posts_per_page' => -1,
'cat' => $category_id,
'meta_query' => array(
array(
'key' => 'event_date',
'value' => date("Ymd", time()),
'compare' => $type == 'upcoming' ? '>=' : '<'
)
),
'orderby' => 'meta_value',
'order' => 'DESC',
'meta_key' => 'event_date'
);
</code></pre>
<p>But the problem I'm facing is that the ACF field was created for post types, after all posts have been created, so many of these posts do not have <code>event_date</code> even defined for the meta_key (which omits these posts from the query automatically when using <code>query_posts($args)</code>. There are too many posts to go through all posts and save them all manually, would take forever.</p>
<p>Basically, if the <code>meta_key</code> for any post does not have <code>event_date</code> than I need to use the <code>date</code> of the actual post itself (when it was published) to order by. I need all posts with <code>event_date</code> shown first in DESC order of <code>event_date</code>, than all posts that don't have <code>event_date</code> defined, need to be shown after that using the published date of the post in DESC order. How can I do this? Preferably, all in 1 <code>query_posts</code> call?</p>
<p>Thanks :)</p>
|
[
{
"answer_id": 216766,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 3,
"selected": true,
"text": "<p>You can get both with an <code>OR</code> <code>meta_query</code> that also checks if the key does not exist:</p>\n\n<pre><code>'meta_query' => array(\n 'relation' => 'OR',\n array(\n 'key' => 'event_date',\n 'compare' => 'NOT EXISTS',\n ),\n array(\n 'key' => 'event_date',\n 'value' => date(\"Ymd\", time()),\n 'compare' => '>',\n ),\n),\n'orderby' => array(\n 'meta_value_num' => 'DESC',\n 'date' => 'ASC',\n),\n</code></pre>\n"
},
{
"answer_id": 216773,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 0,
"selected": false,
"text": "<p>The most probable route I will take with this is to run a script that would add the desired custom field to the posts which does not have the custom field assigned.</p>\n\n<p>You can try the following: (<strong><em>NOTE:</strong> This is untested</em>)</p>\n\n<pre><code>add_action( 'wp', function ()\n{\n $args = [\n 'post_type' => 'post', // Set according to needs\n 'posts_per_page' => -1, // Set to execute smaller chucks per page load if necessary\n 'suppress_filters' => true,\n 'fields' => 'ids',\n 'meta_query' => [\n [\n 'key' => 'event_date',\n 'compare' => 'NOT EXISTS'\n ]\n ]\n ];\n $q = get_posts( $args );\n foreach ( $q as $post_id ) {\n add_post_meta( \n $post_id, // Post ID\n 'event_date', // Custom field name\n get_the_date( 'Ymd', $post_id )\n ); \n }\n});\n</code></pre>\n\n<p>You can run this by simply loading any page after which you can remove it. If you set smaller chuncks, like <code>posts_per_page=100</code>, you will refresh the page until all posts are done. Note that this is quite an expensive resource intensve script which might lead to a time out fatal error, so if you have a huge amount of posts you can run smaller amount of posts per page load.</p>\n\n<p>After this you can run your query as normal as per question. Just a tip though, never ever use <code>query_posts</code>, use <code>WP_Query</code> to run your custom query (<em>or use <code>get_posts</code> alternatively</em>)</p>\n"
}
] |
2016/02/05
|
[
"https://wordpress.stackexchange.com/questions/216765",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54603/"
] |
I have a custom ACF field set on all posts, called `event_date`, I would like to grab all posts within a given `category`, but have posts that have `event_date` defined put first in DESC order of `event_date`. The `args` I'm using for `query_posts` are as follows:
```
$args = array(
'posts_per_page' => -1,
'cat' => $category_id,
'meta_query' => array(
array(
'key' => 'event_date',
'value' => date("Ymd", time()),
'compare' => $type == 'upcoming' ? '>=' : '<'
)
),
'orderby' => 'meta_value',
'order' => 'DESC',
'meta_key' => 'event_date'
);
```
But the problem I'm facing is that the ACF field was created for post types, after all posts have been created, so many of these posts do not have `event_date` even defined for the meta\_key (which omits these posts from the query automatically when using `query_posts($args)`. There are too many posts to go through all posts and save them all manually, would take forever.
Basically, if the `meta_key` for any post does not have `event_date` than I need to use the `date` of the actual post itself (when it was published) to order by. I need all posts with `event_date` shown first in DESC order of `event_date`, than all posts that don't have `event_date` defined, need to be shown after that using the published date of the post in DESC order. How can I do this? Preferably, all in 1 `query_posts` call?
Thanks :)
|
You can get both with an `OR` `meta_query` that also checks if the key does not exist:
```
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'event_date',
'compare' => 'NOT EXISTS',
),
array(
'key' => 'event_date',
'value' => date("Ymd", time()),
'compare' => '>',
),
),
'orderby' => array(
'meta_value_num' => 'DESC',
'date' => 'ASC',
),
```
|
216,793 |
<p>I would like to find out which page template is in use as I only want to enqueue some javascript if the page is using a certain template. Is this possible?</p>
|
[
{
"answer_id": 216795,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": false,
"text": "<p>I'm not sure if this is for front end or back end, so I'm going to handle both.</p>\n\n<h2>BACK END</h2>\n\n<p>You can make use of <code>get_current_screen()</code> or the <code>$pagenow</code> global. Here are two examples which you can add in a plugin or in your <code>functions.php</code> to check the relevant info on an admin page</p>\n\n<pre><code>add_action( 'current_screen', function ( $current_screen )\n{\n ?><pre><?php var_dump($current_screen); ?></pre><?php \n\n});\n</code></pre>\n\n<p>and</p>\n\n<pre><code>add_action( 'admin_head', function ()\n{\n global $pagenow;\n\n ?><pre><?php var_dump($pagenow); ?></pre><?php \n\n});\n</code></pre>\n\n<p>Once you have the name of the specific admin page, you can do the following</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', function ( $hook ) \n{\n if ( 'some-page.php' === $hook ) {\n // Add your scripts\n }\n});\n</code></pre>\n\n<h2>FRONT END</h2>\n\n<p>As birgire pointed out, if you need to know this on front end, you can simply test this with <code>is_page_template( 'some-template.php' )</code></p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', function ()\n{\n if ( is_page_template( 'some-template.php' ) ) {\n // Enqueue your script\n }\n});\n</code></pre>\n"
},
{
"answer_id": 216796,
"author": "Andrew Welch",
"author_id": 17862,
"author_profile": "https://wordpress.stackexchange.com/users/17862",
"pm_score": 1,
"selected": false,
"text": "<p>I did this in the end:</p>\n\n<pre><code> global $post;\n\n if ( isset( $post ) ) {\n $pagetemplate = get_post_meta( $post->ID, '_wp_page_template', true );\n if ( !empty( $pagetemplate ) ) {\n if ( $pagetemplate == 'page-landing_child.php' ) {\n\n //do something\n }\n }\n\n }\n</code></pre>\n"
},
{
"answer_id": 357054,
"author": "admcfajn",
"author_id": 123674,
"author_profile": "https://wordpress.stackexchange.com/users/123674",
"pm_score": 1,
"selected": false,
"text": "<p>I was fumbling with this one, but then i remembered we have access to the post-id via a get-param in wp-admin</p>\n\n<pre><code>add_action('admin_head', 'my_admin_head');\nfunction my_admin_head() {\n if ( ! empty( $_GET['post'] ) ) {\n $post_id = sanitize_key( $_GET['post'] );\n $template_name = get_post_meta( $post_id, '_wp_page_template', true );\n echo $template_name; exit;\n }\n}\n</code></pre>\n"
}
] |
2016/02/05
|
[
"https://wordpress.stackexchange.com/questions/216793",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17862/"
] |
I would like to find out which page template is in use as I only want to enqueue some javascript if the page is using a certain template. Is this possible?
|
I'm not sure if this is for front end or back end, so I'm going to handle both.
BACK END
--------
You can make use of `get_current_screen()` or the `$pagenow` global. Here are two examples which you can add in a plugin or in your `functions.php` to check the relevant info on an admin page
```
add_action( 'current_screen', function ( $current_screen )
{
?><pre><?php var_dump($current_screen); ?></pre><?php
});
```
and
```
add_action( 'admin_head', function ()
{
global $pagenow;
?><pre><?php var_dump($pagenow); ?></pre><?php
});
```
Once you have the name of the specific admin page, you can do the following
```
add_action( 'admin_enqueue_scripts', function ( $hook )
{
if ( 'some-page.php' === $hook ) {
// Add your scripts
}
});
```
FRONT END
---------
As birgire pointed out, if you need to know this on front end, you can simply test this with `is_page_template( 'some-template.php' )`
```
add_action( 'wp_enqueue_scripts', function ()
{
if ( is_page_template( 'some-template.php' ) ) {
// Enqueue your script
}
});
```
|
216,802 |
<p>I have created a custom post type to pull through the date, title, thumbnail and content, some of the posts have images and <code>the_content()</code> is pulling through those images and I don't know how to stop it from doing this, Could someone help me with this issue?</p>
<p>My code:</p>
<pre><code><?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="post">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="col-md-5">
<?php echo the_post_thumbnail(); ?>
</div>
<div class="col-md-6">
<h2><?php the_title(); ?></h2>
<h4><?php the_date('jS F Y');?></h4>
<?php the_content();?>
<a href="<?php echo the_permalink(); ?>">Read More</a>
</div>
</div>
</div>
</div>
</div>
<?php endwhile; else:?>
<h2>There are no blog posts</h2>
<?php endif; ?>
</code></pre>
|
[
{
"answer_id": 216808,
"author": "Tom Withers",
"author_id": 85362,
"author_profile": "https://wordpress.stackexchange.com/users/85362",
"pm_score": -1,
"selected": false,
"text": "<p>I figured out how to do this,</p>\n\n<p>Instead of using <code>the_content();</code> Im now using <code>the_excerpt();</code> and Im just changing the amount of characters it brings through!</p>\n"
},
{
"answer_id": 216811,
"author": "mukto90",
"author_id": 57944,
"author_profile": "https://wordpress.stackexchange.com/users/57944",
"pm_score": 0,
"selected": false,
"text": "<p>Add this code to your <code>functions.php</code></p>\n\n<pre><code>function mdc_remove_img($content) {\n $content = preg_replace(\"/<img[^>]+\\>/i\", \"\", $content); \n return $content;\n}\n\nadd_filter( 'the_content', 'mdc_remove_img' );\n</code></pre>\n"
}
] |
2016/02/05
|
[
"https://wordpress.stackexchange.com/questions/216802",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85362/"
] |
I have created a custom post type to pull through the date, title, thumbnail and content, some of the posts have images and `the_content()` is pulling through those images and I don't know how to stop it from doing this, Could someone help me with this issue?
My code:
```
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="post">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="col-md-5">
<?php echo the_post_thumbnail(); ?>
</div>
<div class="col-md-6">
<h2><?php the_title(); ?></h2>
<h4><?php the_date('jS F Y');?></h4>
<?php the_content();?>
<a href="<?php echo the_permalink(); ?>">Read More</a>
</div>
</div>
</div>
</div>
</div>
<?php endwhile; else:?>
<h2>There are no blog posts</h2>
<?php endif; ?>
```
|
Add this code to your `functions.php`
```
function mdc_remove_img($content) {
$content = preg_replace("/<img[^>]+\>/i", "", $content);
return $content;
}
add_filter( 'the_content', 'mdc_remove_img' );
```
|
216,821 |
<p>I have several custom post types (created through CPT UI plugin). I want to display posts from these post types on my page, for example "News". I've created a page and inserted in it shortcode <code>[show_posts post_type="novyny"].</code> I've got a plugin that processes this shortcode</p>
<pre><code>function foo($args){
$post_type = $args['post_type'];
$custom_post_type = new WP_Query(
array(
'post_type' => $post_type,
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 4
)
);
if( $custom_post_type->have_posts() ) :
while( $custom_post_type->have_posts() ): $custom_post_type->the_post(); ?>
<h1><a href="<?php the_permalink(); ?>"><?php the_title() ?></a></h1>
<p> <?php the_modified_date(); echo ", "; the_modified_time() ?></p>
<p> <?php the_excerpt() ?></p>
<?php endwhile;
the_posts_pagination();
endif;
wp_reset_postdata();
}
add_shortcode('show_posts', 'foo');
</code></pre>
<p>Posts are displayed, but pagination blog doesn't appear at the page even if there is more than 4 posts to display. What's wrong? </p>
|
[
{
"answer_id": 216830,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 3,
"selected": true,
"text": "<p><code>the_posts_pagination</code> uses <code>global</code> query and global query does not have pagination. So it is the correct behavior of WordPress.</p>\n\n<p>To overcome from this problem assign custom query to global query then after looping again restore the global query.</p>\n\n<pre><code>function foo($args){\n $post_type = $args['post_type'];\n global $wp_query;\n $original_query = $wp_query;\n $custom_post_type = new WP_Query(\n array(\n 'post_type' => $post_type,\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'posts_per_page' => 4\n )\n );\n\n $wp_query = $custom_post_type;\n\n if( $custom_post_type->have_posts() ) :\n while( $custom_post_type->have_posts() ): $custom_post_type->the_post(); ?>\n <h1><a href=\"<?php the_permalink(); ?>\"><?php the_title() ?></a></h1>\n <p> <?php the_modified_date(); echo \", \"; the_modified_time() ?></p>\n <p> <?php the_excerpt() ?></p>\n <?php endwhile;\n the_posts_pagination();\n endif;\n wp_reset_postdata();\n\n $wp_query = $original_query;\n}\n</code></pre>\n"
},
{
"answer_id": 216876,
"author": "Vlodko",
"author_id": 86327,
"author_profile": "https://wordpress.stackexchange.com/users/86327",
"pm_score": 2,
"selected": false,
"text": "<p>Thank you all, guys. I've solved it this way: </p>\n\n<ul>\n<li>added <code>$paged</code> variable: <code>$paged = ( get_query_var('page') ) ? get_query_var('page') : 1;</code> (for <strong>main page</strong> you should use <code>get_query_var('page')</code>, for <strong>other pages</strong> - <code>$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;</code> )</li>\n<li>And added a new argument for WP_Query: <code>'paged' => $paged</code></li>\n</ul>\n\n<p>My code now:</p>\n\n<pre><code>function foo($args){\n $post_type = $args['post_type'];\n\n /* Added $paged variable */\n $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;\n\n global $wp_query;\n $original_query = $wp_query;\n\n $query_args = array(\n 'post_type' => $post_type,\n 'posts_per_page' => 3,\n\n /* And added a new argument for WP_Query */\n 'paged' => $paged\n );\n\n $custom_post_type = new WP_Query( $query_args );\n $wp_query = $custom_post_type;\n\n if ( $custom_post_type->have_posts() ) :\n while ( $custom_post_type->have_posts() ) :\n $custom_post_type->the_post(); ?>\n <h1><a href=\"<?php the_permalink(); ?>\"><?php the_title() ?></a></h1>\n <p> <?php the_modified_date(); echo \", \"; the_modified_time() ?></p>\n <p> <?php the_excerpt() ?></p>\n <?php endwhile;\n the_posts_pagination();\n endif;\n\n wp_reset_postdata();\n $wp_query = $original_query;\n}\n</code></pre>\n"
},
{
"answer_id": 397639,
"author": "Roman Berdnikov",
"author_id": 214370,
"author_profile": "https://wordpress.stackexchange.com/users/214370",
"pm_score": 0,
"selected": false,
"text": "<p>A small update to Vlad's last post. You need to change</p>\n<pre><code>$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;\n</code></pre>\n<p>to</p>\n<pre><code>$paged = ( $original_query->query['paged'] ) ? $original_query->query['paged'] : 1;\n</code></pre>\n"
}
] |
2016/02/05
|
[
"https://wordpress.stackexchange.com/questions/216821",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86327/"
] |
I have several custom post types (created through CPT UI plugin). I want to display posts from these post types on my page, for example "News". I've created a page and inserted in it shortcode `[show_posts post_type="novyny"].` I've got a plugin that processes this shortcode
```
function foo($args){
$post_type = $args['post_type'];
$custom_post_type = new WP_Query(
array(
'post_type' => $post_type,
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 4
)
);
if( $custom_post_type->have_posts() ) :
while( $custom_post_type->have_posts() ): $custom_post_type->the_post(); ?>
<h1><a href="<?php the_permalink(); ?>"><?php the_title() ?></a></h1>
<p> <?php the_modified_date(); echo ", "; the_modified_time() ?></p>
<p> <?php the_excerpt() ?></p>
<?php endwhile;
the_posts_pagination();
endif;
wp_reset_postdata();
}
add_shortcode('show_posts', 'foo');
```
Posts are displayed, but pagination blog doesn't appear at the page even if there is more than 4 posts to display. What's wrong?
|
`the_posts_pagination` uses `global` query and global query does not have pagination. So it is the correct behavior of WordPress.
To overcome from this problem assign custom query to global query then after looping again restore the global query.
```
function foo($args){
$post_type = $args['post_type'];
global $wp_query;
$original_query = $wp_query;
$custom_post_type = new WP_Query(
array(
'post_type' => $post_type,
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 4
)
);
$wp_query = $custom_post_type;
if( $custom_post_type->have_posts() ) :
while( $custom_post_type->have_posts() ): $custom_post_type->the_post(); ?>
<h1><a href="<?php the_permalink(); ?>"><?php the_title() ?></a></h1>
<p> <?php the_modified_date(); echo ", "; the_modified_time() ?></p>
<p> <?php the_excerpt() ?></p>
<?php endwhile;
the_posts_pagination();
endif;
wp_reset_postdata();
$wp_query = $original_query;
}
```
|
216,859 |
<p>I'm trying to delete a variable stored in local storage when user logs out of WordPress, none of the two code blocks below work for me, both have been tested in my functions.php file one at a time. </p>
<pre><code> function del_local_reload_var() {
$str = <<<HD
<script>
localStorage.removeItem("justOnce");
</script>
HD;
echo $str;
}
add_action('wp_logout', 'del_local_reload_var');
</code></pre>
<p>Second method:</p>
<pre><code> function del_local_reload_var() {
echo '<script type="text/javascript">';
echo 'localStorage.removeItem( "justOnce" )';
echo '</script>';
}
add_action('wp_logout', 'del_local_reload_var');
</code></pre>
|
[
{
"answer_id": 216865,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p><code>wp_logout</code> is being triggered server side when the user is logging out, but the fact that it is being triggered do not indicate that there is a browser on the other side that actually triggered it. For example a user might log out via Ajax and then the JS code will not be evaluated.</p>\n\n<p>In any case, it is much better to define a logged out user as one that do not have the authentication cookie. You can do something like</p>\n\n<pre><code>if (value in local storage) {\n if (wordpress cookie exists)\n remove value from local storage\n}\n</code></pre>\n\n<p>Anyway, if you want to be able to control client data from the server you should use cookies instead of local storage.</p>\n"
},
{
"answer_id": 410802,
"author": "Sean Michaud",
"author_id": 43348,
"author_profile": "https://wordpress.stackexchange.com/users/43348",
"pm_score": 0,
"selected": false,
"text": "<p>Since WordPress redirects you to the login page, add the JavaScript to a code block on there. Something like:</p>\n<pre><code>function my_remove_local_storage() {\n if ( isset( $_GET['loggedout'] ) && $_GET['loggedout'] == 'true' ) { ?>\n <script>localStorage.removeItem("justOnce");</script>\n <?php }\n}\nadd_action( 'login_form', 'my_remove_local_storage' );\n \n</code></pre>\n"
}
] |
2016/02/06
|
[
"https://wordpress.stackexchange.com/questions/216859",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76433/"
] |
I'm trying to delete a variable stored in local storage when user logs out of WordPress, none of the two code blocks below work for me, both have been tested in my functions.php file one at a time.
```
function del_local_reload_var() {
$str = <<<HD
<script>
localStorage.removeItem("justOnce");
</script>
HD;
echo $str;
}
add_action('wp_logout', 'del_local_reload_var');
```
Second method:
```
function del_local_reload_var() {
echo '<script type="text/javascript">';
echo 'localStorage.removeItem( "justOnce" )';
echo '</script>';
}
add_action('wp_logout', 'del_local_reload_var');
```
|
`wp_logout` is being triggered server side when the user is logging out, but the fact that it is being triggered do not indicate that there is a browser on the other side that actually triggered it. For example a user might log out via Ajax and then the JS code will not be evaluated.
In any case, it is much better to define a logged out user as one that do not have the authentication cookie. You can do something like
```
if (value in local storage) {
if (wordpress cookie exists)
remove value from local storage
}
```
Anyway, if you want to be able to control client data from the server you should use cookies instead of local storage.
|
216,879 |
<p>I am struggling a lot this time working on including a JavaScript files in plugin folder.</p>
<p>I am trying to create a plugin by transferring widget files from themes directory.
I copied the widget file, but that widget file was depending on a JavaScript file so I created a /js/ folder in plugin directory. where this files is hosted "jquery.repeatable.js"</p>
<p>I used this code, but it doesn't seems to include the js file - </p>
<pre><code>function Zumper_widget_enqueue_script()
{
wp_enqueue_script( 'my_custom_script', plugin_dir_url( __FILE__ ) . 'js/jquery.repeatable.js' );
}
add_action('admin_enqueue_scripts', 'Zumper_widget_enqueue_script');
</code></pre>
<p>I searched this on forum-
<a href="https://stackoverflow.com/questions/31489615/call-a-js-file-from-a-plugin-directory">https://stackoverflow.com/questions/31489615/call-a-js-file-from-a-plugin-directory</a></p>
<p>But still this was not helpful.</p>
<p>I am re-summarizing my question.
In my plugin directory there is a js file under this folder - /js/</p>
<p>I wish to include it what is the correct process, do I need to register something also?</p>
<p>Is there something wrong with this portion - <code>'admin_enqueue_scripts'</code>?</p>
|
[
{
"answer_id": 216880,
"author": "mukto90",
"author_id": 57944,
"author_profile": "https://wordpress.stackexchange.com/users/57944",
"pm_score": 1,
"selected": false,
"text": "<p><strong>UPDATED:</strong></p>\n\n<p>Use this code instead</p>\n\n<pre><code>function Zumper_widget_enqueue_script()\n{ \n wp_enqueue_script( 'my_custom_script', plugin_dir_url( __FILE__ ) . 'js/jquery.repeatable.js', array('jquery'), '1.0.0', false );\n}\nadd_action('admin_enqueue_scripts', 'Zumper_widget_enqueue_script');\n</code></pre>\n\n<p>3rd parameter is to declare dependency and 4th one is to define version.</p>\n\n<p>Set 5rd parameter of <code>wp_enqueue_script()</code> to <code>true</code>. That's meaning, this file will be loaded in footer.</p>\n"
},
{
"answer_id": 216881,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 6,
"selected": true,
"text": "<p>Your code seems correct, but it will load the script only in admin area beacuse you are enqueuing the script in <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts\" rel=\"noreferrer\"><code>admin_enqueue_scripts</code> action</a>.</p>\n\n<p>To load the script in frontend, use <code>wp_enqueue_scripts</code> action (which is not the same that <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"noreferrer\"><code>wp_enqueue_script()</code> function</a>):</p>\n\n<pre><code>function Zumper_widget_enqueue_script() { \n wp_enqueue_script( 'my_custom_script', plugin_dir_url( __FILE__ ) . 'js/jquery.repeatable.js' );\n}\nadd_action('wp_enqueue_scripts', 'Zumper_widget_enqueue_script');\n</code></pre>\n\n<p>Also, that script seems to depends on jQuery, so you should declare that dependencie or the script can be loaded before jQuery and it won't work. Also, I strongly recommend to declare the version of the scripot. This way, if you update the script to a new version, the browser will donwload it again and discard the copy it may have on cache.</p>\n\n<p>For example, if the version of the script is 1.0:</p>\n\n<pre><code>function Zumper_widget_enqueue_script() { \n wp_enqueue_script( 'my_custom_script', plugin_dir_url( __FILE__ ) . 'js/jquery.repeatable.js', array('jquery'), '1.0' );\n}\nadd_action('wp_enqueue_scripts', 'Zumper_widget_enqueue_script');\n</code></pre>\n\n<p>If you want to load it in admin area:</p>\n\n<pre><code>function Zumper_widget_enqueue_script() { \n wp_enqueue_script( 'my_custom_script', plugin_dir_url( __FILE__ ) . 'js/jquery.repeatable.js', array('jquery'), '1.0' );\n}\nadd_action('admin_enqueue_scripts', 'Zumper_widget_enqueue_script');\n</code></pre>\n"
},
{
"answer_id": 344655,
"author": "Zaheer Abbas",
"author_id": 135489,
"author_profile": "https://wordpress.stackexchange.com/users/135489",
"pm_score": 2,
"selected": false,
"text": "<p>I normally use <a href=\"https://codex.wordpress.org/Function_Reference/plugins_url\" rel=\"nofollow noreferrer\">plugins_url()</a> method to achieve enqueue. </p>\n\n<pre><code>function Zumper_widget_enqueue_script()\n{ \n wp_enqueue_script( 'my_custom_script', plugins_url('js/jquery.repeatable.js', __FILE__ ), '1.0.0', false );\n}\nadd_action('admin_enqueue_scripts', 'Zumper_widget_enqueue_script');\n</code></pre>\n"
}
] |
2016/02/06
|
[
"https://wordpress.stackexchange.com/questions/216879",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105791/"
] |
I am struggling a lot this time working on including a JavaScript files in plugin folder.
I am trying to create a plugin by transferring widget files from themes directory.
I copied the widget file, but that widget file was depending on a JavaScript file so I created a /js/ folder in plugin directory. where this files is hosted "jquery.repeatable.js"
I used this code, but it doesn't seems to include the js file -
```
function Zumper_widget_enqueue_script()
{
wp_enqueue_script( 'my_custom_script', plugin_dir_url( __FILE__ ) . 'js/jquery.repeatable.js' );
}
add_action('admin_enqueue_scripts', 'Zumper_widget_enqueue_script');
```
I searched this on forum-
<https://stackoverflow.com/questions/31489615/call-a-js-file-from-a-plugin-directory>
But still this was not helpful.
I am re-summarizing my question.
In my plugin directory there is a js file under this folder - /js/
I wish to include it what is the correct process, do I need to register something also?
Is there something wrong with this portion - `'admin_enqueue_scripts'`?
|
Your code seems correct, but it will load the script only in admin area beacuse you are enqueuing the script in [`admin_enqueue_scripts` action](https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts).
To load the script in frontend, use `wp_enqueue_scripts` action (which is not the same that [`wp_enqueue_script()` function](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts)):
```
function Zumper_widget_enqueue_script() {
wp_enqueue_script( 'my_custom_script', plugin_dir_url( __FILE__ ) . 'js/jquery.repeatable.js' );
}
add_action('wp_enqueue_scripts', 'Zumper_widget_enqueue_script');
```
Also, that script seems to depends on jQuery, so you should declare that dependencie or the script can be loaded before jQuery and it won't work. Also, I strongly recommend to declare the version of the scripot. This way, if you update the script to a new version, the browser will donwload it again and discard the copy it may have on cache.
For example, if the version of the script is 1.0:
```
function Zumper_widget_enqueue_script() {
wp_enqueue_script( 'my_custom_script', plugin_dir_url( __FILE__ ) . 'js/jquery.repeatable.js', array('jquery'), '1.0' );
}
add_action('wp_enqueue_scripts', 'Zumper_widget_enqueue_script');
```
If you want to load it in admin area:
```
function Zumper_widget_enqueue_script() {
wp_enqueue_script( 'my_custom_script', plugin_dir_url( __FILE__ ) . 'js/jquery.repeatable.js', array('jquery'), '1.0' );
}
add_action('admin_enqueue_scripts', 'Zumper_widget_enqueue_script');
```
|
216,894 |
<p>When I made a Bootstrap carousel in plain HTML it was working just fine, but when I pasted the code into Wordpress the carousel is completely white.</p>
<p><br />
It's not a problem with the path because it will work if I change it from</p>
<pre><code><div class="fill" style="background-image:url("img/image01.png");"></div>
</code></pre>
<p>to </p>
<pre><code><img src="img/image01.png" class="img-responsive" alt="">
</code></pre>
<p>then it works.</p>
<p><br />
I know this seems like a HTML or CSS problem, but I feel like I've exhausted all options that I can think of, leading me to think it's something with Wordpress and Bootstrap not working together. I've tried changing <strong>background-image:url</strong> to just <strong>background:url</strong> but it still comes up with totally white. </p>
<p>I also know that if I try it on another div like:</p>
<pre><code><section id="schedule">
<div class="row" style="background-image: url('img/image01.png'); margin-top: 75px;">
<div class="callout-light text-center" style="margin-bottom: 30px;">
<h1>Header!</h1>
</div>
</div>
</section>
</code></pre>
<p>That it comes up just fine.</p>
<p><br /><br /><br />
Here is the full code:</p>
<pre><code><style>
.fill {
width: 100%;
height: 100%;
background-position: center;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover;
}
</style>
<header id="myCarousel" class="carousel slide">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>
<!-- Wrapper for Slides -->
<div class="carousel-inner">
<div class="item active">
<!-- Set the first background image using inline CSS below. -->
<div class="fill" style="background-image:url('img/image01.png');"></div>
<div class="carousel-caption">
<h2>Caption 1</h2>
</div>
</div>
<div class="item">
<!-- Set the second background image using inline CSS below. -->
<div class="fill" style="background-image:url('img/image02.png');"></div>
<div class="carousel-caption">
<h2>Caption 2</h2>
</div>
</div>
<div class="item">
<!-- Set the third background image using inline CSS below. -->
<div class="fill" style="background-image:url('img/image03.png');"></div>
<div class="carousel-caption">
<h2>Caption 3</h2>
</div>
</div>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#myCarousel" data-slide="prev">
<span class="icon-prev"></span>
</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">
<span class="icon-next"></span>
</a>
</header>
</code></pre>
|
[
{
"answer_id": 232383,
"author": "matt",
"author_id": 98400,
"author_profile": "https://wordpress.stackexchange.com/users/98400",
"pm_score": 0,
"selected": false,
"text": "<pre><code><div class=\"fill\" style=\"background-image:url(\"img/image01.png\");\"></div>\n</code></pre>\n\n<p>Your double quotes within double quotes will stop it from working, you need:</p>\n\n<pre><code><div class=\"fill\" style=\"background-image:url('img/image01.png');\"></div>\n</code></pre>\n"
},
{
"answer_id": 232399,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>You should never use relative urls in wordpress except for css files. If \"pretty permalink\" something that works on one page might break on another. All urls should be absolute. The most you can get with usually is being relative to the protocol, but almost never anything more then that.</p>\n"
},
{
"answer_id": 237276,
"author": "user101738",
"author_id": 101738,
"author_profile": "https://wordpress.stackexchange.com/users/101738",
"pm_score": 2,
"selected": false,
"text": "<p>What if you use:</p>\n\n<pre><code><div class=\"fill\" style=\"background-image: url(<?php \n echo get_stylesheet_directory_uri();?>/img/image01.png);\"></div>\n</code></pre>\n\n<p>You need to tell WordPress in \"a WordPress-way\" where to find the image...\nLook in codex at <a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri\" rel=\"nofollow\">get_stylesheet_directory_uri()</a>.</p>\n"
}
] |
2016/02/06
|
[
"https://wordpress.stackexchange.com/questions/216894",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84013/"
] |
When I made a Bootstrap carousel in plain HTML it was working just fine, but when I pasted the code into Wordpress the carousel is completely white.
It's not a problem with the path because it will work if I change it from
```
<div class="fill" style="background-image:url("img/image01.png");"></div>
```
to
```
<img src="img/image01.png" class="img-responsive" alt="">
```
then it works.
I know this seems like a HTML or CSS problem, but I feel like I've exhausted all options that I can think of, leading me to think it's something with Wordpress and Bootstrap not working together. I've tried changing **background-image:url** to just **background:url** but it still comes up with totally white.
I also know that if I try it on another div like:
```
<section id="schedule">
<div class="row" style="background-image: url('img/image01.png'); margin-top: 75px;">
<div class="callout-light text-center" style="margin-bottom: 30px;">
<h1>Header!</h1>
</div>
</div>
</section>
```
That it comes up just fine.
Here is the full code:
```
<style>
.fill {
width: 100%;
height: 100%;
background-position: center;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover;
}
</style>
<header id="myCarousel" class="carousel slide">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>
<!-- Wrapper for Slides -->
<div class="carousel-inner">
<div class="item active">
<!-- Set the first background image using inline CSS below. -->
<div class="fill" style="background-image:url('img/image01.png');"></div>
<div class="carousel-caption">
<h2>Caption 1</h2>
</div>
</div>
<div class="item">
<!-- Set the second background image using inline CSS below. -->
<div class="fill" style="background-image:url('img/image02.png');"></div>
<div class="carousel-caption">
<h2>Caption 2</h2>
</div>
</div>
<div class="item">
<!-- Set the third background image using inline CSS below. -->
<div class="fill" style="background-image:url('img/image03.png');"></div>
<div class="carousel-caption">
<h2>Caption 3</h2>
</div>
</div>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#myCarousel" data-slide="prev">
<span class="icon-prev"></span>
</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">
<span class="icon-next"></span>
</a>
</header>
```
|
What if you use:
```
<div class="fill" style="background-image: url(<?php
echo get_stylesheet_directory_uri();?>/img/image01.png);"></div>
```
You need to tell WordPress in "a WordPress-way" where to find the image...
Look in codex at [get\_stylesheet\_directory\_uri()](https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri).
|
216,896 |
<p>I have a field that lets me enter a price for a product in 'edit post'.</p>
<p>Here's how it's currently called: </p>
<pre><code><span class="price"> "$" <?php echo get_post_meta(get_the_ID(),'si-price',true); ?> </span>
</code></pre>
<p>Because some products are discontinued, I would like to only show the "$" if what I type in the box is a number. That way I can have products with no price, and have some products marked as "coming soon" etc. without having the '$' in front of it.</p>
<p>I have tried:</p>
<pre><code><?php
$price = get_post_meta(get_the_ID(),'si-price',true);
foreach ($price as $element) {
if (is_numeric($element)) {
echo '$' $price;
} else {
echo $price;
}
}
?>
</code></pre>
<p>No joy! Any help would be greatly appreciated.</p>
|
[
{
"answer_id": 232383,
"author": "matt",
"author_id": 98400,
"author_profile": "https://wordpress.stackexchange.com/users/98400",
"pm_score": 0,
"selected": false,
"text": "<pre><code><div class=\"fill\" style=\"background-image:url(\"img/image01.png\");\"></div>\n</code></pre>\n\n<p>Your double quotes within double quotes will stop it from working, you need:</p>\n\n<pre><code><div class=\"fill\" style=\"background-image:url('img/image01.png');\"></div>\n</code></pre>\n"
},
{
"answer_id": 232399,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>You should never use relative urls in wordpress except for css files. If \"pretty permalink\" something that works on one page might break on another. All urls should be absolute. The most you can get with usually is being relative to the protocol, but almost never anything more then that.</p>\n"
},
{
"answer_id": 237276,
"author": "user101738",
"author_id": 101738,
"author_profile": "https://wordpress.stackexchange.com/users/101738",
"pm_score": 2,
"selected": false,
"text": "<p>What if you use:</p>\n\n<pre><code><div class=\"fill\" style=\"background-image: url(<?php \n echo get_stylesheet_directory_uri();?>/img/image01.png);\"></div>\n</code></pre>\n\n<p>You need to tell WordPress in \"a WordPress-way\" where to find the image...\nLook in codex at <a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri\" rel=\"nofollow\">get_stylesheet_directory_uri()</a>.</p>\n"
}
] |
2016/02/06
|
[
"https://wordpress.stackexchange.com/questions/216896",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88223/"
] |
I have a field that lets me enter a price for a product in 'edit post'.
Here's how it's currently called:
```
<span class="price"> "$" <?php echo get_post_meta(get_the_ID(),'si-price',true); ?> </span>
```
Because some products are discontinued, I would like to only show the "$" if what I type in the box is a number. That way I can have products with no price, and have some products marked as "coming soon" etc. without having the '$' in front of it.
I have tried:
```
<?php
$price = get_post_meta(get_the_ID(),'si-price',true);
foreach ($price as $element) {
if (is_numeric($element)) {
echo '$' $price;
} else {
echo $price;
}
}
?>
```
No joy! Any help would be greatly appreciated.
|
What if you use:
```
<div class="fill" style="background-image: url(<?php
echo get_stylesheet_directory_uri();?>/img/image01.png);"></div>
```
You need to tell WordPress in "a WordPress-way" where to find the image...
Look in codex at [get\_stylesheet\_directory\_uri()](https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri).
|
216,903 |
<p>In my theme, I have a custom post type called sliders. Here the user is allowed to upload images in a <code>meta-box</code>. So, the images are saved as meta data in <code>wp_post_meta</code> table. </p>
<p>Now what I want to do is, displaying a slider using its ID. </p>
<p>I did like following but no result</p>
<pre><code>$my_query = new WP_Query('post_type=sliders&p=411');
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
the_post();
endwhile;
}
</code></pre>
<p>This doesn't display anything. No even errors. Anyway, If I used <code>the_title()</code> instead of <code>the_post()</code>, it shows the title of the slider fine. Same for the <code>the_author()</code> It shows the author without error. </p>
<p>Why is this weird ?</p>
|
[
{
"answer_id": 232383,
"author": "matt",
"author_id": 98400,
"author_profile": "https://wordpress.stackexchange.com/users/98400",
"pm_score": 0,
"selected": false,
"text": "<pre><code><div class=\"fill\" style=\"background-image:url(\"img/image01.png\");\"></div>\n</code></pre>\n\n<p>Your double quotes within double quotes will stop it from working, you need:</p>\n\n<pre><code><div class=\"fill\" style=\"background-image:url('img/image01.png');\"></div>\n</code></pre>\n"
},
{
"answer_id": 232399,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>You should never use relative urls in wordpress except for css files. If \"pretty permalink\" something that works on one page might break on another. All urls should be absolute. The most you can get with usually is being relative to the protocol, but almost never anything more then that.</p>\n"
},
{
"answer_id": 237276,
"author": "user101738",
"author_id": 101738,
"author_profile": "https://wordpress.stackexchange.com/users/101738",
"pm_score": 2,
"selected": false,
"text": "<p>What if you use:</p>\n\n<pre><code><div class=\"fill\" style=\"background-image: url(<?php \n echo get_stylesheet_directory_uri();?>/img/image01.png);\"></div>\n</code></pre>\n\n<p>You need to tell WordPress in \"a WordPress-way\" where to find the image...\nLook in codex at <a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri\" rel=\"nofollow\">get_stylesheet_directory_uri()</a>.</p>\n"
}
] |
2016/02/06
|
[
"https://wordpress.stackexchange.com/questions/216903",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62209/"
] |
In my theme, I have a custom post type called sliders. Here the user is allowed to upload images in a `meta-box`. So, the images are saved as meta data in `wp_post_meta` table.
Now what I want to do is, displaying a slider using its ID.
I did like following but no result
```
$my_query = new WP_Query('post_type=sliders&p=411');
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
the_post();
endwhile;
}
```
This doesn't display anything. No even errors. Anyway, If I used `the_title()` instead of `the_post()`, it shows the title of the slider fine. Same for the `the_author()` It shows the author without error.
Why is this weird ?
|
What if you use:
```
<div class="fill" style="background-image: url(<?php
echo get_stylesheet_directory_uri();?>/img/image01.png);"></div>
```
You need to tell WordPress in "a WordPress-way" where to find the image...
Look in codex at [get\_stylesheet\_directory\_uri()](https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri).
|
216,908 |
<p>Is there a way to make the admins see only their pod entries in the back-end "View All entries" ?</p>
<p>Normal users see only their entries but admins see everything no matter how i configure the roles….</p>
|
[
{
"answer_id": 232383,
"author": "matt",
"author_id": 98400,
"author_profile": "https://wordpress.stackexchange.com/users/98400",
"pm_score": 0,
"selected": false,
"text": "<pre><code><div class=\"fill\" style=\"background-image:url(\"img/image01.png\");\"></div>\n</code></pre>\n\n<p>Your double quotes within double quotes will stop it from working, you need:</p>\n\n<pre><code><div class=\"fill\" style=\"background-image:url('img/image01.png');\"></div>\n</code></pre>\n"
},
{
"answer_id": 232399,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>You should never use relative urls in wordpress except for css files. If \"pretty permalink\" something that works on one page might break on another. All urls should be absolute. The most you can get with usually is being relative to the protocol, but almost never anything more then that.</p>\n"
},
{
"answer_id": 237276,
"author": "user101738",
"author_id": 101738,
"author_profile": "https://wordpress.stackexchange.com/users/101738",
"pm_score": 2,
"selected": false,
"text": "<p>What if you use:</p>\n\n<pre><code><div class=\"fill\" style=\"background-image: url(<?php \n echo get_stylesheet_directory_uri();?>/img/image01.png);\"></div>\n</code></pre>\n\n<p>You need to tell WordPress in \"a WordPress-way\" where to find the image...\nLook in codex at <a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri\" rel=\"nofollow\">get_stylesheet_directory_uri()</a>.</p>\n"
}
] |
2016/02/06
|
[
"https://wordpress.stackexchange.com/questions/216908",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66972/"
] |
Is there a way to make the admins see only their pod entries in the back-end "View All entries" ?
Normal users see only their entries but admins see everything no matter how i configure the roles….
|
What if you use:
```
<div class="fill" style="background-image: url(<?php
echo get_stylesheet_directory_uri();?>/img/image01.png);"></div>
```
You need to tell WordPress in "a WordPress-way" where to find the image...
Look in codex at [get\_stylesheet\_directory\_uri()](https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri).
|
216,912 |
<p>Any expert who knows about removing <a href="https://wordpress.org/plugins/remove-query-strings-from-static-resources/" rel="nofollow noreferrer">Remove Query Strings From Static Resources</a> plugin? It's not working.</p>
<p>Also, I have tried to write this code in <code>function.php</code> file of my theme</p>
<pre><code>function _remove_script_version( $src ){
$parts = explode( '?', $src );
return $parts[0];
}
add_filter( 'script_loader_src', '_remove_script_version', 15, 1 );
add_filter( 'style_loader_src', '_remove_script_version', 15, 1 );
</code></pre>
<p>This is also not working for me.</p>
<p>I have also unchecked "Prevent caching of objects after settings change after settings change" in <a href="https://wordpress.org/plugins/w3-total-cache/" rel="nofollow noreferrer">W3 Total Cache</a>, but I'm still getting the same result in <a href="https://gtmetrix.com/" rel="nofollow noreferrer">GTMetrix</a>.</p>
<p>Can anybody help me? I am using the <a href="https://wordpress.org/themes/twentytwelve/" rel="nofollow noreferrer">Twenty Twelve</a> theme. I have also tried the same techniques in other themes.</p>
<p>Below is a screenshot of the message form GTMetrix:
<a href="https://i.stack.imgur.com/tM0D5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tM0D5.png" alt="screen shot of problem"></a></p>
|
[
{
"answer_id": 217973,
"author": "CodyA",
"author_id": 84632,
"author_profile": "https://wordpress.stackexchange.com/users/84632",
"pm_score": 3,
"selected": false,
"text": "<p>It looks like you are using JetPack's Photon which adds query strings to your URLs. According to this thread there is no way to remove them <a href=\"https://wordpress.org/support/topic/how-to-remove-photon-query-string?replies=2\" rel=\"noreferrer\">https://wordpress.org/support/topic/how-to-remove-photon-query-string?replies=2</a></p>\n\n<p>If you want to get rid of the query strings I would suggest deactivating photon, using a CDN which does not add query strings, and using the snippet you mentioned:</p>\n\n<pre><code>function _remove_script_version( $src ){\n$parts = explode( '?ver', $src );\nreturn $parts[0];\n}\nadd_filter( 'script_loader_src', '_remove_script_version', 15, 1 );\nadd_filter( 'style_loader_src', '_remove_script_version', 15, 1 );\n</code></pre>\n"
},
{
"answer_id": 217975,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>It is a bad idea to remove query string as it is the best way to bust caches.</p>\n\n<p>Hmmm, maybe I should rephrase it. The cost of implementing a url scheme which will \"hide\" the parameters while still letting you bust the cache is too much for simple wordpress sites to implement. In theory you can do it, but in practice I never saw anyone do it.</p>\n"
},
{
"answer_id": 236167,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 0,
"selected": false,
"text": "<p>As mentioned by <a href=\"https://wordpress.stackexchange.com/users/23970/mark-kaplun\">Mark Kaplun</a>, sometimes query strings are necessary for a website. In this instance, having the <code>?w=</code> query sets the image size.</p>\n\n<p>If you still want to remove those queries, use the following code in your <code>functions.php</code>:</p>\n\n<pre><code>add_filter( 'script_loader_src', 'wpse_216912_remove_query' );\nadd_filter( 'style_loader_src', 'wpse_216912_remove_query' );\n\nfunction wpse_216912_remove_query( $src ) { // Remove query strings from static resources also jetpack query\n if ( strpos( $src, '?ver=' ) || strpos( $src, '&ver=' ) || strpos( $src, '?w=') || strpos( $src, '?a600e5') ) {\n $src = remove_query_arg( array( 'ver', 'w', 'a600e5' ), $src );\n }\n return $src;\n}\n</code></pre>\n"
}
] |
2016/02/06
|
[
"https://wordpress.stackexchange.com/questions/216912",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88233/"
] |
Any expert who knows about removing [Remove Query Strings From Static Resources](https://wordpress.org/plugins/remove-query-strings-from-static-resources/) plugin? It's not working.
Also, I have tried to write this code in `function.php` file of my theme
```
function _remove_script_version( $src ){
$parts = explode( '?', $src );
return $parts[0];
}
add_filter( 'script_loader_src', '_remove_script_version', 15, 1 );
add_filter( 'style_loader_src', '_remove_script_version', 15, 1 );
```
This is also not working for me.
I have also unchecked "Prevent caching of objects after settings change after settings change" in [W3 Total Cache](https://wordpress.org/plugins/w3-total-cache/), but I'm still getting the same result in [GTMetrix](https://gtmetrix.com/).
Can anybody help me? I am using the [Twenty Twelve](https://wordpress.org/themes/twentytwelve/) theme. I have also tried the same techniques in other themes.
Below is a screenshot of the message form GTMetrix:
[](https://i.stack.imgur.com/tM0D5.png)
|
It looks like you are using JetPack's Photon which adds query strings to your URLs. According to this thread there is no way to remove them <https://wordpress.org/support/topic/how-to-remove-photon-query-string?replies=2>
If you want to get rid of the query strings I would suggest deactivating photon, using a CDN which does not add query strings, and using the snippet you mentioned:
```
function _remove_script_version( $src ){
$parts = explode( '?ver', $src );
return $parts[0];
}
add_filter( 'script_loader_src', '_remove_script_version', 15, 1 );
add_filter( 'style_loader_src', '_remove_script_version', 15, 1 );
```
|
216,913 |
<p>How do I convert file system path to URL?
I have found some general PHP solutions that can be error prone.</p>
<p>Is there some WordPress specific way to do it?</p>
|
[
{
"answer_id": 216915,
"author": "chrisguitarguy",
"author_id": 6035,
"author_profile": "https://wordpress.stackexchange.com/users/6035",
"pm_score": 4,
"selected": true,
"text": "<p>Kind of depends on where you are in the WordPress environment.</p>\n\n<h2>Plugins</h2>\n\n<p>If you're in a plugin, you can use <a href=\"https://codex.wordpress.org/Function_Reference/plugins_url\" rel=\"noreferrer\"><code>plugins_url</code></a>.</p>\n\n<pre><code><?php\n$url = plugins_url('css/admin.css', __FILE__);\n</code></pre>\n\n<p>The above will give you the path relative to the file passed into the second argument. So if you're in the main plugin file you might get something like <code>http://example.com/wp-content/plugins/your-plugin/css/admin.css</code>.</p>\n\n<p>There's also <a href=\"https://codex.wordpress.org/Function_Reference/plugin_dir_url\" rel=\"noreferrer\"><code>plugin_dir_url</code></a> to get the URL of a directory. One fairly common pattern is to define a constant with your plugin url in the main plugin file.</p>\n\n<pre><code><?php\n/** plugin name: wpse216913 example */\ndefine('WPSE216913_PLUGINURL', plugin_dir_url(__FILE__));\n\n// wp_enqueue_style('example', WPSE216913_PLUGINURL.'css/admin.css');\n</code></pre>\n\n<h2>Themes</h2>\n\n<p>Themes, on the other hand should use <a href=\"https://developer.wordpress.org/reference/functions/get_template_directory_uri/\" rel=\"noreferrer\"><code>get_template_directory_uri</code></a> or <a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri\" rel=\"noreferrer\"><code>get_stylesheet_directory_uri</code></a>.</p>\n\n<p><code>get_template_directory_uri</code> will return the parent theme's directory URI if there is a parent theme. <code>get_stylesheet_directory_uri</code> will return the child theme's URI if there is a child theme, or the parent theme's otherwise. Read the codex for more on the differences. The <a href=\"https://github.com/WordPress/WordPress/blob/146320744f7c9ee169b67127613ef0cea882fa5c/wp-content/themes/twentyfifteen/functions.php#L236\" rel=\"noreferrer\">twenty fifteen theme</a> has some examples of how these are used.</p>\n\n<pre><code>wp_enqueue_style(\n 'twentyfifteen-ie',\n get_template_directory_uri().'/css/ie.css',\n array('twentyfifteen-style'),\n '20141010'\n);\n</code></pre>\n\n<h2>Uploads</h2>\n\n<p>Use <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"noreferrer\"><code>wp_get_attachment_image_src</code></a> for uploaded images. The return value will also include the width and height of the image. This also let's you say which size you want.</p>\n\n<p>Or there's <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_url\" rel=\"noreferrer\"><code>wp_get_attachment_url</code></a> to retrieve the URL of the attachment that was uploaded. If used on images, this will return the URL of the original image.</p>\n\n<p>If you need the URL (or path) of the upload directory so you can do something like a custom upload or otherwise, you can use <a href=\"https://developer.wordpress.org/reference/functions/wp_upload_dir/\" rel=\"noreferrer\"><code>wp_upload_dir</code></a> which returns an array with all the info you'll need.</p>\n\n<pre><code>print_r(wp_upload_dir())\n/*\nArray\n(\n [path] => /path/to/wordpress/wp-content/uploads/2016/02\n [url] => http://example.com/wp-content/uploads/2016/02\n [subdir] => /2016/02\n [basedir] => /path/to/wordpress/wp-content/uploads\n [baseurl] => http://example.com/wp-content/uploads\n [error] => false\n)\n*/\n</code></pre>\n\n<h2>Other Useful URL Functions</h2>\n\n<p>All of these have the same signature, <code>urlFunc($path, $scheme)</code>, and both arguments are optionall.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/home_url\" rel=\"noreferrer\"><code>home_url</code></a> returns a path relative to the sites home page.</p>\n\n<pre><code>echo home_url('/example'); // http://example.com/example\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/site_url\" rel=\"noreferrer\"><code>site_url</code></a> returns a URL relative to where the WordPress core files are. Say you had WordPress in the directory <code>wp</code>...</p>\n\n<pre><code>echo site_url('/example'); // http://example.com/wp/example\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/admin_url\" rel=\"noreferrer\"><code>admin_url</code></a> returns a URL relative to the <code>wp-admin</code> path. Useful when you need the path to <code>admin-ajax.php</code>, for instance.</p>\n\n<pre><code>echo admin_url('admin-ajax.php'); // http://example.com/wp/wp-admin/admin-ajax.php\n</code></pre>\n\n<p>There are a few others like <code>content_url</code> and <code>includes_url</code> which return the paths to the WP content and includes directories (or paths relative to them) respectively.</p>\n"
},
{
"answer_id": 259254,
"author": "Corey C.",
"author_id": 89740,
"author_profile": "https://wordpress.stackexchange.com/users/89740",
"pm_score": 2,
"selected": false,
"text": "<p>In a theme, if you want to literally convert a file system path to a URL for a given file, you would do this:</p>\n\n<p><code>$url = str_replace( get_stylesheet_directory(), get_stylesheet_directory_uri(), $systempath);</code></p>\n"
},
{
"answer_id": 264870,
"author": "Serge Liatko",
"author_id": 118406,
"author_profile": "https://wordpress.stackexchange.com/users/118406",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Or global</strong></p>\n\n<pre><code>function abs_path_to_url( $path = '' ) {\n $url = str_replace(\n wp_normalize_path( untrailingslashit( ABSPATH ) ),\n site_url(),\n wp_normalize_path( $path )\n );\n return esc_url_raw( $url );\n}\n</code></pre>\n"
},
{
"answer_id": 314762,
"author": "GDY",
"author_id": 52227,
"author_profile": "https://wordpress.stackexchange.com/users/52227",
"pm_score": 0,
"selected": false,
"text": "<p>This should work with any wordpress path:</p>\n\n<pre><code>function path_to_url( $path ) {\n\n return get_site_url() . '/' . str_replace( ABSPATH, '', $path );\n\n}\n\necho path_to_url( YOUR_PATH_HERE );\n</code></pre>\n"
},
{
"answer_id": 346036,
"author": "Sergio Zaharchenko",
"author_id": 136533,
"author_profile": "https://wordpress.stackexchange.com/users/136533",
"pm_score": 2,
"selected": false,
"text": "<p>Here is my solution for this:</p>\n\n<pre><code>function convert_url_to_path( $url ) {\n return str_replace( \n wp_get_upload_dir()['baseurl'], \n wp_get_upload_dir()['basedir'], \n $url\n );\n}\n</code></pre>\n"
}
] |
2016/02/06
|
[
"https://wordpress.stackexchange.com/questions/216913",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85230/"
] |
How do I convert file system path to URL?
I have found some general PHP solutions that can be error prone.
Is there some WordPress specific way to do it?
|
Kind of depends on where you are in the WordPress environment.
Plugins
-------
If you're in a plugin, you can use [`plugins_url`](https://codex.wordpress.org/Function_Reference/plugins_url).
```
<?php
$url = plugins_url('css/admin.css', __FILE__);
```
The above will give you the path relative to the file passed into the second argument. So if you're in the main plugin file you might get something like `http://example.com/wp-content/plugins/your-plugin/css/admin.css`.
There's also [`plugin_dir_url`](https://codex.wordpress.org/Function_Reference/plugin_dir_url) to get the URL of a directory. One fairly common pattern is to define a constant with your plugin url in the main plugin file.
```
<?php
/** plugin name: wpse216913 example */
define('WPSE216913_PLUGINURL', plugin_dir_url(__FILE__));
// wp_enqueue_style('example', WPSE216913_PLUGINURL.'css/admin.css');
```
Themes
------
Themes, on the other hand should use [`get_template_directory_uri`](https://developer.wordpress.org/reference/functions/get_template_directory_uri/) or [`get_stylesheet_directory_uri`](https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri).
`get_template_directory_uri` will return the parent theme's directory URI if there is a parent theme. `get_stylesheet_directory_uri` will return the child theme's URI if there is a child theme, or the parent theme's otherwise. Read the codex for more on the differences. The [twenty fifteen theme](https://github.com/WordPress/WordPress/blob/146320744f7c9ee169b67127613ef0cea882fa5c/wp-content/themes/twentyfifteen/functions.php#L236) has some examples of how these are used.
```
wp_enqueue_style(
'twentyfifteen-ie',
get_template_directory_uri().'/css/ie.css',
array('twentyfifteen-style'),
'20141010'
);
```
Uploads
-------
Use [`wp_get_attachment_image_src`](https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/) for uploaded images. The return value will also include the width and height of the image. This also let's you say which size you want.
Or there's [`wp_get_attachment_url`](https://codex.wordpress.org/Function_Reference/wp_get_attachment_url) to retrieve the URL of the attachment that was uploaded. If used on images, this will return the URL of the original image.
If you need the URL (or path) of the upload directory so you can do something like a custom upload or otherwise, you can use [`wp_upload_dir`](https://developer.wordpress.org/reference/functions/wp_upload_dir/) which returns an array with all the info you'll need.
```
print_r(wp_upload_dir())
/*
Array
(
[path] => /path/to/wordpress/wp-content/uploads/2016/02
[url] => http://example.com/wp-content/uploads/2016/02
[subdir] => /2016/02
[basedir] => /path/to/wordpress/wp-content/uploads
[baseurl] => http://example.com/wp-content/uploads
[error] => false
)
*/
```
Other Useful URL Functions
--------------------------
All of these have the same signature, `urlFunc($path, $scheme)`, and both arguments are optionall.
[`home_url`](https://codex.wordpress.org/Function_Reference/home_url) returns a path relative to the sites home page.
```
echo home_url('/example'); // http://example.com/example
```
[`site_url`](https://codex.wordpress.org/Function_Reference/site_url) returns a URL relative to where the WordPress core files are. Say you had WordPress in the directory `wp`...
```
echo site_url('/example'); // http://example.com/wp/example
```
[`admin_url`](https://codex.wordpress.org/Function_Reference/admin_url) returns a URL relative to the `wp-admin` path. Useful when you need the path to `admin-ajax.php`, for instance.
```
echo admin_url('admin-ajax.php'); // http://example.com/wp/wp-admin/admin-ajax.php
```
There are a few others like `content_url` and `includes_url` which return the paths to the WP content and includes directories (or paths relative to them) respectively.
|
216,929 |
<p>I'm currently trying to output a list of music titles and would like to have the sorting ignore (but still display) the initial article of the title.</p>
<p>For example if I had a list of bands it will be displayed alphabetically in WordPress like this:</p>
<ul>
<li>Black Sabbath </li>
<li>Led Zeppelin</li>
<li>Pink Floyd</li>
<li>The Beatles</li>
<li>The Kinks</li>
<li>The Rolling Stones</li>
<li>Thin Lizzy</li>
</ul>
<p>Instead I would like to have it displayed alphabetically while ignoring the initial article 'The', like this:</p>
<ul>
<li>The Beatles</li>
<li>Black Sabbath</li>
<li>The Kinks</li>
<li>Led Zeppelin</li>
<li>Pink Floyd</li>
<li>The Rolling Stones</li>
<li>Thin Lizzy</li>
</ul>
<p>I came across a solution in <a href="https://css-tricks.com/ignoring-the-in-wordpress-queries/">a blog entry from last year</a>, that suggests the following code in <code>functions.php</code>:</p>
<pre><code>function wpcf_create_temp_column($fields) {
global $wpdb;
$matches = 'The';
$has_the = " CASE
WHEN $wpdb->posts.post_title regexp( '^($matches)[[:space:]]' )
THEN trim(substr($wpdb->posts.post_title from 4))
ELSE $wpdb->posts.post_title
END AS title2";
if ($has_the) {
$fields .= ( preg_match( '/^(\s+)?,/', $has_the ) ) ? $has_the : ", $has_the";
}
return $fields;
}
function wpcf_sort_by_temp_column ($orderby) {
$custom_orderby = " UPPER(title2) ASC";
if ($custom_orderby) {
$orderby = $custom_orderby;
}
return $orderby;
}
</code></pre>
<p>and then wrapping the query with <code>add_filter</code> before and <code>remove_filter</code> after.</p>
<p>I've tried this, but I keep getting the following error on my site:</p>
<blockquote>
<p>WordPress database error: [Unknown column 'title2' in 'order clause']</p>
<p>SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.post_type =
'release' AND (wp_posts.post_status = 'publish' OR
wp_posts.post_status = 'private') ORDER BY UPPER(title2) ASC</p>
</blockquote>
<p>I'm not gonna lie, I'm pretty new to the php part of WordPress, so I'm unsure as to why I'm getting this error. I can see it's got something to do with the 'title2' column, but it was my understanding that the first function should take care of that. Also, if there's a smarter way to do this I'm all ears. I've been googling around and searching this site, but I haven't really found a lot of solutions.</p>
<p>My code using the filters looks like this if it's any help:</p>
<pre><code><?php
$args_post = array('post_type' => 'release', 'orderby' => 'title', 'order' => 'ASC', 'posts_per_page' => -1, );
add_filter('post_fields', 'wpcf_create_temp_column'); /* remove initial 'The' from post titles */
add_filter('posts_orderby', 'wpcf_sort_by_temp_column');
$loop = new WP_Query($args_post);
remove_filter('post_fields', 'wpcf_create_temp_column');
remove_filter('posts_orderby', 'wpcf_sort_by_temp_column');
while ($loop->have_posts() ) : $loop->the_post();
?>
</code></pre>
|
[
{
"answer_id": 216942,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 4,
"selected": false,
"text": "<p>An easier way may be to go through and change the permalink slug on those posts that need it (under the title on the post writing screen) and then just use that for ordering instead of the title. </p>\n\n<p>ie. use <code>post_name</code> not <code>post_title</code> for sorting... </p>\n\n<p>This would also mean that your permalink may be different if you use %postname% in your permalink structure, which could be an added bonus.</p>\n\n<p>eg. gives <code>http://example.com/rolling-stones/</code>\nnot <code>http://example.com/the-rolling-stones/</code></p>\n\n<p><strong>EDIT</strong>: code to update the existing slugs, removing the unwanted prefixes from <code>post_name</code> column...</p>\n\n<pre><code>global $wpdb;\n$posttype = 'release';\n$stripprefixes = array('a-','an-','the-');\n\n$results = $wpdb->get_results(\"SELECT ID, post_name FROM \".$wpdb->prefix.\"posts\" WHERE post_type = '\".$posttype.\"' AND post_status = 'publish');\nif (count($results) > 0) {\n foreach ($results as $result) {\n $postid = $result->ID;\n $postslug = $result->post_name;\n foreach ($stripprefixes as $stripprefix) {\n $checkprefix = strtolower(substr($postslug,0,strlen($stripprefix));\n if ($checkprefix == $stripprefix) {\n $newslug = substr($postslug,strlen($stripprefix),strlen($postslug));\n // echo $newslug; // debug point\n $query = $wpdb->prepare(\"UPDATE \".$wpdb->prefix.\"posts SET post_name = '%s' WHERE ID = '%d'\", $newslug, $postid);\n $wpdb->query($query);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 216944,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<h2>The Problem</h2>\n\n<p>I think there's a typo in there:</p>\n\n<p>The name of the filter is <code>posts_fields</code> not <code>post_fields</code>.</p>\n\n<p>That could explain why the <code>title2</code> field is unknown, because it's definition isn't added to the generated SQL string.</p>\n\n<h2>Alternative - Single filter</h2>\n\n<p>We can rewrite it to use only a single filter:</p>\n\n<pre><code>add_filter( 'posts_orderby', function( $orderby, \\WP_Query $q )\n{\n // Do nothing\n if( '_custom' !== $q->get( 'orderby' ) )\n return $orderby;\n\n global $wpdb;\n\n $matches = 'The'; // REGEXP is not case sensitive here\n\n // Custom ordering (SQL)\n return sprintf( \n \" \n CASE \n WHEN {$wpdb->posts}.post_title REGEXP( '^($matches)[[:space:]]+' )\n THEN TRIM( SUBSTR( {$wpdb->posts}.post_title FROM %d )) \n ELSE {$wpdb->posts}.post_title \n END %s\n \",\n strlen( $matches ) + 1,\n 'ASC' === strtoupper( $q->get( 'order' ) ) ? 'ASC' : 'DESC' \n );\n\n}, 10, 2 );\n</code></pre>\n\n<p>where you can now activate the custom ordering with the <code>_custom</code> orderby parameter:</p>\n\n<pre><code>$args_post = array\n 'post_type' => 'release', \n 'orderby' => '_custom', // Activate the custom ordering \n 'order' => 'ASC', \n 'posts_per_page' => -1, \n);\n\n$loop = new WP_Query($args_post);\n\nwhile ($loop->have_posts() ) : $loop->the_post();\n</code></pre>\n\n<h2>Alternative - Recursive <code>TRIM()</code></h2>\n\n<p>Let's implement the recursive idea by <strong>Pascal Birchler</strong>, <a href=\"https://css-tricks.com/ignoring-the-in-wordpress-queries/#comment-1594211\" rel=\"noreferrer\">commented here</a>:</p>\n\n<pre><code>add_filter( 'posts_orderby', function( $orderby, \\WP_Query $q )\n{\n if( '_custom' !== $q->get( 'orderby' ) )\n return $orderby;\n\n global $wpdb;\n\n // Adjust this to your needs:\n $matches = [ 'the ', 'an ', 'a ' ];\n\n return sprintf( \n \" %s %s \",\n wpse_sql( $matches, \" LOWER( {$wpdb->posts}.post_title) \" ),\n 'ASC' === strtoupper( $q->get( 'order' ) ) ? 'ASC' : 'DESC' \n );\n\n}, 10, 2 );\n</code></pre>\n\n<p>where we can for example construct the recursive function as:</p>\n\n<pre><code>function wpse_sql( &$matches, $sql )\n{\n if( empty( $matches ) || ! is_array( $matches ) )\n return $sql;\n\n $sql = sprintf( \" TRIM( LEADING '%s' FROM ( %s ) ) \", $matches[0], $sql );\n array_shift( $matches ); \n return wpse_sql( $matches, $sql );\n}\n</code></pre>\n\n<p>This means that </p>\n\n<pre><code>$matches = [ 'the ', 'an ', 'a ' ];\necho wpse_sql( $matches, \" LOWER( {$wpdb->posts}.post_title) \" );\n</code></pre>\n\n<p>will generate:</p>\n\n<pre><code>TRIM( LEADING 'a ' FROM ( \n TRIM( LEADING 'an ' FROM ( \n TRIM( LEADING 'the ' FROM ( \n LOWER( wp_posts.post_title) \n ) )\n ) )\n) )\n</code></pre>\n\n<h2>Alternative - MariaDB</h2>\n\n<p>In general I like to use <em>MariaDB</em> instead of <em>MySQL</em>. Then it's much easier because <em>MariaDB 10.0.5</em> <a href=\"https://mariadb.com/kb/en/mariadb/regexp_replace/\" rel=\"noreferrer\">supports</a> <code>REGEXP_REPLACE</code>:</p>\n\n<pre><code>/**\n * Ignore (the,an,a) in post title ordering\n *\n * @uses MariaDB 10.0.5+\n */\nadd_filter( 'posts_orderby', function( $orderby, \\WP_Query $q )\n{\n if( '_custom' !== $q->get( 'orderby' ) )\n return $orderby;\n\n global $wpdb;\n return sprintf( \n \" REGEXP_REPLACE( {$wpdb->posts}.post_title, '^(the|a|an)[[:space:]]+', '' ) %s\",\n 'ASC' === strtoupper( $q->get( 'order' ) ) ? 'ASC' : 'DESC' \n );\n}, 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 216945,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": false,
"text": "<h2>EDIT</h2>\n\n<p>I have improved the code a bit. All code block are updated accordingly. Just a note though before jumping into the updates in the <strong>ORIGINAL ANSWER</strong>, I have set up the code to work with the following</p>\n\n<ul>\n<li><p>Custom post type -> <strong><code>release</code></strong></p></li>\n<li><p>Custom taxonomy -> <strong><code>game</code></strong></p></li>\n</ul>\n\n<p>Make sure to set this according to your needs</p>\n\n<h2>ORIGINAL ANSWER</h2>\n\n<p>In addition to the other answers and the typo pointed out by @birgire, here is another approach.</p>\n\n<p>First, we will set the title as a hidden custom field, but we will first remove the words like <code>the</code> that we would want to exclude. Before we do that, we need to first create a helper function in order to remove the banned words from the term names and post titles</p>\n\n<pre><code>/**\n * Function get_name_banned_removed()\n *\n * A helper function to handle removing banned words\n * \n * @param string $tring String to remove banned words from\n * @param array $banned Array of banned words to remove\n * @return string $string\n */\nfunction get_name_banned_removed( $string = '', $banned = [] )\n{\n // Make sure we have a $string to handle\n if ( !$string )\n return $string;\n\n // Sanitize the string\n $string = filter_var( $string, FILTER_SANITIZE_STRING );\n\n // Make sure we have an array of banned words\n if ( !$banned\n || !is_array( $banned )\n )\n return $string; \n\n // Make sure that all banned words is lowercase\n $banned = array_map( 'strtolower', $banned );\n\n // Trim the string and explode into an array, remove banned words and implode\n $text = trim( $string );\n $text = strtolower( $text );\n $text_exploded = explode( ' ', $text );\n\n if ( in_array( $text_exploded[0], $banned ) )\n unset( $text_exploded[0] );\n\n $text_as_string = implode( ' ', $text_exploded );\n\n return $string = $text_as_string;\n}\n</code></pre>\n\n<p>Now that we have that covered, lets look at the piece of code to set our custom field. You must <strong>remove</strong> this code completely as soon as you have loaded any page once. If you have a huge site with a ton of posts, you can set <code>posts_per_page</code> to something to <code>100</code> and run the scripts a couple of times until all posts have the custom field have been set to all posts</p>\n\n<pre><code>add_action( 'wp', function ()\n{\n add_filter( 'posts_fields', function ( $fields, \\WP_Query $q ) \n {\n global $wpdb;\n\n remove_filter( current_filter(), __FUNCTION__ );\n\n // Only target a query where the new custom_query parameter is set with a value of custom_meta_1\n if ( 'custom_meta_1' === $q->get( 'custom_query' ) ) {\n // Only get the ID and post title fields to reduce server load\n $fields = \"$wpdb->posts.ID, $wpdb->posts.post_title\";\n }\n\n return $fields;\n }, 10, 2);\n\n $args = [\n 'post_type' => 'release', // Set according to needs\n 'posts_per_page' => -1, // Set to execute smaller chucks per page load if necessary\n 'suppress_filters' => false, // Allow the posts_fields filter\n 'custom_query' => 'custom_meta_1', // New parameter to allow that our filter only target this query\n 'meta_query' => [\n [\n 'key' => '_custom_sort_post_title', // Make it a hidden custom field\n 'compare' => 'NOT EXISTS'\n ]\n ]\n ];\n $q = get_posts( $args );\n\n // Make sure we have posts before we continue, if not, bail\n if ( !$q ) \n return;\n\n foreach ( $q as $p ) {\n $new_post_title = strtolower( $p->post_title );\n\n if ( function_exists( 'get_name_banned_removed' ) )\n $new_post_title = get_name_banned_removed( $new_post_title, ['the'] );\n\n // Set our custom field value\n add_post_meta( \n $p->ID, // Post ID\n '_custom_sort_post_title', // Custom field name\n $new_post_title // Custom field value\n ); \n } //endforeach $q\n});\n</code></pre>\n\n<p>Now that the custom fields are set to all posts and the code above is removed, we need to make sure that we set the this custom field to all new posts or whenever we update the post title. For this we will use the <code>transition_post_status</code> hook. The following code can go into a plugin (<em>which I recommend</em>) or in your <code>functions.php</code></p>\n\n<pre><code>add_action( 'transition_post_status', function ( $new_status, $old_status, $post )\n{\n // Make sure we only run this for the release post type\n if ( 'release' !== $post->post_type )\n return;\n\n $text = strtolower( $post->post_title ); \n\n if ( function_exists( 'get_name_banned_removed' ) )\n $text = get_name_banned_removed( $text, ['the'] );\n\n // Set our custom field value\n update_post_meta( \n $post->ID, // Post ID\n '_custom_sort_post_title', // Custom field name\n $text // Custom field value\n );\n}, 10, 3 );\n</code></pre>\n\n<h2>QUERYING YOUR POSTS</h2>\n\n<p>You can run your queries as normal without any custom filters. You can query and sort your posts as follow</p>\n\n<pre><code>$args_post = [\n 'post_type' => 'release', \n 'orderby' => 'meta_value', \n 'meta_key' => '_custom_sort_post_title',\n 'order' => 'ASC', \n 'posts_per_page' => -1, \n];\n$loop = new WP_Query( $args );\n</code></pre>\n"
},
{
"answer_id": 268386,
"author": "Yedidel Elhayany",
"author_id": 120611,
"author_profile": "https://wordpress.stackexchange.com/users/120611",
"pm_score": 0,
"selected": false,
"text": "<p>birgire's answers works good when ordering only by this field.\nI made some modifications to make it work when ordering by multiple fields (I am not sure that it works correctly when title ordering is the primary one):</p>\n\n<pre><code>add_filter( 'posts_orderby', function( $orderby, \\WP_Query $q )\n{\n// Do nothing\nif( '_custom' !== $q->get( 'orderby' ) && !isset($q->get( 'orderby' )['_custom']) )\n return $orderby;\n\nglobal $wpdb;\n\n$matches = 'The'; // REGEXP is not case sensitive here\n\n// Custom ordering (SQL)\nif (is_array($q->get( 'orderby' ))) {\n return sprintf( \n \" $orderby, \n CASE \n WHEN {$wpdb->posts}.post_title REGEXP( '^($matches)[[:space:]]+' )\n THEN TRIM( SUBSTR( {$wpdb->posts}.post_title FROM %d )) \n ELSE {$wpdb->posts}.post_title \n END %s\n \",\n strlen( $matches ) + 1,\n 'ASC' === strtoupper( $q->get( 'orderby' )['_custom'] ) ? 'ASC' : 'DESC' \n );\n}\nelse {\n return sprintf( \n \"\n CASE \n WHEN {$wpdb->posts}.post_title REGEXP( '^($matches)[[:space:]]+' )\n THEN TRIM( SUBSTR( {$wpdb->posts}.post_title FROM %d )) \n ELSE {$wpdb->posts}.post_title \n END %s\n \",\n strlen( $matches ) + 1,\n 'ASC' === strtoupper( $q->get( 'order' ) ) ? 'ASC' : 'DESC' \n );\n}\n\n}, 10, 2 );\n</code></pre>\n"
}
] |
2016/02/07
|
[
"https://wordpress.stackexchange.com/questions/216929",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86933/"
] |
I'm currently trying to output a list of music titles and would like to have the sorting ignore (but still display) the initial article of the title.
For example if I had a list of bands it will be displayed alphabetically in WordPress like this:
* Black Sabbath
* Led Zeppelin
* Pink Floyd
* The Beatles
* The Kinks
* The Rolling Stones
* Thin Lizzy
Instead I would like to have it displayed alphabetically while ignoring the initial article 'The', like this:
* The Beatles
* Black Sabbath
* The Kinks
* Led Zeppelin
* Pink Floyd
* The Rolling Stones
* Thin Lizzy
I came across a solution in [a blog entry from last year](https://css-tricks.com/ignoring-the-in-wordpress-queries/), that suggests the following code in `functions.php`:
```
function wpcf_create_temp_column($fields) {
global $wpdb;
$matches = 'The';
$has_the = " CASE
WHEN $wpdb->posts.post_title regexp( '^($matches)[[:space:]]' )
THEN trim(substr($wpdb->posts.post_title from 4))
ELSE $wpdb->posts.post_title
END AS title2";
if ($has_the) {
$fields .= ( preg_match( '/^(\s+)?,/', $has_the ) ) ? $has_the : ", $has_the";
}
return $fields;
}
function wpcf_sort_by_temp_column ($orderby) {
$custom_orderby = " UPPER(title2) ASC";
if ($custom_orderby) {
$orderby = $custom_orderby;
}
return $orderby;
}
```
and then wrapping the query with `add_filter` before and `remove_filter` after.
I've tried this, but I keep getting the following error on my site:
>
> WordPress database error: [Unknown column 'title2' in 'order clause']
>
>
> SELECT wp\_posts.\* FROM wp\_posts WHERE 1=1 AND wp\_posts.post\_type =
> 'release' AND (wp\_posts.post\_status = 'publish' OR
> wp\_posts.post\_status = 'private') ORDER BY UPPER(title2) ASC
>
>
>
I'm not gonna lie, I'm pretty new to the php part of WordPress, so I'm unsure as to why I'm getting this error. I can see it's got something to do with the 'title2' column, but it was my understanding that the first function should take care of that. Also, if there's a smarter way to do this I'm all ears. I've been googling around and searching this site, but I haven't really found a lot of solutions.
My code using the filters looks like this if it's any help:
```
<?php
$args_post = array('post_type' => 'release', 'orderby' => 'title', 'order' => 'ASC', 'posts_per_page' => -1, );
add_filter('post_fields', 'wpcf_create_temp_column'); /* remove initial 'The' from post titles */
add_filter('posts_orderby', 'wpcf_sort_by_temp_column');
$loop = new WP_Query($args_post);
remove_filter('post_fields', 'wpcf_create_temp_column');
remove_filter('posts_orderby', 'wpcf_sort_by_temp_column');
while ($loop->have_posts() ) : $loop->the_post();
?>
```
|
The Problem
-----------
I think there's a typo in there:
The name of the filter is `posts_fields` not `post_fields`.
That could explain why the `title2` field is unknown, because it's definition isn't added to the generated SQL string.
Alternative - Single filter
---------------------------
We can rewrite it to use only a single filter:
```
add_filter( 'posts_orderby', function( $orderby, \WP_Query $q )
{
// Do nothing
if( '_custom' !== $q->get( 'orderby' ) )
return $orderby;
global $wpdb;
$matches = 'The'; // REGEXP is not case sensitive here
// Custom ordering (SQL)
return sprintf(
"
CASE
WHEN {$wpdb->posts}.post_title REGEXP( '^($matches)[[:space:]]+' )
THEN TRIM( SUBSTR( {$wpdb->posts}.post_title FROM %d ))
ELSE {$wpdb->posts}.post_title
END %s
",
strlen( $matches ) + 1,
'ASC' === strtoupper( $q->get( 'order' ) ) ? 'ASC' : 'DESC'
);
}, 10, 2 );
```
where you can now activate the custom ordering with the `_custom` orderby parameter:
```
$args_post = array
'post_type' => 'release',
'orderby' => '_custom', // Activate the custom ordering
'order' => 'ASC',
'posts_per_page' => -1,
);
$loop = new WP_Query($args_post);
while ($loop->have_posts() ) : $loop->the_post();
```
Alternative - Recursive `TRIM()`
--------------------------------
Let's implement the recursive idea by **Pascal Birchler**, [commented here](https://css-tricks.com/ignoring-the-in-wordpress-queries/#comment-1594211):
```
add_filter( 'posts_orderby', function( $orderby, \WP_Query $q )
{
if( '_custom' !== $q->get( 'orderby' ) )
return $orderby;
global $wpdb;
// Adjust this to your needs:
$matches = [ 'the ', 'an ', 'a ' ];
return sprintf(
" %s %s ",
wpse_sql( $matches, " LOWER( {$wpdb->posts}.post_title) " ),
'ASC' === strtoupper( $q->get( 'order' ) ) ? 'ASC' : 'DESC'
);
}, 10, 2 );
```
where we can for example construct the recursive function as:
```
function wpse_sql( &$matches, $sql )
{
if( empty( $matches ) || ! is_array( $matches ) )
return $sql;
$sql = sprintf( " TRIM( LEADING '%s' FROM ( %s ) ) ", $matches[0], $sql );
array_shift( $matches );
return wpse_sql( $matches, $sql );
}
```
This means that
```
$matches = [ 'the ', 'an ', 'a ' ];
echo wpse_sql( $matches, " LOWER( {$wpdb->posts}.post_title) " );
```
will generate:
```
TRIM( LEADING 'a ' FROM (
TRIM( LEADING 'an ' FROM (
TRIM( LEADING 'the ' FROM (
LOWER( wp_posts.post_title)
) )
) )
) )
```
Alternative - MariaDB
---------------------
In general I like to use *MariaDB* instead of *MySQL*. Then it's much easier because *MariaDB 10.0.5* [supports](https://mariadb.com/kb/en/mariadb/regexp_replace/) `REGEXP_REPLACE`:
```
/**
* Ignore (the,an,a) in post title ordering
*
* @uses MariaDB 10.0.5+
*/
add_filter( 'posts_orderby', function( $orderby, \WP_Query $q )
{
if( '_custom' !== $q->get( 'orderby' ) )
return $orderby;
global $wpdb;
return sprintf(
" REGEXP_REPLACE( {$wpdb->posts}.post_title, '^(the|a|an)[[:space:]]+', '' ) %s",
'ASC' === strtoupper( $q->get( 'order' ) ) ? 'ASC' : 'DESC'
);
}, 10, 2 );
```
|
216,966 |
<p>Here's the code I'm trying to use.</p>
<pre><code><input type="button" class="next-step" value="Adopt Now" onClick="parent.location='http://example.com/adoption-application/?Name=[Title]'" />
</code></pre>
<p>The shortcode Title is defined.</p>
<p>End link in browser shows as <a href="http://example.com/adoption-application/?Name=[Title]" rel="nofollow">http://example.com/adoption-application/?Name=[Title]</a></p>
<p>Should show as</p>
<p><a href="http://example.com/adoption-application/?Name=Skeeter" rel="nofollow">http://example.com/adoption-application/?Name=Skeeter</a> (or whatever the current value of [Title] is)</p>
<p>What am I missing to make this work?</p>
|
[
{
"answer_id": 216972,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>You can not use a shortcode inside an attribute. You need to make a shortcode that will output the whole element.</p>\n"
},
{
"answer_id": 216973,
"author": "Emre Erkan",
"author_id": 9654,
"author_profile": "https://wordpress.stackexchange.com/users/9654",
"pm_score": 0,
"selected": false,
"text": "<p>You are using inline JavaScript, so it'll be fine to render shortcode like this;</p>\n\n<pre><code><input type=\"button\" class=\"next-step\" value=\"Adopt Now\" onClick=\"parent.location='http://example.com/adoption-application/?Name=<?php echo do_shortcode('[Title]'); ?>'\" />\n</code></pre>\n"
},
{
"answer_id": 216990,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 0,
"selected": false,
"text": "<p>If you're entering this directly in the post editor, rather than have the Shortcode return the title, make a Shortcode to return the link with title.</p>\n\n<pre><code>function adoption_link_function(){\n global $post;\n $link = \"parent.location='http://example.com/adoption-application/?Name={$post->post_title}'\";\n return '<input type=\"button\" class=\"next-step\" value=\"Adopt Now\" onClick=\"' . $link . '\" />';\n}\nadd_shortcode( 'adoption_link', 'adoption_link_function' );\n</code></pre>\n"
}
] |
2016/02/07
|
[
"https://wordpress.stackexchange.com/questions/216966",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88257/"
] |
Here's the code I'm trying to use.
```
<input type="button" class="next-step" value="Adopt Now" onClick="parent.location='http://example.com/adoption-application/?Name=[Title]'" />
```
The shortcode Title is defined.
End link in browser shows as <http://example.com/adoption-application/?Name=[Title]>
Should show as
<http://example.com/adoption-application/?Name=Skeeter> (or whatever the current value of [Title] is)
What am I missing to make this work?
|
You can not use a shortcode inside an attribute. You need to make a shortcode that will output the whole element.
|
217,013 |
<p>I am working on an enhanced revisioning system, to create a log file for all changes made by users and/or algorithms concerning metadata attached to specific post types.</p>
<p>While I am perfectly aware that <code>update_post_meta</code> works for all post types, while <code>update_postmeta</code> just works on post, my question is not dependent on the post type, and it also does not just cover the <code>update</code> part, as it is the same for <code>updated</code>, <code>delete</code>, etc.</p>
<p>After inspectiong <code>wp-includes/meta.php</code>, I found the previously mentioned hooks to get my stuff done, but this raised a questions for me.</p>
<p>The section in the core is this one - line 215 in Version 4.4.2:</p>
<pre><code>foreach ( $meta_ids as $meta_id ) {
/**
* Fires immediately before updating metadata of a specific type.
*
* The dynamic portion of the hook, `$meta_type`, refers to the meta
* object type (comment, post, or user).
*
* @since 2.9.0
*
* @param int $meta_id ID of the metadata entry to update.
* @param int $object_id Object ID.
* @param string $meta_key Meta key.
* @param mixed $meta_value Meta value.
*/
do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
}
if ( 'post' == $meta_type ) {
foreach ( $meta_ids as $meta_id ) {
/**
* Fires immediately before updating a post's metadata.
*
* @since 2.9.0
*
* @param int $meta_id ID of metadata entry to update.
* @param int $object_id Object ID.
* @param string $meta_key Meta key.
* @param mixed $meta_value Meta value.
*/
do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
}
}
</code></pre>
<p>So there is a hook for <code>update_post_meta</code>, <code>update_comment_meta</code>, and <code>update_user_meta</code>. Directly after that another hook is called - just for the posts table, named <code>update_postmeta</code>, working almost exactly the same way, with the only difference being that the <code>maybe_serialize()</code> data of the meta_value is passed.</p>
<p>Line 204: </p>
<pre><code>$_meta_value = $meta_value;
$meta_value = maybe_serialize( $meta_value );
</code></pre>
<p>At first I thought that the second hook is there for backward compatibility, but both of those were introduced in 2.9.0. <a href="http://adambrown.info/p/wp_hooks/hook/update_postmeta"><code>update_postmeta</code></a> and <a href="http://adambrown.info/p/wp_hooks/hook/update_%7B$meta_type%7D_meta"><code>update_{$meta_type}_meta</code></a></p>
<p>Looking a little bit further, I also found another answer by me, three years ago, where this topic also came up, but this was not the main point.</p>
<p>Am I missing something here?</p>
<p>Is this backward compatibility after all - and has just been moved to <code>meta.php</code> in 2.9.0? Or is there any real reason to have both of those? For me, the actions hooked to the <code>update_post_meta()</code> function could easily <code>maybe_unserialize()</code> the data, if needed, so I really do not see the point of having both.</p>
<p>Looking forward to your input!</p>
|
[
{
"answer_id": 217019,
"author": "Adam",
"author_id": 13418,
"author_profile": "https://wordpress.stackexchange.com/users/13418",
"pm_score": 3,
"selected": true,
"text": "<p>They were both introduced in version 2.9, but were done so in different files.</p>\n\n<p><code>update_postmeta</code> went into <a href=\"http://svn.automattic.com/wordpress/tags/2.9/wp-admin/includes/post.php\" rel=\"nofollow\"><code>/wp-admin/includes/post.php</code></a></p>\n\n<p>While...</p>\n\n<p><code>update_{$meta_type}_meta</code> went into <a href=\"http://adambrown.info/p/wp_hooks/version/2.9/wp-includes/meta.php\" rel=\"nofollow\"><code>/wp-includes/meta.php</code></a></p>\n\n<p>It was only later that <code>update_postmeta</code> was shifted into <code>/wp-includes/meta.php</code>.</p>\n\n<p>So I believe it was for backward compatability, where by because the <code>update_postmeta</code> hook was always receiving the value of <code>maybe_serialize()</code> then it should continue to do so, despite later being moved into <code>/wp-includes/meta.php</code>.</p>\n\n<p>Furthermore, which you may already know, but for the sake of others reading, the <code>update_postmeta</code> hook returns data from the <code>$_POST['meta']</code> superglobal and key which holds data from the <a href=\"https://codex.wordpress.org/Custom_Fields\" rel=\"nofollow\">custom fields panel</a>.</p>\n\n<p>Could this just have been a poor design decision? Looks like it.</p>\n\n<p><em>I thought I recalled some other reason surrounding this very question in relation to double serialization of data, however I could be getting mixed up with something else.</em></p>\n\n<p>Interestingly, if you store already serialized data in the Custom Field UI textarea, WordPress will serialize it again before storing it, which supports the notion of backward compatability in relation to:</p>\n\n<ul>\n<li><a href=\"https://core.trac.wordpress.org/ticket/12930\" rel=\"nofollow\">https://core.trac.wordpress.org/ticket/12930</a></li>\n<li><a href=\"https://nacin.com/2010/04/18/wordpress-serializing-data/\" rel=\"nofollow\">https://nacin.com/2010/04/18/wordpress-serializing-data/</a></li>\n</ul>\n\n<p>Note: <strong>this answer is not neccessarily complete</strong>.</p>\n"
},
{
"answer_id": 324997,
"author": "R. Simon",
"author_id": 158600,
"author_profile": "https://wordpress.stackexchange.com/users/158600",
"pm_score": 0,
"selected": false,
"text": "<p>As noticed in Wordpress Codex, <strong>add_post_meta</strong> inserts new postmeta associated to a post. If provided parameter \"unique\" as true, will check for existing key with same name. If exists, bypass it, if not, create and assign value</p>\n\n<p><strong>update_post_meta</strong> will update metadata and create new key and value pairs, if provided meta_key not exists.</p>\n\n<p><strong>What is the best to use?</strong> It depends. update_post_meta fits the most situations, but sometimes add_post_meta will get the work done if you need to add metadata in restrited environments (shared hosting, for example).</p>\n\n<p>Please read for more info:\n<a href=\"https://codex.wordpress.org/Function_Reference/update_post_meta\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/update_post_meta</a> and \n<a href=\"https://codex.wordpress.org/Function_Reference/add_post_meta\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/add_post_meta</a></p>\n"
}
] |
2016/02/08
|
[
"https://wordpress.stackexchange.com/questions/217013",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/15680/"
] |
I am working on an enhanced revisioning system, to create a log file for all changes made by users and/or algorithms concerning metadata attached to specific post types.
While I am perfectly aware that `update_post_meta` works for all post types, while `update_postmeta` just works on post, my question is not dependent on the post type, and it also does not just cover the `update` part, as it is the same for `updated`, `delete`, etc.
After inspectiong `wp-includes/meta.php`, I found the previously mentioned hooks to get my stuff done, but this raised a questions for me.
The section in the core is this one - line 215 in Version 4.4.2:
```
foreach ( $meta_ids as $meta_id ) {
/**
* Fires immediately before updating metadata of a specific type.
*
* The dynamic portion of the hook, `$meta_type`, refers to the meta
* object type (comment, post, or user).
*
* @since 2.9.0
*
* @param int $meta_id ID of the metadata entry to update.
* @param int $object_id Object ID.
* @param string $meta_key Meta key.
* @param mixed $meta_value Meta value.
*/
do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
}
if ( 'post' == $meta_type ) {
foreach ( $meta_ids as $meta_id ) {
/**
* Fires immediately before updating a post's metadata.
*
* @since 2.9.0
*
* @param int $meta_id ID of metadata entry to update.
* @param int $object_id Object ID.
* @param string $meta_key Meta key.
* @param mixed $meta_value Meta value.
*/
do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
}
}
```
So there is a hook for `update_post_meta`, `update_comment_meta`, and `update_user_meta`. Directly after that another hook is called - just for the posts table, named `update_postmeta`, working almost exactly the same way, with the only difference being that the `maybe_serialize()` data of the meta\_value is passed.
Line 204:
```
$_meta_value = $meta_value;
$meta_value = maybe_serialize( $meta_value );
```
At first I thought that the second hook is there for backward compatibility, but both of those were introduced in 2.9.0. [`update_postmeta`](http://adambrown.info/p/wp_hooks/hook/update_postmeta) and [`update_{$meta_type}_meta`](http://adambrown.info/p/wp_hooks/hook/update_%7B$meta_type%7D_meta)
Looking a little bit further, I also found another answer by me, three years ago, where this topic also came up, but this was not the main point.
Am I missing something here?
Is this backward compatibility after all - and has just been moved to `meta.php` in 2.9.0? Or is there any real reason to have both of those? For me, the actions hooked to the `update_post_meta()` function could easily `maybe_unserialize()` the data, if needed, so I really do not see the point of having both.
Looking forward to your input!
|
They were both introduced in version 2.9, but were done so in different files.
`update_postmeta` went into [`/wp-admin/includes/post.php`](http://svn.automattic.com/wordpress/tags/2.9/wp-admin/includes/post.php)
While...
`update_{$meta_type}_meta` went into [`/wp-includes/meta.php`](http://adambrown.info/p/wp_hooks/version/2.9/wp-includes/meta.php)
It was only later that `update_postmeta` was shifted into `/wp-includes/meta.php`.
So I believe it was for backward compatability, where by because the `update_postmeta` hook was always receiving the value of `maybe_serialize()` then it should continue to do so, despite later being moved into `/wp-includes/meta.php`.
Furthermore, which you may already know, but for the sake of others reading, the `update_postmeta` hook returns data from the `$_POST['meta']` superglobal and key which holds data from the [custom fields panel](https://codex.wordpress.org/Custom_Fields).
Could this just have been a poor design decision? Looks like it.
*I thought I recalled some other reason surrounding this very question in relation to double serialization of data, however I could be getting mixed up with something else.*
Interestingly, if you store already serialized data in the Custom Field UI textarea, WordPress will serialize it again before storing it, which supports the notion of backward compatability in relation to:
* <https://core.trac.wordpress.org/ticket/12930>
* <https://nacin.com/2010/04/18/wordpress-serializing-data/>
Note: **this answer is not neccessarily complete**.
|
217,027 |
<p>I have used to following code to change the location of 'single' Wordpress templates.</p>
<pre><code>define(SINGLE_PATH, TEMPLATEPATH.'/single/');
add_filter('single_template', 'lsmwp_custom_single');
function lsmwp_custom_single($single) {
global $wp_query, $post;
if ($post->post_type == "cpt_operator"){
if(file_exists(SINGLE_PATH . '/single-' . $post->post_type . '.php'))
return SINGLE_PATH . '/single-' . $post->post_type . '.php';
}
foreach((array)get_the_category() as $cat) :
if(file_exists(SINGLE_PATH . '/single-cat-' . $cat->slug . '.php'))
return SINGLE_PATH . '/single-cat-' . $cat->slug . '.php';
elseif(file_exists(SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php'))
return SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php';
endforeach;
if(file_exists(SINGLE_PATH . '/single.php'))
return SINGLE_PATH . '/single.php';
elseif(file_exists(SINGLE_PATH . '/default.php'))
return SINGLE_PATH . '/default.php';
return $single;
}
</code></pre>
<p>The function works fine and Worpdress is looking for single templates in the new folder. However if I have <code>WP_DEBUG</code> set to <code>TRUE</code> I receive the following error:</p>
<blockquote>
<p>Use of undefined constant SINGLE_PATH - assumed 'SINGLE_PATH'</p>
</blockquote>
<p>Have I gone wrong with my function somewhere?</p>
|
[
{
"answer_id": 217035,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>You have a lot of issues here. </p>\n\n<ul>\n<li><p>Stay away from defining globals and constants if you can. The global scope is an evil place to be. WordPress has made a huge mess of the global scope already, don't make it a bigger mess than it already is. You can make use a static variable inside your function/filter</p></li>\n<li><p>Avoid using <code>TEMPLATEPATH</code>. You should use <code>get_template_directory_uri()</code>. IIRC, there was a notice somewhere of future depreciation of <code>TEMPLATEPATH</code>, but citation is needed on this as <code>locate_template()</code> for one still uses <code>TEMPLATEPATH</code>. But anyway, use <code>get_template_path_directory_uri()</code> for parent themes, that is the correct way</p></li>\n<li><p>You would want to use <code>locate_template()</code> to search for a specific template, and not <code>file_exists</code>. Let WordPress handle WordPress stuff. Only use PHP (<em>or for that matter custom SQL</em>) if WordPress does not provide a native function/means of doing something. The native functions are there to take care of other stuff that you might be forgetting about when using custom PHP</p>\n\n<p>In the new context, if we use <code>locate_template()</code>, we do not need to use <code>get_template_directory_uir()</code>. <code>locate_template()</code> by default handles that section for us. That is why it is important to use native WordPress functions to handle a specific job</p>\n\n<p>You have a double slash in your generated filenames. Your constant is <code>/single/</code> and your file name is <code>/single.php</code>, which renders <code>/single//single.php</code>. You need to remove a slash in iether of the two to avoid the duplicate slash</p></li>\n<li><p><code>single-{$post_type}.php</code> is by default used for custom post types</p></li>\n<li><p>If you are working with the post object of a single post page outside the loop, rather use <code>get_queried_object()</code> which is much more reliable than the <code>$post</code> global. </p></li>\n<li><p>Although your syntax is valid, it is better to use curly brackets (<code>{}</code>) instead of the <code>:</code> and <code>endforeach</code> syntax. This also goes for the syntax of your conditionl statements. I prefer curlies as they are easy to debug should my code fail</p></li>\n<li><p>If you create a custom hierarchy like you have, always set <code>index.php</code> as your ultimate fallback template as <code>index.php</code> is required by all themes</p></li>\n</ul>\n\n<p>Lets properly rewrite your code (<strong><em>NOTE:</strong> I'm using closures which have the downside that it cannot be removed by <code>remove_filter()</code>, so change it to normal spaghetti if you wish.</em>). We will be using the logic inside <code>get_single_template()</code> to help us here</p>\n\n<p>(<em>The code requires PHP 5.4+ <strike>and is <strong>untested</strong></strike></em>)</p>\n\n<pre><code>add_filter( 'single_template', function ( $template )\n{\n // Get the current single post object\n $post = get_queried_object();\n // Set our 'constant' folder path\n $path = 'single/';\n\n // Set our variable to hold our templates\n $templates = [];\n\n // Lets handle the custom post type section\n if ( 'post' !== $post->post_type ) {\n $templates[] = $path . 'single-' . $post->post_type . '-' . $post->post_name . '.php';\n $templates[] = $path . 'single-' . $post->post_type . '.php';\n }\n\n // Lets handle the post post type stuff\n if ( 'post' === $post->post_type ) {\n // Get the post categories\n $categories = get_the_category( $post->ID );\n // Just for incase, check if we have categories\n if ( $categories ) {\n foreach ( $categories as $category ) {\n // Create possible template names\n $templates[] = $path . 'single-cat-' . $category->slug . '.php';\n $templates[] = $path . 'single-cat-' . $category->term_id . '.php';\n } //endforeach\n } //endif $categories\n } // endif \n\n // Set our fallback templates\n $templates[] = $path . 'single.php';\n $templates[] = $path . 'default.php';\n $templates[] = 'index.php';\n\n /**\n * Now we can search for our templates and load the first one we find\n * We will use the array ability of locate_template here\n */\n $template = locate_template( $templates );\n\n // Return the template rteurned by locate_template\n return $template;\n});\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>The code above is tested and working as expected.</p>\n\n<h2>EDIT 2 - Pre PHP 5.4 (<em>T_Rex still roam the darkness</em>)</h2>\n\n<pre><code>add_filter( 'single_template', function ( $template )\n{\n // Get the current single post object\n $post = get_queried_object();\n // Set our 'constant' folder path\n $path = 'single/';\n\n // Set our variable to hold our templates\n $templates = array();\n\n // Lets handle the custom post type section\n if ( 'post' !== $post->post_type ) {\n $templates[] = $path . 'single-' . $post->post_type . '-' . $post->post_name . '.php';\n $templates[] = $path . 'single-' . $post->post_type . '.php';\n }\n\n // Lets handle the post post type stuff\n if ( 'post' === $post->post_type ) {\n // Get the post categories\n $categories = get_the_category( $post->ID );\n // Just for incase, check if we have categories\n if ( $categories ) {\n foreach ( $categories as $category ) {\n // Create possible template names\n $templates[] = $path . 'single-cat-' . $category->slug . '.php';\n $templates[] = $path . 'single-cat-' . $category->term_id . '.php';\n } //endforeach\n } //endif $categories\n } // endif \n\n // Set our fallback templates\n $templates[] = $path . 'single.php';\n $templates[] = $path . 'default.php';\n $templates[] = 'index.php';\n\n /**\n * Now we can search for our templates and load the first one we find\n * We will use the array ability of locate_template here\n */\n $template = locate_template( $templates );\n\n // Return the template rteurned by locate_template\n return $template;\n});\n</code></pre>\n"
},
{
"answer_id": 217053,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 2,
"selected": false,
"text": "<p>A note about the actual message you're getting from PHP. When you define a constant, you should do it with a string. </p>\n\n<pre><code>define(SINGLE_PATH, TEMPLATEPATH.'/single/');\n</code></pre>\n\n<p>The first parameter is the constant name - when you call <code>define</code> the constant doesn't exist yet.</p>\n\n<p>This would take care of the message from PHP:</p>\n\n<pre><code>define('SINGLE_PATH', TEMPLATEPATH.'/single/');\n</code></pre>\n\n<p>A full example of using a constant:</p>\n\n<pre><code><?php\ndefine( 'SOME_CONSTANT', true );\n\nif ( SOME_CONSTANT ) {\n echo 'Constant was true';\n}\n</code></pre>\n\n<p>Also</p>\n\n<blockquote>\n <p>if I have 'WP_DEBUG' set to TRUE</p>\n</blockquote>\n\n<p>Notice how <code>WP_DEBUG</code> is defined:</p>\n\n<pre><code>define( 'WP_DEBUG', true );\n</code></pre>\n\n<p>But in your code later you would call it without quotes:</p>\n\n<pre><code>var_dump( WP_DEBUG ); // bool(true)\n</code></pre>\n"
},
{
"answer_id": 316965,
"author": "Seth M",
"author_id": 145261,
"author_profile": "https://wordpress.stackexchange.com/users/145261",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using \"template-parts\" folder instead this will work. -function.php</p>\n\n<pre><code>add_filter( 'single_template', function ( $template )\n{\n // Get the current single post object\n $post = get_queried_object();\n // Set our 'constant' folder path\n $path = 'template-parts/';\n\n// Set our variable to hold our templates\n$templates = array();\n\n// Lets handle the custom post type section\nif ( 'post' !== $post->post_type ) {\n $templates[] = $path . 'content-' . $post->post_type . '-' . $post->post_name . '.php';\n $templates[] = $path . 'content-' . $post->post_type . '.php';\n}\n\n// Lets handle the post post type stuff\nif ( 'post' === $post->post_type ) {\n // Get the post categories\n $categories = get_the_category( $post->ID );\n // Just for incase, check if we have categories\n if ( $categories ) {\n foreach ( $categories as $category ) {\n // Create possible template names\n $templates[] = $path . 'content-' . $category->slug . '.php';\n $templates[] = $path . 'content-' . $category->term_id . '.php';\n } //endforeach\n } //endif $categories\n} // endif \n\n// Set our fallback templates\n$templates[] = $path . 'single.php';\n$templates[] = 'index.php';\n\n/**\n * Now we can search for our templates and load the first one we find\n * We will use the array ability of locate_template here\n */\n$template = locate_template( $templates );\n\n// Return the template rteurned by locate_template\nreturn $template;\n});\n</code></pre>\n"
}
] |
2016/02/08
|
[
"https://wordpress.stackexchange.com/questions/217027",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71177/"
] |
I have used to following code to change the location of 'single' Wordpress templates.
```
define(SINGLE_PATH, TEMPLATEPATH.'/single/');
add_filter('single_template', 'lsmwp_custom_single');
function lsmwp_custom_single($single) {
global $wp_query, $post;
if ($post->post_type == "cpt_operator"){
if(file_exists(SINGLE_PATH . '/single-' . $post->post_type . '.php'))
return SINGLE_PATH . '/single-' . $post->post_type . '.php';
}
foreach((array)get_the_category() as $cat) :
if(file_exists(SINGLE_PATH . '/single-cat-' . $cat->slug . '.php'))
return SINGLE_PATH . '/single-cat-' . $cat->slug . '.php';
elseif(file_exists(SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php'))
return SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php';
endforeach;
if(file_exists(SINGLE_PATH . '/single.php'))
return SINGLE_PATH . '/single.php';
elseif(file_exists(SINGLE_PATH . '/default.php'))
return SINGLE_PATH . '/default.php';
return $single;
}
```
The function works fine and Worpdress is looking for single templates in the new folder. However if I have `WP_DEBUG` set to `TRUE` I receive the following error:
>
> Use of undefined constant SINGLE\_PATH - assumed 'SINGLE\_PATH'
>
>
>
Have I gone wrong with my function somewhere?
|
You have a lot of issues here.
* Stay away from defining globals and constants if you can. The global scope is an evil place to be. WordPress has made a huge mess of the global scope already, don't make it a bigger mess than it already is. You can make use a static variable inside your function/filter
* Avoid using `TEMPLATEPATH`. You should use `get_template_directory_uri()`. IIRC, there was a notice somewhere of future depreciation of `TEMPLATEPATH`, but citation is needed on this as `locate_template()` for one still uses `TEMPLATEPATH`. But anyway, use `get_template_path_directory_uri()` for parent themes, that is the correct way
* You would want to use `locate_template()` to search for a specific template, and not `file_exists`. Let WordPress handle WordPress stuff. Only use PHP (*or for that matter custom SQL*) if WordPress does not provide a native function/means of doing something. The native functions are there to take care of other stuff that you might be forgetting about when using custom PHP
In the new context, if we use `locate_template()`, we do not need to use `get_template_directory_uir()`. `locate_template()` by default handles that section for us. That is why it is important to use native WordPress functions to handle a specific job
You have a double slash in your generated filenames. Your constant is `/single/` and your file name is `/single.php`, which renders `/single//single.php`. You need to remove a slash in iether of the two to avoid the duplicate slash
* `single-{$post_type}.php` is by default used for custom post types
* If you are working with the post object of a single post page outside the loop, rather use `get_queried_object()` which is much more reliable than the `$post` global.
* Although your syntax is valid, it is better to use curly brackets (`{}`) instead of the `:` and `endforeach` syntax. This also goes for the syntax of your conditionl statements. I prefer curlies as they are easy to debug should my code fail
* If you create a custom hierarchy like you have, always set `index.php` as your ultimate fallback template as `index.php` is required by all themes
Lets properly rewrite your code (***NOTE:*** I'm using closures which have the downside that it cannot be removed by `remove_filter()`, so change it to normal spaghetti if you wish.). We will be using the logic inside `get_single_template()` to help us here
(*The code requires PHP 5.4+ and is **untested***)
```
add_filter( 'single_template', function ( $template )
{
// Get the current single post object
$post = get_queried_object();
// Set our 'constant' folder path
$path = 'single/';
// Set our variable to hold our templates
$templates = [];
// Lets handle the custom post type section
if ( 'post' !== $post->post_type ) {
$templates[] = $path . 'single-' . $post->post_type . '-' . $post->post_name . '.php';
$templates[] = $path . 'single-' . $post->post_type . '.php';
}
// Lets handle the post post type stuff
if ( 'post' === $post->post_type ) {
// Get the post categories
$categories = get_the_category( $post->ID );
// Just for incase, check if we have categories
if ( $categories ) {
foreach ( $categories as $category ) {
// Create possible template names
$templates[] = $path . 'single-cat-' . $category->slug . '.php';
$templates[] = $path . 'single-cat-' . $category->term_id . '.php';
} //endforeach
} //endif $categories
} // endif
// Set our fallback templates
$templates[] = $path . 'single.php';
$templates[] = $path . 'default.php';
$templates[] = 'index.php';
/**
* Now we can search for our templates and load the first one we find
* We will use the array ability of locate_template here
*/
$template = locate_template( $templates );
// Return the template rteurned by locate_template
return $template;
});
```
EDIT
----
The code above is tested and working as expected.
EDIT 2 - Pre PHP 5.4 (*T\_Rex still roam the darkness*)
-------------------------------------------------------
```
add_filter( 'single_template', function ( $template )
{
// Get the current single post object
$post = get_queried_object();
// Set our 'constant' folder path
$path = 'single/';
// Set our variable to hold our templates
$templates = array();
// Lets handle the custom post type section
if ( 'post' !== $post->post_type ) {
$templates[] = $path . 'single-' . $post->post_type . '-' . $post->post_name . '.php';
$templates[] = $path . 'single-' . $post->post_type . '.php';
}
// Lets handle the post post type stuff
if ( 'post' === $post->post_type ) {
// Get the post categories
$categories = get_the_category( $post->ID );
// Just for incase, check if we have categories
if ( $categories ) {
foreach ( $categories as $category ) {
// Create possible template names
$templates[] = $path . 'single-cat-' . $category->slug . '.php';
$templates[] = $path . 'single-cat-' . $category->term_id . '.php';
} //endforeach
} //endif $categories
} // endif
// Set our fallback templates
$templates[] = $path . 'single.php';
$templates[] = $path . 'default.php';
$templates[] = 'index.php';
/**
* Now we can search for our templates and load the first one we find
* We will use the array ability of locate_template here
*/
$template = locate_template( $templates );
// Return the template rteurned by locate_template
return $template;
});
```
|
217,038 |
<p>I need to see all urls of all publish blog posts in the site. How can I get this?
I want this for redirecting in .htaccess of old site to new site.
This needed in anything page of site.The result is each posts url on a new line.</p>
|
[
{
"answer_id": 217035,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>You have a lot of issues here. </p>\n\n<ul>\n<li><p>Stay away from defining globals and constants if you can. The global scope is an evil place to be. WordPress has made a huge mess of the global scope already, don't make it a bigger mess than it already is. You can make use a static variable inside your function/filter</p></li>\n<li><p>Avoid using <code>TEMPLATEPATH</code>. You should use <code>get_template_directory_uri()</code>. IIRC, there was a notice somewhere of future depreciation of <code>TEMPLATEPATH</code>, but citation is needed on this as <code>locate_template()</code> for one still uses <code>TEMPLATEPATH</code>. But anyway, use <code>get_template_path_directory_uri()</code> for parent themes, that is the correct way</p></li>\n<li><p>You would want to use <code>locate_template()</code> to search for a specific template, and not <code>file_exists</code>. Let WordPress handle WordPress stuff. Only use PHP (<em>or for that matter custom SQL</em>) if WordPress does not provide a native function/means of doing something. The native functions are there to take care of other stuff that you might be forgetting about when using custom PHP</p>\n\n<p>In the new context, if we use <code>locate_template()</code>, we do not need to use <code>get_template_directory_uir()</code>. <code>locate_template()</code> by default handles that section for us. That is why it is important to use native WordPress functions to handle a specific job</p>\n\n<p>You have a double slash in your generated filenames. Your constant is <code>/single/</code> and your file name is <code>/single.php</code>, which renders <code>/single//single.php</code>. You need to remove a slash in iether of the two to avoid the duplicate slash</p></li>\n<li><p><code>single-{$post_type}.php</code> is by default used for custom post types</p></li>\n<li><p>If you are working with the post object of a single post page outside the loop, rather use <code>get_queried_object()</code> which is much more reliable than the <code>$post</code> global. </p></li>\n<li><p>Although your syntax is valid, it is better to use curly brackets (<code>{}</code>) instead of the <code>:</code> and <code>endforeach</code> syntax. This also goes for the syntax of your conditionl statements. I prefer curlies as they are easy to debug should my code fail</p></li>\n<li><p>If you create a custom hierarchy like you have, always set <code>index.php</code> as your ultimate fallback template as <code>index.php</code> is required by all themes</p></li>\n</ul>\n\n<p>Lets properly rewrite your code (<strong><em>NOTE:</strong> I'm using closures which have the downside that it cannot be removed by <code>remove_filter()</code>, so change it to normal spaghetti if you wish.</em>). We will be using the logic inside <code>get_single_template()</code> to help us here</p>\n\n<p>(<em>The code requires PHP 5.4+ <strike>and is <strong>untested</strong></strike></em>)</p>\n\n<pre><code>add_filter( 'single_template', function ( $template )\n{\n // Get the current single post object\n $post = get_queried_object();\n // Set our 'constant' folder path\n $path = 'single/';\n\n // Set our variable to hold our templates\n $templates = [];\n\n // Lets handle the custom post type section\n if ( 'post' !== $post->post_type ) {\n $templates[] = $path . 'single-' . $post->post_type . '-' . $post->post_name . '.php';\n $templates[] = $path . 'single-' . $post->post_type . '.php';\n }\n\n // Lets handle the post post type stuff\n if ( 'post' === $post->post_type ) {\n // Get the post categories\n $categories = get_the_category( $post->ID );\n // Just for incase, check if we have categories\n if ( $categories ) {\n foreach ( $categories as $category ) {\n // Create possible template names\n $templates[] = $path . 'single-cat-' . $category->slug . '.php';\n $templates[] = $path . 'single-cat-' . $category->term_id . '.php';\n } //endforeach\n } //endif $categories\n } // endif \n\n // Set our fallback templates\n $templates[] = $path . 'single.php';\n $templates[] = $path . 'default.php';\n $templates[] = 'index.php';\n\n /**\n * Now we can search for our templates and load the first one we find\n * We will use the array ability of locate_template here\n */\n $template = locate_template( $templates );\n\n // Return the template rteurned by locate_template\n return $template;\n});\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>The code above is tested and working as expected.</p>\n\n<h2>EDIT 2 - Pre PHP 5.4 (<em>T_Rex still roam the darkness</em>)</h2>\n\n<pre><code>add_filter( 'single_template', function ( $template )\n{\n // Get the current single post object\n $post = get_queried_object();\n // Set our 'constant' folder path\n $path = 'single/';\n\n // Set our variable to hold our templates\n $templates = array();\n\n // Lets handle the custom post type section\n if ( 'post' !== $post->post_type ) {\n $templates[] = $path . 'single-' . $post->post_type . '-' . $post->post_name . '.php';\n $templates[] = $path . 'single-' . $post->post_type . '.php';\n }\n\n // Lets handle the post post type stuff\n if ( 'post' === $post->post_type ) {\n // Get the post categories\n $categories = get_the_category( $post->ID );\n // Just for incase, check if we have categories\n if ( $categories ) {\n foreach ( $categories as $category ) {\n // Create possible template names\n $templates[] = $path . 'single-cat-' . $category->slug . '.php';\n $templates[] = $path . 'single-cat-' . $category->term_id . '.php';\n } //endforeach\n } //endif $categories\n } // endif \n\n // Set our fallback templates\n $templates[] = $path . 'single.php';\n $templates[] = $path . 'default.php';\n $templates[] = 'index.php';\n\n /**\n * Now we can search for our templates and load the first one we find\n * We will use the array ability of locate_template here\n */\n $template = locate_template( $templates );\n\n // Return the template rteurned by locate_template\n return $template;\n});\n</code></pre>\n"
},
{
"answer_id": 217053,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 2,
"selected": false,
"text": "<p>A note about the actual message you're getting from PHP. When you define a constant, you should do it with a string. </p>\n\n<pre><code>define(SINGLE_PATH, TEMPLATEPATH.'/single/');\n</code></pre>\n\n<p>The first parameter is the constant name - when you call <code>define</code> the constant doesn't exist yet.</p>\n\n<p>This would take care of the message from PHP:</p>\n\n<pre><code>define('SINGLE_PATH', TEMPLATEPATH.'/single/');\n</code></pre>\n\n<p>A full example of using a constant:</p>\n\n<pre><code><?php\ndefine( 'SOME_CONSTANT', true );\n\nif ( SOME_CONSTANT ) {\n echo 'Constant was true';\n}\n</code></pre>\n\n<p>Also</p>\n\n<blockquote>\n <p>if I have 'WP_DEBUG' set to TRUE</p>\n</blockquote>\n\n<p>Notice how <code>WP_DEBUG</code> is defined:</p>\n\n<pre><code>define( 'WP_DEBUG', true );\n</code></pre>\n\n<p>But in your code later you would call it without quotes:</p>\n\n<pre><code>var_dump( WP_DEBUG ); // bool(true)\n</code></pre>\n"
},
{
"answer_id": 316965,
"author": "Seth M",
"author_id": 145261,
"author_profile": "https://wordpress.stackexchange.com/users/145261",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using \"template-parts\" folder instead this will work. -function.php</p>\n\n<pre><code>add_filter( 'single_template', function ( $template )\n{\n // Get the current single post object\n $post = get_queried_object();\n // Set our 'constant' folder path\n $path = 'template-parts/';\n\n// Set our variable to hold our templates\n$templates = array();\n\n// Lets handle the custom post type section\nif ( 'post' !== $post->post_type ) {\n $templates[] = $path . 'content-' . $post->post_type . '-' . $post->post_name . '.php';\n $templates[] = $path . 'content-' . $post->post_type . '.php';\n}\n\n// Lets handle the post post type stuff\nif ( 'post' === $post->post_type ) {\n // Get the post categories\n $categories = get_the_category( $post->ID );\n // Just for incase, check if we have categories\n if ( $categories ) {\n foreach ( $categories as $category ) {\n // Create possible template names\n $templates[] = $path . 'content-' . $category->slug . '.php';\n $templates[] = $path . 'content-' . $category->term_id . '.php';\n } //endforeach\n } //endif $categories\n} // endif \n\n// Set our fallback templates\n$templates[] = $path . 'single.php';\n$templates[] = 'index.php';\n\n/**\n * Now we can search for our templates and load the first one we find\n * We will use the array ability of locate_template here\n */\n$template = locate_template( $templates );\n\n// Return the template rteurned by locate_template\nreturn $template;\n});\n</code></pre>\n"
}
] |
2016/02/08
|
[
"https://wordpress.stackexchange.com/questions/217038",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88305/"
] |
I need to see all urls of all publish blog posts in the site. How can I get this?
I want this for redirecting in .htaccess of old site to new site.
This needed in anything page of site.The result is each posts url on a new line.
|
You have a lot of issues here.
* Stay away from defining globals and constants if you can. The global scope is an evil place to be. WordPress has made a huge mess of the global scope already, don't make it a bigger mess than it already is. You can make use a static variable inside your function/filter
* Avoid using `TEMPLATEPATH`. You should use `get_template_directory_uri()`. IIRC, there was a notice somewhere of future depreciation of `TEMPLATEPATH`, but citation is needed on this as `locate_template()` for one still uses `TEMPLATEPATH`. But anyway, use `get_template_path_directory_uri()` for parent themes, that is the correct way
* You would want to use `locate_template()` to search for a specific template, and not `file_exists`. Let WordPress handle WordPress stuff. Only use PHP (*or for that matter custom SQL*) if WordPress does not provide a native function/means of doing something. The native functions are there to take care of other stuff that you might be forgetting about when using custom PHP
In the new context, if we use `locate_template()`, we do not need to use `get_template_directory_uir()`. `locate_template()` by default handles that section for us. That is why it is important to use native WordPress functions to handle a specific job
You have a double slash in your generated filenames. Your constant is `/single/` and your file name is `/single.php`, which renders `/single//single.php`. You need to remove a slash in iether of the two to avoid the duplicate slash
* `single-{$post_type}.php` is by default used for custom post types
* If you are working with the post object of a single post page outside the loop, rather use `get_queried_object()` which is much more reliable than the `$post` global.
* Although your syntax is valid, it is better to use curly brackets (`{}`) instead of the `:` and `endforeach` syntax. This also goes for the syntax of your conditionl statements. I prefer curlies as they are easy to debug should my code fail
* If you create a custom hierarchy like you have, always set `index.php` as your ultimate fallback template as `index.php` is required by all themes
Lets properly rewrite your code (***NOTE:*** I'm using closures which have the downside that it cannot be removed by `remove_filter()`, so change it to normal spaghetti if you wish.). We will be using the logic inside `get_single_template()` to help us here
(*The code requires PHP 5.4+ and is **untested***)
```
add_filter( 'single_template', function ( $template )
{
// Get the current single post object
$post = get_queried_object();
// Set our 'constant' folder path
$path = 'single/';
// Set our variable to hold our templates
$templates = [];
// Lets handle the custom post type section
if ( 'post' !== $post->post_type ) {
$templates[] = $path . 'single-' . $post->post_type . '-' . $post->post_name . '.php';
$templates[] = $path . 'single-' . $post->post_type . '.php';
}
// Lets handle the post post type stuff
if ( 'post' === $post->post_type ) {
// Get the post categories
$categories = get_the_category( $post->ID );
// Just for incase, check if we have categories
if ( $categories ) {
foreach ( $categories as $category ) {
// Create possible template names
$templates[] = $path . 'single-cat-' . $category->slug . '.php';
$templates[] = $path . 'single-cat-' . $category->term_id . '.php';
} //endforeach
} //endif $categories
} // endif
// Set our fallback templates
$templates[] = $path . 'single.php';
$templates[] = $path . 'default.php';
$templates[] = 'index.php';
/**
* Now we can search for our templates and load the first one we find
* We will use the array ability of locate_template here
*/
$template = locate_template( $templates );
// Return the template rteurned by locate_template
return $template;
});
```
EDIT
----
The code above is tested and working as expected.
EDIT 2 - Pre PHP 5.4 (*T\_Rex still roam the darkness*)
-------------------------------------------------------
```
add_filter( 'single_template', function ( $template )
{
// Get the current single post object
$post = get_queried_object();
// Set our 'constant' folder path
$path = 'single/';
// Set our variable to hold our templates
$templates = array();
// Lets handle the custom post type section
if ( 'post' !== $post->post_type ) {
$templates[] = $path . 'single-' . $post->post_type . '-' . $post->post_name . '.php';
$templates[] = $path . 'single-' . $post->post_type . '.php';
}
// Lets handle the post post type stuff
if ( 'post' === $post->post_type ) {
// Get the post categories
$categories = get_the_category( $post->ID );
// Just for incase, check if we have categories
if ( $categories ) {
foreach ( $categories as $category ) {
// Create possible template names
$templates[] = $path . 'single-cat-' . $category->slug . '.php';
$templates[] = $path . 'single-cat-' . $category->term_id . '.php';
} //endforeach
} //endif $categories
} // endif
// Set our fallback templates
$templates[] = $path . 'single.php';
$templates[] = $path . 'default.php';
$templates[] = 'index.php';
/**
* Now we can search for our templates and load the first one we find
* We will use the array ability of locate_template here
*/
$template = locate_template( $templates );
// Return the template rteurned by locate_template
return $template;
});
```
|
217,072 |
<p>I'm hoping someone can help me with this seemingly simple problem. </p>
<p>This is a custom theme that I've been given, and simply changing the number of displayed posts in the Settings menu is ineffective(it's set to 10). But I can't tell where the number of post excerpts being displayed on the blog page is set. It's currently one, with a pagination link at the bottom, but I'm trying to expand it to 5.</p>
<p>The page is: <a href="https://community.sum180.com/blog/" rel="nofollow">https://community.sum180.com/blog/</a>
The template is:</p>
<pre><code><?php global $post, $wp_query, $blog_query, $shortcode_values, $theLayout; ?>
<section class="content-post-list">
<ol class="posts-list hfeed">
<?php
if (!$blog_query) $blog_query = $wp_query;
$blogOptions = ($shortcode_values) ? $shortcode_values : $theLayout['blog'];
while( $blog_query->have_posts() ) : $blog_query->the_post();
// style and layout info
$postClass = array();
// images enabled?
if ($blogOptions['blog_featured_images']) {
// class
$postClass[] = ''; //'style-image-left';
// get thumbnail image
$thumb = get_post_thumbnail_id();
// image sizes
$imageW = $blogOptions['image']['width'];
$imageH = $blogOptions['image']['height'];
// crop image (default = true)
$imageCrop = ( $imageW === 0 || $imageH === 0 ) ? false : true; // Setting to FALSE is useful when setting one value so other adjusts automatically
// get resized image
// this will return the resized $thumb or placeholder if enabled and no $thumb
$image = vt_resize( $thumb, '', $imageW, $imageH, $imageCrop );
// If media field is populated use lightbox for image/video on click
$popup_link = '';
if (get_meta('media_url')) {
$popup_link = '<a href="'. get_meta('media_url') .'" class="popup" title="'. get_meta('media_title') .'">';
}
}
if (!$image['url']) {
// no imge
$postClass[] = 'noImage';
}
?>
<li class="post-item clearfix">
<article id="post-<?php the_ID(); ?>" <?php post_class($postClass); ?>>
<div class="item-container">
<?php if ($image['url']) : ?>
<div class="the-post-image">
<?php
if ($popup_link) :
echo $popup_link;
else : ?>
<a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php printf( esc_attr__( 'Permalink to %s', THEME_NAME ), the_title_attribute( 'echo=0' ) ); ?>">
<?php endif; ?>
<figure>
<img src="<?php echo $image['url']; ?>" width="<?php echo $image['width']; ?>" height="<?php echo $image['height']; ?>" />
</figure>
</a>
</div>
<?php endif; ?>
<div class="the-post-content">
<header class="entry-header">
<?php
// Author avatar
if ($blogOptions['author_avatar']) :
?>
<div class="author-avatar">
<a href="<?php echo get_author_posts_url(get_the_author_meta('ID')); ?>"><?php echo get_avatar( get_the_author_meta('ID'), 35, '', get_the_author_meta('display_name')); ?></a>
</div>
<?php
endif; ?>
<!-- Title / Page Headline -->
<h2 class="entry-title"><a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php printf( esc_attr__( 'Permalink to %s', THEME_NAME ), the_title_attribute( 'echo=0' ) ); ?>"><?php the_title(); ?></a></h2>
<?php if ($blogOptions['author_name'] || $blogOptions['post_date'] || $blogOptions['comments_link'] || $blogOptions['category_list']) : ?>
<div class="post-header-info clearfix" <?php if ( !$blogOptions['author_avatar'] ) : echo 'style="margin-left: 0;"'; endif; ?>>
<?php
// Author name
if ($blogOptions['author_name']) :
?>
<address class="vcard author">
<?php _e( 'by ', THEME_NAME ) . the_author_posts_link(); ?>
</address>
<?php
endif;
// Comments link
if ($blogOptions['comments_link']) :
// comments link ?>
<span class="comments-link"><?php comments_popup_link( __( 'Comment', THEME_NAME ), __( '1', THEME_NAME ), __( '%', THEME_NAME ), '', '' ); ?></span>
<?php
endif;
// Category list
if ($blogOptions['category_list']) :
if ( count( get_the_category() ) ) :
?>
<div class="cat-links">
<?php
// seperator
if ($blogOptions['post_date']) { echo ' <span class="meta-sep">|</span> '; }
//printf( __( '<span class="%1$s">Posted in</span> %2$s', THEME_NAME ), 'entry-utility-prep entry-utility-prep-cat-links', get_the_category_list( ', ' ) );
echo get_the_category_list( ', ' );
?>
</div>
<?php
endif;
endif;
// Date Published
if ($blogOptions['post_date']) :
?>
<abbr class="published" title="<?php the_time('c'); ?>"><span class="entry-date"><?php the_time(get_option('date_format')); ?></span></abbr>
<?php
//if ($blogOptions['comments_link']) { echo ' <span class="meta-sep">|</span> '; } // seperator
endif;
?>
</div>
<?php endif; ?>
</header>
<!-- Content -->
<div class="entry-content">
<?php
// Post content/excerpt
if ($blogOptions['use_excerpt']) {
if ($blogOptions['excerpt_length'] != '-1') {
echo customExcerpt(get_the_excerpt(), $blogOptions['excerpt_length']);
}
} else {
// set $more to 0 or WP will ignore the <!--more--> tags if not on the home page
global $more;
$more = 0;
the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', THEME_NAME ) );
}
// Read more link
if ($blogOptions['read_more'] && $blogOptions['read_more'] != "-1") {
$readMore = prep_content($blogOptions['read_more'], 0, 1);
echo '<div class="read-more"><a href="'. get_permalink() .'" title="'. $readMore .'" class="read-more-link">'. $readMore .'</a></div>';
}
?>
</div><!-- END .entry-content -->
<!-- Post Footer -->
<footer class="post-footer-info">
<?php
// tag list
if ($blogOptions['tag_list']) :
$tags_list = get_the_tag_list( '', ', ' );
if ( $tags_list ): ?>
<div class="tag-links">
<?php printf( __( '<span class="%1$s">Tagged</span> %2$s', THEME_NAME ), 'entry-utility-prep entry-utility-prep-tag-links', $tags_list ); ?>
</div>
<?php
endif;
endif; ?>
</footer><!-- END .post-footer-info -->
</div>
</div>
</article>
</li>
<?php endwhile; ?>
</ol>
</section>
<?php
// show paging (< 1 3 4 >)
if ($blogOptions['paging']) get_pagination($blog_query);
?>
</code></pre>
|
[
{
"answer_id": 217077,
"author": "idpokute",
"author_id": 87895,
"author_profile": "https://wordpress.stackexchange.com/users/87895",
"pm_score": -1,
"selected": false,
"text": "<p>Use the following code: </p>\n\n<pre><code>query_posts('posts_per_page=5');\n$blogOptions = ($shortcode_values) ? $shortcode_values : $theLayout['blog'];\n</code></pre>\n"
},
{
"answer_id": 217081,
"author": "Will",
"author_id": 44795,
"author_profile": "https://wordpress.stackexchange.com/users/44795",
"pm_score": 0,
"selected": false,
"text": "<p>That looks like a <a href=\"http://para.llel.us/support/\" rel=\"nofollow\">http://para.llel.us/support/</a> theme. You might start there for docs—for instance, they probably have a custom 'Theme Options' page in the admin.</p>\n\n<p>Short of that, and presuming you're ok with setting it in code (which may negate any future settings in the admin), you'll first need to find out where <code>$blog_query</code> is being defined. You can start in <code>functions.php</code> but it's hard to say without knowing the theme. </p>\n\n<p>Once you find it, either update its <code>posts_per_page</code> value to the value you want or add it manually if it's not there.</p>\n"
}
] |
2016/02/08
|
[
"https://wordpress.stackexchange.com/questions/217072",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35682/"
] |
I'm hoping someone can help me with this seemingly simple problem.
This is a custom theme that I've been given, and simply changing the number of displayed posts in the Settings menu is ineffective(it's set to 10). But I can't tell where the number of post excerpts being displayed on the blog page is set. It's currently one, with a pagination link at the bottom, but I'm trying to expand it to 5.
The page is: <https://community.sum180.com/blog/>
The template is:
```
<?php global $post, $wp_query, $blog_query, $shortcode_values, $theLayout; ?>
<section class="content-post-list">
<ol class="posts-list hfeed">
<?php
if (!$blog_query) $blog_query = $wp_query;
$blogOptions = ($shortcode_values) ? $shortcode_values : $theLayout['blog'];
while( $blog_query->have_posts() ) : $blog_query->the_post();
// style and layout info
$postClass = array();
// images enabled?
if ($blogOptions['blog_featured_images']) {
// class
$postClass[] = ''; //'style-image-left';
// get thumbnail image
$thumb = get_post_thumbnail_id();
// image sizes
$imageW = $blogOptions['image']['width'];
$imageH = $blogOptions['image']['height'];
// crop image (default = true)
$imageCrop = ( $imageW === 0 || $imageH === 0 ) ? false : true; // Setting to FALSE is useful when setting one value so other adjusts automatically
// get resized image
// this will return the resized $thumb or placeholder if enabled and no $thumb
$image = vt_resize( $thumb, '', $imageW, $imageH, $imageCrop );
// If media field is populated use lightbox for image/video on click
$popup_link = '';
if (get_meta('media_url')) {
$popup_link = '<a href="'. get_meta('media_url') .'" class="popup" title="'. get_meta('media_title') .'">';
}
}
if (!$image['url']) {
// no imge
$postClass[] = 'noImage';
}
?>
<li class="post-item clearfix">
<article id="post-<?php the_ID(); ?>" <?php post_class($postClass); ?>>
<div class="item-container">
<?php if ($image['url']) : ?>
<div class="the-post-image">
<?php
if ($popup_link) :
echo $popup_link;
else : ?>
<a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php printf( esc_attr__( 'Permalink to %s', THEME_NAME ), the_title_attribute( 'echo=0' ) ); ?>">
<?php endif; ?>
<figure>
<img src="<?php echo $image['url']; ?>" width="<?php echo $image['width']; ?>" height="<?php echo $image['height']; ?>" />
</figure>
</a>
</div>
<?php endif; ?>
<div class="the-post-content">
<header class="entry-header">
<?php
// Author avatar
if ($blogOptions['author_avatar']) :
?>
<div class="author-avatar">
<a href="<?php echo get_author_posts_url(get_the_author_meta('ID')); ?>"><?php echo get_avatar( get_the_author_meta('ID'), 35, '', get_the_author_meta('display_name')); ?></a>
</div>
<?php
endif; ?>
<!-- Title / Page Headline -->
<h2 class="entry-title"><a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php printf( esc_attr__( 'Permalink to %s', THEME_NAME ), the_title_attribute( 'echo=0' ) ); ?>"><?php the_title(); ?></a></h2>
<?php if ($blogOptions['author_name'] || $blogOptions['post_date'] || $blogOptions['comments_link'] || $blogOptions['category_list']) : ?>
<div class="post-header-info clearfix" <?php if ( !$blogOptions['author_avatar'] ) : echo 'style="margin-left: 0;"'; endif; ?>>
<?php
// Author name
if ($blogOptions['author_name']) :
?>
<address class="vcard author">
<?php _e( 'by ', THEME_NAME ) . the_author_posts_link(); ?>
</address>
<?php
endif;
// Comments link
if ($blogOptions['comments_link']) :
// comments link ?>
<span class="comments-link"><?php comments_popup_link( __( 'Comment', THEME_NAME ), __( '1', THEME_NAME ), __( '%', THEME_NAME ), '', '' ); ?></span>
<?php
endif;
// Category list
if ($blogOptions['category_list']) :
if ( count( get_the_category() ) ) :
?>
<div class="cat-links">
<?php
// seperator
if ($blogOptions['post_date']) { echo ' <span class="meta-sep">|</span> '; }
//printf( __( '<span class="%1$s">Posted in</span> %2$s', THEME_NAME ), 'entry-utility-prep entry-utility-prep-cat-links', get_the_category_list( ', ' ) );
echo get_the_category_list( ', ' );
?>
</div>
<?php
endif;
endif;
// Date Published
if ($blogOptions['post_date']) :
?>
<abbr class="published" title="<?php the_time('c'); ?>"><span class="entry-date"><?php the_time(get_option('date_format')); ?></span></abbr>
<?php
//if ($blogOptions['comments_link']) { echo ' <span class="meta-sep">|</span> '; } // seperator
endif;
?>
</div>
<?php endif; ?>
</header>
<!-- Content -->
<div class="entry-content">
<?php
// Post content/excerpt
if ($blogOptions['use_excerpt']) {
if ($blogOptions['excerpt_length'] != '-1') {
echo customExcerpt(get_the_excerpt(), $blogOptions['excerpt_length']);
}
} else {
// set $more to 0 or WP will ignore the <!--more--> tags if not on the home page
global $more;
$more = 0;
the_content( __( 'Continue reading <span class="meta-nav">→</span>', THEME_NAME ) );
}
// Read more link
if ($blogOptions['read_more'] && $blogOptions['read_more'] != "-1") {
$readMore = prep_content($blogOptions['read_more'], 0, 1);
echo '<div class="read-more"><a href="'. get_permalink() .'" title="'. $readMore .'" class="read-more-link">'. $readMore .'</a></div>';
}
?>
</div><!-- END .entry-content -->
<!-- Post Footer -->
<footer class="post-footer-info">
<?php
// tag list
if ($blogOptions['tag_list']) :
$tags_list = get_the_tag_list( '', ', ' );
if ( $tags_list ): ?>
<div class="tag-links">
<?php printf( __( '<span class="%1$s">Tagged</span> %2$s', THEME_NAME ), 'entry-utility-prep entry-utility-prep-tag-links', $tags_list ); ?>
</div>
<?php
endif;
endif; ?>
</footer><!-- END .post-footer-info -->
</div>
</div>
</article>
</li>
<?php endwhile; ?>
</ol>
</section>
<?php
// show paging (< 1 3 4 >)
if ($blogOptions['paging']) get_pagination($blog_query);
?>
```
|
That looks like a <http://para.llel.us/support/> theme. You might start there for docs—for instance, they probably have a custom 'Theme Options' page in the admin.
Short of that, and presuming you're ok with setting it in code (which may negate any future settings in the admin), you'll first need to find out where `$blog_query` is being defined. You can start in `functions.php` but it's hard to say without knowing the theme.
Once you find it, either update its `posts_per_page` value to the value you want or add it manually if it's not there.
|
217,075 |
<p>I currently use <code>Post name</code> for the permalink structure. I want to add text from a field at the end of the permalink. Is there any hook for the permalink creation when a <code>Post</code> is published?</p>
<p>In my case, I use <code>Advanced Custom Fields</code> and every post has a Title and Subtitle. Currently, the permalink is <code>/title/</code> but I wanted to be <code>/title-subtitle/</code>.</p>
<p><strong>Edit:</strong> similar to this <a href="https://wordpress.stackexchange.com/questions/105926/rewriting-post-slug-before-post-save">previous question</a>, except that I only want to do it for post creation and not on future post editions, since this will modify the URL of the post which is a disaster for SEO.</p>
|
[
{
"answer_id": 217079,
"author": "stoopkid1",
"author_id": 55193,
"author_profile": "https://wordpress.stackexchange.com/users/55193",
"pm_score": -1,
"selected": false,
"text": "<p>in your functions.php file, you should be able to accomplish your desired functionality with something like this:</p>\n\n<pre><code>function adjust_permalinks() {\n global $wp_rewrite;\n $title = get_field( 'title_field' );\n $subtitle = get_field( 'sub_title_field' );\n $wp_rewrite->set_permalink_structure( $title . '-' . $subtitle );\n $wp_rewrite->flush_rules();\n}\nadd_action('init', 'adjust_permalinks');\n</code></pre>\n\n<p>this will set your permalink structure to always use the $title & $subtitle</p>\n"
},
{
"answer_id": 217101,
"author": "IvanRF",
"author_id": 59235,
"author_profile": "https://wordpress.stackexchange.com/users/59235",
"pm_score": 5,
"selected": true,
"text": "<p>Here is what I did to implement this:</p>\n\n<pre><code>function slug_save_post_callback( $post_ID, $post, $update ) {\n // allow 'publish', 'draft', 'future'\n if ($post->post_type != 'post' || $post->post_status == 'auto-draft')\n return;\n\n // only change slug when the post is created (both dates are equal)\n if ($post->post_date_gmt != $post->post_modified_gmt)\n return;\n\n // use title, since $post->post_name might have unique numbers added\n $new_slug = sanitize_title( $post->post_title, $post_ID );\n $subtitle = sanitize_title( get_field( 'subtitle', $post_ID ), '' );\n if (empty( $subtitle ) || strpos( $new_slug, $subtitle ) !== false)\n return; // No subtitle or already in slug\n\n $new_slug .= '-' . $subtitle;\n if ($new_slug == $post->post_name)\n return; // already set\n\n // unhook this function to prevent infinite looping\n remove_action( 'save_post', 'slug_save_post_callback', 10, 3 );\n // update the post slug (WP handles unique post slug)\n wp_update_post( array(\n 'ID' => $post_ID,\n 'post_name' => $new_slug\n ));\n // re-hook this function\n add_action( 'save_post', 'slug_save_post_callback', 10, 3 );\n}\nadd_action( 'save_post', 'slug_save_post_callback', 10, 3 );\n</code></pre>\n\n<p>It generates and updates the <code>slug</code>. Previous slug generated by WP can not be reused since it can have unique numbers if the title/slug was already used in another post. So, I sanitize the title. Then, <code>wp_update_post</code> makes sure there are no duplicates for the new slug with <code>wp_unique_post_slug</code>.</p>\n\n<p>The only way I could find to only do this on publish is to compare the creation and the modified time. They are only equal when the post is created. The <code>$update</code> parameter is useless, since is <code>true</code> for the publish.</p>\n"
}
] |
2016/02/08
|
[
"https://wordpress.stackexchange.com/questions/217075",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/59235/"
] |
I currently use `Post name` for the permalink structure. I want to add text from a field at the end of the permalink. Is there any hook for the permalink creation when a `Post` is published?
In my case, I use `Advanced Custom Fields` and every post has a Title and Subtitle. Currently, the permalink is `/title/` but I wanted to be `/title-subtitle/`.
**Edit:** similar to this [previous question](https://wordpress.stackexchange.com/questions/105926/rewriting-post-slug-before-post-save), except that I only want to do it for post creation and not on future post editions, since this will modify the URL of the post which is a disaster for SEO.
|
Here is what I did to implement this:
```
function slug_save_post_callback( $post_ID, $post, $update ) {
// allow 'publish', 'draft', 'future'
if ($post->post_type != 'post' || $post->post_status == 'auto-draft')
return;
// only change slug when the post is created (both dates are equal)
if ($post->post_date_gmt != $post->post_modified_gmt)
return;
// use title, since $post->post_name might have unique numbers added
$new_slug = sanitize_title( $post->post_title, $post_ID );
$subtitle = sanitize_title( get_field( 'subtitle', $post_ID ), '' );
if (empty( $subtitle ) || strpos( $new_slug, $subtitle ) !== false)
return; // No subtitle or already in slug
$new_slug .= '-' . $subtitle;
if ($new_slug == $post->post_name)
return; // already set
// unhook this function to prevent infinite looping
remove_action( 'save_post', 'slug_save_post_callback', 10, 3 );
// update the post slug (WP handles unique post slug)
wp_update_post( array(
'ID' => $post_ID,
'post_name' => $new_slug
));
// re-hook this function
add_action( 'save_post', 'slug_save_post_callback', 10, 3 );
}
add_action( 'save_post', 'slug_save_post_callback', 10, 3 );
```
It generates and updates the `slug`. Previous slug generated by WP can not be reused since it can have unique numbers if the title/slug was already used in another post. So, I sanitize the title. Then, `wp_update_post` makes sure there are no duplicates for the new slug with `wp_unique_post_slug`.
The only way I could find to only do this on publish is to compare the creation and the modified time. They are only equal when the post is created. The `$update` parameter is useless, since is `true` for the publish.
|
217,097 |
<p>Is possible to check if has any sidebar active on current page?</p>
<p>Like this:</p>
<p>@edit</p>
<p><em>This function also return true even if the current page does not have this sidebar active...</em></p>
<pre><code><?php if(is_active_sidebar('sidebar-1')) {
// sidebar-1 is active...
} ?>
</code></pre>
<p>But I need to check if has any sidebar active (without specify sidebar name ), and I need to check only to current page, not for all pages, like:</p>
<pre><code><?php if(any_sidebar_active_on_this_page()) {
// has sidebar active on this specific page, do something...
} ?>
</code></pre>
|
[
{
"answer_id": 217281,
"author": "Sterling Hamilton",
"author_id": 10075,
"author_profile": "https://wordpress.stackexchange.com/users/10075",
"pm_score": 2,
"selected": false,
"text": "<p>I believe the issue here is a problem with vernacular.</p>\n\n<p><code>is_active_sidebar</code> isn't page specific -- just checks to see if it has data within it throughout the entire site.</p>\n\n<p>You are asking a different question.\nSounds like you are asking \"does this template reference and sidebars AND do any of those sidebars have data in them,?\" it also sounds like you don't want to reference the sidebar names at all and you'd like this to be a generic question across the board.</p>\n\n<p>That last bit makes this difficult and can potentially turn this into an architectural problem -- not a WordPress problem. Think of WordPress as a waiter -- it just takes your orders and gets you results. It wasn't built for you to ask questions like \"is anyone in the restaurant eating steak?\" -- so it doesn't have anything for you there.</p>\n\n<p>You COULD tie into <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/dynamic_sidebar\" rel=\"nofollow\">https://codex.wordpress.org/Plugin_API/Action_Reference/dynamic_sidebar</a></p>\n\n<p>Then you could set a variable or call a function anytime someone calls a sidebar that has data in it -- this would allow you to react in those moments.</p>\n"
},
{
"answer_id": 288502,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": 0,
"selected": false,
"text": "<pre><code>foreach ( $GLOBALS['wp_registered_sidebars'] as $sidebar ) { \n if(is_active_sidebar($sidebar['name'])) {\n // $sidebar['name'] is active...\n }\n}\n</code></pre>\n\n<p>This will loop through the list of registered sidebars and then check on every page load if any of them exists.</p>\n"
}
] |
2016/02/09
|
[
"https://wordpress.stackexchange.com/questions/217097",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/39187/"
] |
Is possible to check if has any sidebar active on current page?
Like this:
@edit
*This function also return true even if the current page does not have this sidebar active...*
```
<?php if(is_active_sidebar('sidebar-1')) {
// sidebar-1 is active...
} ?>
```
But I need to check if has any sidebar active (without specify sidebar name ), and I need to check only to current page, not for all pages, like:
```
<?php if(any_sidebar_active_on_this_page()) {
// has sidebar active on this specific page, do something...
} ?>
```
|
I believe the issue here is a problem with vernacular.
`is_active_sidebar` isn't page specific -- just checks to see if it has data within it throughout the entire site.
You are asking a different question.
Sounds like you are asking "does this template reference and sidebars AND do any of those sidebars have data in them,?" it also sounds like you don't want to reference the sidebar names at all and you'd like this to be a generic question across the board.
That last bit makes this difficult and can potentially turn this into an architectural problem -- not a WordPress problem. Think of WordPress as a waiter -- it just takes your orders and gets you results. It wasn't built for you to ask questions like "is anyone in the restaurant eating steak?" -- so it doesn't have anything for you there.
You COULD tie into <https://codex.wordpress.org/Plugin_API/Action_Reference/dynamic_sidebar>
Then you could set a variable or call a function anytime someone calls a sidebar that has data in it -- this would allow you to react in those moments.
|
217,103 |
<p>I am using AngularJS to load a list of my WordPress posts, however I can not get any of my PHP functions to work with my partials file. </p>
<p>I've tried using something such as <code>search.php</code> instead of <code>search.html</code> but when doing so I get errors such as fatal error get_post_meta is undefined. </p>
<p>Now I know we are not suppose to mix client side with server side, and I can possibly use some kind of service to parse my PHP, but I have no idea how to go about it. I need my <code>search.php</code> to render my PHP tags so I can display custom fields, and use several PHP functions I have there. </p>
<p>Whats the best way of doing this?</p>
<p>On my page template (<code>.php</code>) I have --</p>
<pre><code><div id="page" ng-app="app">
<header>
<h1>
<a href="<?php echo home_url(); ?>">Search</a>
</h1>
</header>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<div ng-Cloak ng-controller="MyController" class="my-controller">
<div ng-view></div>
</div>
<?php endwhile; ?>
<?php endif; ?>
<?php rewind_posts(); ?>
<div ng-controller="OtherController" class="other-controller">
<div class="text-center">
<dir-pagination-controls boundary-links="true" on-page-change="pageChangeHandler(newPageNumber)" template-url="/partials/dirPagination.tpl.html"></dir-pagination-controls>
</div>
</div>
<footer>
&copy; <?php echo date( 'Y' ); ?>
</footer>
</div>
</code></pre>
<p>And on my PHP file I want to be called into view has functions such as --</p>
<pre><code><?php
$pcomp1b = get_post_meta(get_the_ID(), 'pa_meta_comp1b', true);
$pcomp1c = get_post_meta(get_the_ID(), 'pa_meta_comp1c', true);
$pcomp1d = get_post_meta(get_the_ID(), 'pa_meta_comp1d', true); ?>
</code></pre>
<p>Math --
<pre><code>if( is_numeric( $price1 ) ) {
$a1 = $price1;
}
$b1 = $pcomp1d;
$sqft1 = str_replace( ',', '', $b1 );
if( is_numeric( $sqft1 ) ) {
$b1 = $sqft1;
}
$a2 = $pcomp2f;
$price2 = str_replace( ',', '', $a2 );
if( is_numeric( $price2 ) ) {
$a2 = $price2;
}
$b2 = $pcomp2d;
$sqft2 = str_replace( ',', '', $b2 );
if( is_numeric( $sqft2 ) ) {
$b2 = $sqft2;
}
$a3 = $pcomp3f;
$price3 = str_replace( ',', '', $a3 );
if( is_numeric( $price3 ) ) {
$a3 = $price3;
}
$b3 = $pcomp3d;
$sqft3 = str_replace( ',', '', $b3 );
if( is_numeric( $sqft3 ) ) {
$b3 = $sqft3;
}
$ppsqft1 = ROUND($price1 / $sqft1);
$ppsqft2 = ROUND($price2 / $sqft2);
$ppsqft3 = ROUND($price3 / $sqft3);
$ppsav = ROUND((($ppsqft1 + $ppsqft2 + $ppsqft3)/3));
$b4 = $property_area;
$parea = str_replace( ',', '', $b4 );
if( is_numeric( $parea ) ) {
$b4 = $parea;
}
$ehvp = $ppsav * $parea;
$homevalue = number_format($ehvp, 0, '.', ',');
echo '$' . $homevalue; ?>
</code></pre>
<p>And functions -- </p>
<pre><code><?php if (class_exists('MRP_Multi_Rating_API')){ MRP_Multi_Rating_API::display_rating_result(array('rating_item_ids' => 2, 'show_count' => false, 'result_type' => 'value_rt', 'no_rating_results_text' => 'N/A'));} ?>
</code></pre>
<p>So how can I get this to work with <code>ng-view</code> and my partials templates?</p>
<p><strong>UPDATE</strong></p>
<p>This is what my current setup looks like --
First I have a page template called search-results.php -</p>
<pre><code><?php
/* Template Name:Search Results */ ?>
<!DOCTYPE html>
<html>
<head>
<base href="<?php $url_info = parse_url( home_url() ); echo trailingslashit( $url_info['path'] ); ?>">
<title>Search</title>
<link rel="stylesheet" type="text/css" href="/style.css" media="print" />
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.3.0.min.js"></script>
<?php wp_head(); ?>
</head>
<body>
<div id="page" ng-app="app">
<header>
<h1>
<a href="<?php echo home_url(); ?>">Search</a>
</h1>
</header>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<div ng-Cloak ng-controller="MyController" class="my-controller">
<div ng-view></div></div>
<?php endwhile; ?>
<?php endif; ?>
<?php rewind_posts(); ?>
<div ng-controller="OtherController" class="other-controller">
<div class="text-center">
<dir-pagination-controls boundary-links="true" on-page-change="pageChangeHandler(newPageNumber)" template-url="/partials/dirPagination.tpl.html"></dir-pagination-controls>
</div>
</div>
<footer>
&copy; <?php echo date( 'Y' ); ?>
</footer>
</div>
<script>
function getdata($scope,$http){
$http.get("/wp-json/posts?type=property")
.success(function(data)
{$scope.result = data;}
);
}
</script>
<?php wp_footer(); ?>
</body>
</html>
</code></pre>
<p>Then my app script without calling the php file as a partial --</p>
<pre><code>var app = angular.module('app', ['ngRoute', 'ngSanitize', 'angularUtils.directives.dirPagination'])
function MyController($scope) {
$scope.currentPage = 1;
$scope.pageSize = 2;
$scope.posts = [];
$scope.pageChangeHandler = function(num) {
console.log('search page changed to ' + num);
};
}
function OtherController($scope) {
$scope.pageChangeHandler = function(num) {
console.log('going to page ' + num);
};
}
app.config(function(paginationTemplateProvider) {
paginationTemplateProvider.setPath('/partials/dirPagination.tpl.html');
});
app.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/search-results', {
templateUrl: myLocalized.partials + 'main.html',
controller: 'Main'
})
.when('/:ID', {
templateUrl: myLocalized.partials + 'content.html',
controller: 'Content'
});
})
app.controller('Main', function($scope, $http, $routeParams) {
$http.get('wp-json/posts?type=property').success(function(res){
$scope.posts = res;
});
})
app.controller('Content', function($scope, $http, $routeParams) {
$http.get('wp-json/posts?type=property/?filter["posts_per_page"]=25&filter["orderby"]=date&filter["order"]=desc/' + $routeParams.ID).success(function(res){
$scope.post = res;
});
});
app.controller('MyController', MyController);
app.controller('OtherController', OtherController);
</code></pre>
<p>Then the partial file will be a search.php file with the functions and code shown in my original question.</p>
|
[
{
"answer_id": 217281,
"author": "Sterling Hamilton",
"author_id": 10075,
"author_profile": "https://wordpress.stackexchange.com/users/10075",
"pm_score": 2,
"selected": false,
"text": "<p>I believe the issue here is a problem with vernacular.</p>\n\n<p><code>is_active_sidebar</code> isn't page specific -- just checks to see if it has data within it throughout the entire site.</p>\n\n<p>You are asking a different question.\nSounds like you are asking \"does this template reference and sidebars AND do any of those sidebars have data in them,?\" it also sounds like you don't want to reference the sidebar names at all and you'd like this to be a generic question across the board.</p>\n\n<p>That last bit makes this difficult and can potentially turn this into an architectural problem -- not a WordPress problem. Think of WordPress as a waiter -- it just takes your orders and gets you results. It wasn't built for you to ask questions like \"is anyone in the restaurant eating steak?\" -- so it doesn't have anything for you there.</p>\n\n<p>You COULD tie into <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/dynamic_sidebar\" rel=\"nofollow\">https://codex.wordpress.org/Plugin_API/Action_Reference/dynamic_sidebar</a></p>\n\n<p>Then you could set a variable or call a function anytime someone calls a sidebar that has data in it -- this would allow you to react in those moments.</p>\n"
},
{
"answer_id": 288502,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": 0,
"selected": false,
"text": "<pre><code>foreach ( $GLOBALS['wp_registered_sidebars'] as $sidebar ) { \n if(is_active_sidebar($sidebar['name'])) {\n // $sidebar['name'] is active...\n }\n}\n</code></pre>\n\n<p>This will loop through the list of registered sidebars and then check on every page load if any of them exists.</p>\n"
}
] |
2016/02/09
|
[
"https://wordpress.stackexchange.com/questions/217103",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24067/"
] |
I am using AngularJS to load a list of my WordPress posts, however I can not get any of my PHP functions to work with my partials file.
I've tried using something such as `search.php` instead of `search.html` but when doing so I get errors such as fatal error get\_post\_meta is undefined.
Now I know we are not suppose to mix client side with server side, and I can possibly use some kind of service to parse my PHP, but I have no idea how to go about it. I need my `search.php` to render my PHP tags so I can display custom fields, and use several PHP functions I have there.
Whats the best way of doing this?
On my page template (`.php`) I have --
```
<div id="page" ng-app="app">
<header>
<h1>
<a href="<?php echo home_url(); ?>">Search</a>
</h1>
</header>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<div ng-Cloak ng-controller="MyController" class="my-controller">
<div ng-view></div>
</div>
<?php endwhile; ?>
<?php endif; ?>
<?php rewind_posts(); ?>
<div ng-controller="OtherController" class="other-controller">
<div class="text-center">
<dir-pagination-controls boundary-links="true" on-page-change="pageChangeHandler(newPageNumber)" template-url="/partials/dirPagination.tpl.html"></dir-pagination-controls>
</div>
</div>
<footer>
© <?php echo date( 'Y' ); ?>
</footer>
</div>
```
And on my PHP file I want to be called into view has functions such as --
```
<?php
$pcomp1b = get_post_meta(get_the_ID(), 'pa_meta_comp1b', true);
$pcomp1c = get_post_meta(get_the_ID(), 'pa_meta_comp1c', true);
$pcomp1d = get_post_meta(get_the_ID(), 'pa_meta_comp1d', true); ?>
```
Math --
```
if( is_numeric( $price1 ) ) {
$a1 = $price1;
}
$b1 = $pcomp1d;
$sqft1 = str_replace( ',', '', $b1 );
if( is_numeric( $sqft1 ) ) {
$b1 = $sqft1;
}
$a2 = $pcomp2f;
$price2 = str_replace( ',', '', $a2 );
if( is_numeric( $price2 ) ) {
$a2 = $price2;
}
$b2 = $pcomp2d;
$sqft2 = str_replace( ',', '', $b2 );
if( is_numeric( $sqft2 ) ) {
$b2 = $sqft2;
}
$a3 = $pcomp3f;
$price3 = str_replace( ',', '', $a3 );
if( is_numeric( $price3 ) ) {
$a3 = $price3;
}
$b3 = $pcomp3d;
$sqft3 = str_replace( ',', '', $b3 );
if( is_numeric( $sqft3 ) ) {
$b3 = $sqft3;
}
$ppsqft1 = ROUND($price1 / $sqft1);
$ppsqft2 = ROUND($price2 / $sqft2);
$ppsqft3 = ROUND($price3 / $sqft3);
$ppsav = ROUND((($ppsqft1 + $ppsqft2 + $ppsqft3)/3));
$b4 = $property_area;
$parea = str_replace( ',', '', $b4 );
if( is_numeric( $parea ) ) {
$b4 = $parea;
}
$ehvp = $ppsav * $parea;
$homevalue = number_format($ehvp, 0, '.', ',');
echo '$' . $homevalue; ?>
```
And functions --
```
<?php if (class_exists('MRP_Multi_Rating_API')){ MRP_Multi_Rating_API::display_rating_result(array('rating_item_ids' => 2, 'show_count' => false, 'result_type' => 'value_rt', 'no_rating_results_text' => 'N/A'));} ?>
```
So how can I get this to work with `ng-view` and my partials templates?
**UPDATE**
This is what my current setup looks like --
First I have a page template called search-results.php -
```
<?php
/* Template Name:Search Results */ ?>
<!DOCTYPE html>
<html>
<head>
<base href="<?php $url_info = parse_url( home_url() ); echo trailingslashit( $url_info['path'] ); ?>">
<title>Search</title>
<link rel="stylesheet" type="text/css" href="/style.css" media="print" />
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.3.0.min.js"></script>
<?php wp_head(); ?>
</head>
<body>
<div id="page" ng-app="app">
<header>
<h1>
<a href="<?php echo home_url(); ?>">Search</a>
</h1>
</header>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<div ng-Cloak ng-controller="MyController" class="my-controller">
<div ng-view></div></div>
<?php endwhile; ?>
<?php endif; ?>
<?php rewind_posts(); ?>
<div ng-controller="OtherController" class="other-controller">
<div class="text-center">
<dir-pagination-controls boundary-links="true" on-page-change="pageChangeHandler(newPageNumber)" template-url="/partials/dirPagination.tpl.html"></dir-pagination-controls>
</div>
</div>
<footer>
© <?php echo date( 'Y' ); ?>
</footer>
</div>
<script>
function getdata($scope,$http){
$http.get("/wp-json/posts?type=property")
.success(function(data)
{$scope.result = data;}
);
}
</script>
<?php wp_footer(); ?>
</body>
</html>
```
Then my app script without calling the php file as a partial --
```
var app = angular.module('app', ['ngRoute', 'ngSanitize', 'angularUtils.directives.dirPagination'])
function MyController($scope) {
$scope.currentPage = 1;
$scope.pageSize = 2;
$scope.posts = [];
$scope.pageChangeHandler = function(num) {
console.log('search page changed to ' + num);
};
}
function OtherController($scope) {
$scope.pageChangeHandler = function(num) {
console.log('going to page ' + num);
};
}
app.config(function(paginationTemplateProvider) {
paginationTemplateProvider.setPath('/partials/dirPagination.tpl.html');
});
app.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/search-results', {
templateUrl: myLocalized.partials + 'main.html',
controller: 'Main'
})
.when('/:ID', {
templateUrl: myLocalized.partials + 'content.html',
controller: 'Content'
});
})
app.controller('Main', function($scope, $http, $routeParams) {
$http.get('wp-json/posts?type=property').success(function(res){
$scope.posts = res;
});
})
app.controller('Content', function($scope, $http, $routeParams) {
$http.get('wp-json/posts?type=property/?filter["posts_per_page"]=25&filter["orderby"]=date&filter["order"]=desc/' + $routeParams.ID).success(function(res){
$scope.post = res;
});
});
app.controller('MyController', MyController);
app.controller('OtherController', OtherController);
```
Then the partial file will be a search.php file with the functions and code shown in my original question.
|
I believe the issue here is a problem with vernacular.
`is_active_sidebar` isn't page specific -- just checks to see if it has data within it throughout the entire site.
You are asking a different question.
Sounds like you are asking "does this template reference and sidebars AND do any of those sidebars have data in them,?" it also sounds like you don't want to reference the sidebar names at all and you'd like this to be a generic question across the board.
That last bit makes this difficult and can potentially turn this into an architectural problem -- not a WordPress problem. Think of WordPress as a waiter -- it just takes your orders and gets you results. It wasn't built for you to ask questions like "is anyone in the restaurant eating steak?" -- so it doesn't have anything for you there.
You COULD tie into <https://codex.wordpress.org/Plugin_API/Action_Reference/dynamic_sidebar>
Then you could set a variable or call a function anytime someone calls a sidebar that has data in it -- this would allow you to react in those moments.
|
217,116 |
<p>Could you please let me know wordpress action hook that must triggered only once when a user create a new custom post.</p>
<p>That means if user creates a new post that hook must be triggered but when user update or edit the post then that hook should not be executed.</p>
<p>Previously i was using publish_post but it always executed when user create, edit or update the post however i have added some conditions to prevent this action but didn't works for me.</p>
<p>The code is as follow:</p>
<pre><code>add_action( 'publish_property', 'pms_post_published_notification', 10, 2 );
function pms_post_published_notification( $ID, $post ) {
if(get_post_field('post_type',$ID ) === 'property' && !wp_is_post_revision( $ID )){// custom code here}
</code></pre>
|
[
{
"answer_id": 217120,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 2,
"selected": false,
"text": "<p>You have to use <code>new_to_publish</code> action as described on <a href=\"https://codex.wordpress.org/Post_Status_Transitions\" rel=\"nofollow noreferrer\">Post Status Transitions</a> Codex page (updated according @prog comment):</p>\n<pre><code>add_action( 'new_to_publish', 'pms_post_published_notification', 10, 1 );\n\nfunction pms_post_published_notification( $post ) {\n if( 'property' === $post->post_type ) {\n // custom code here\n }\n}\n</code></pre>\n<p>The only argument is passed to your function is <code>$post</code> object, so you can utilize it to check the post type.</p>\n<ul>\n<li><a href=\"https://codex.wordpress.org/Post_Status_Transitions\" rel=\"nofollow noreferrer\">Post Status Transitions</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/old_status_to_new_status/\" rel=\"nofollow noreferrer\">{$old_status}_to_{$new_status}</a> action</li>\n</ul>\n"
},
{
"answer_id": 217123,
"author": "tinku",
"author_id": 74154,
"author_profile": "https://wordpress.stackexchange.com/users/74154",
"pm_score": 0,
"selected": false,
"text": "<p>However the below given code works for me.</p>\n\n<pre><code>add_action( 'new_to_publish', 'pms_post_published_notification', 10, 1 );\n\nfunction pms_post_published_notification( $post ) {\n if($post->post_type == 'property') {\n // custom code here\n }\n}\n</code></pre>\n\n<p>Thanks @Max</p>\n"
},
{
"answer_id": 217132,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 1,
"selected": false,
"text": "<p>You can always make use of the more global <a href=\"https://developer.wordpress.org/reference/hooks/transition_post_status/\" rel=\"nofollow\"><code>transition_post_status</code></a> action hook which fires on every transition status for all post types. </p>\n\n<p>Three values are passed by reference to the hook </p>\n\n<ul>\n<li><p><code>$new_status</code> which is the post status the post will have after transition</p></li>\n<li><p><code>$old_status</code> which is the post status the post had before transitioning</p></li>\n<li><p><code>$post</code> which is the current post object of the post being transitioned</p></li>\n</ul>\n\n<p>Because a new post does not have any concrete set old post status, and definitely does not have an old status of publish, we can use that as logic to test against and then run our custom code based on that</p>\n\n<pre><code>add_action( 'transition_post_status', function ( $new_status, $old_status, $post )\n{\n if ( 'publish' === $new_status\n && 'publish' !== $old_status\n && 'property' === $post->post_type\n ) {\n // This is a new property post, lets do some work\n // Run your custom code here\n }\n}, 10, 3 ); \n</code></pre>\n"
}
] |
2016/02/09
|
[
"https://wordpress.stackexchange.com/questions/217116",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74154/"
] |
Could you please let me know wordpress action hook that must triggered only once when a user create a new custom post.
That means if user creates a new post that hook must be triggered but when user update or edit the post then that hook should not be executed.
Previously i was using publish\_post but it always executed when user create, edit or update the post however i have added some conditions to prevent this action but didn't works for me.
The code is as follow:
```
add_action( 'publish_property', 'pms_post_published_notification', 10, 2 );
function pms_post_published_notification( $ID, $post ) {
if(get_post_field('post_type',$ID ) === 'property' && !wp_is_post_revision( $ID )){// custom code here}
```
|
You have to use `new_to_publish` action as described on [Post Status Transitions](https://codex.wordpress.org/Post_Status_Transitions) Codex page (updated according @prog comment):
```
add_action( 'new_to_publish', 'pms_post_published_notification', 10, 1 );
function pms_post_published_notification( $post ) {
if( 'property' === $post->post_type ) {
// custom code here
}
}
```
The only argument is passed to your function is `$post` object, so you can utilize it to check the post type.
* [Post Status Transitions](https://codex.wordpress.org/Post_Status_Transitions)
* [{$old\_status}\_to\_{$new\_status}](https://developer.wordpress.org/reference/hooks/old_status_to_new_status/) action
|
217,125 |
<p>I found here on WPSE that you can <a href="https://wordpress.stackexchange.com/questions/140319/add-content-before-after-admin-post-wp-list-table">add content before post title</a> in the post page, and in custom post type pages</p>
<pre><code> add_action( 'load-edit.php', function(){
$screen = get_current_screen();
// Only edit post screen:
if( 'edit-reservation' === $screen->id )
{
// Before:
add_action( 'all_admin_notices', function(){
echo '<p>Greetings from <strong>all_admin_notices</strong>!</p>';
});
}
});
</code></pre>
<p>Which works in my reservation custom post type. But I'm wondering if it's possible to output content after the title, but before table with custom post types?</p>
<p><a href="https://i.stack.imgur.com/dIDLD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dIDLD.jpg" alt="enter image description here"></a></p>
|
[
{
"answer_id": 217182,
"author": "Charles Jaimet",
"author_id": 43741,
"author_profile": "https://wordpress.stackexchange.com/users/43741",
"pm_score": 2,
"selected": false,
"text": "<p>You can do it with JavaScript.</p>\n\n<pre><code>add_action( 'all_admin_notices', function(){\n echo '<script>jQuery(document).ready(function($) { $( \"<p>Greetings from <strong>all_admin_notices</strong>!</p>\" ).insertAfter( \".subsubsub\" );});</script>';\n} );\n</code></pre>\n"
},
{
"answer_id": 217191,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<p>You could try to \"hijack\" the following filter in the <code>WP_List_Table</code> class:</p>\n\n<pre><code>/**\n * Filter the list of available list table views.\n *\n * The dynamic portion of the hook name, `$this->screen->id`, refers\n * to the ID of the current screen, usually a string.\n *\n * @since 3.5.0\n *\n * @param array $views An array of available list table views.\n */\n $views = apply_filters( \"views_{$this->screen->id}\", $views );\n</code></pre>\n\n<h2>Example</h2>\n\n<p>For the <code>edit-post</code> screen, the filter is <code>views_edit-post</code>:</p>\n\n<pre><code>/**\n * Display HTML after the 'Posts' title\n * where we target the 'edit-post' screen\n */\nadd_filter( 'views_edit-post', function( $views )\n{\n echo '<p>Greetings from <strong>views_edit-post</strong></p>';\n\n return $views;\n} );\n</code></pre>\n\n<p>and this will display as:</p>\n\n<p><a href=\"https://i.stack.imgur.com/vb6ib.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/vb6ib.jpg\" alt=\"greetings\"></a></p>\n"
}
] |
2016/02/09
|
[
"https://wordpress.stackexchange.com/questions/217125",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58895/"
] |
I found here on WPSE that you can [add content before post title](https://wordpress.stackexchange.com/questions/140319/add-content-before-after-admin-post-wp-list-table) in the post page, and in custom post type pages
```
add_action( 'load-edit.php', function(){
$screen = get_current_screen();
// Only edit post screen:
if( 'edit-reservation' === $screen->id )
{
// Before:
add_action( 'all_admin_notices', function(){
echo '<p>Greetings from <strong>all_admin_notices</strong>!</p>';
});
}
});
```
Which works in my reservation custom post type. But I'm wondering if it's possible to output content after the title, but before table with custom post types?
[](https://i.stack.imgur.com/dIDLD.jpg)
|
You could try to "hijack" the following filter in the `WP_List_Table` class:
```
/**
* Filter the list of available list table views.
*
* The dynamic portion of the hook name, `$this->screen->id`, refers
* to the ID of the current screen, usually a string.
*
* @since 3.5.0
*
* @param array $views An array of available list table views.
*/
$views = apply_filters( "views_{$this->screen->id}", $views );
```
Example
-------
For the `edit-post` screen, the filter is `views_edit-post`:
```
/**
* Display HTML after the 'Posts' title
* where we target the 'edit-post' screen
*/
add_filter( 'views_edit-post', function( $views )
{
echo '<p>Greetings from <strong>views_edit-post</strong></p>';
return $views;
} );
```
and this will display as:
[](https://i.stack.imgur.com/vb6ib.jpg)
|
217,126 |
<p>Hello I am really sorry if this has been asked before but I couldn't find the exact solution I need. So here's the problem I want to create a search in my Wordpress page. Whenever a user submits the form I want to create a query to search for posts by their categories or their parents/child categories. Here's an example: </p>
<p><a href="https://i.stack.imgur.com/rR1gs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rR1gs.png" alt="Example"></a> </p>
<p>So in MYSQL it would look something like this but I don't know how to do it in Wordpress with the help of WP_Query since I am new to this.</p>
<pre><code>SELECT * FROM posts
WHERE posts.category
LIKE '%John Doe%' OR posts.sub_category LIKE '%John Doe%'
</code></pre>
<p>I haven't figured out how the tables are connected so probably a few JOIN operations need to be made here but I hope someone understands what I am asking.</p>
<p>Any help would be appreciated.
Thanks in advance!</p>
|
[
{
"answer_id": 217173,
"author": "Charles Jaimet",
"author_id": 43741,
"author_profile": "https://wordpress.stackexchange.com/users/43741",
"pm_score": 1,
"selected": false,
"text": "<p>Use this:</p>\n\n<pre><code>$query = new WP_Query( array( 'cat' => 4 ) );\n</code></pre>\n\n<p>Where 4 is the ID of the top-level category (Blackburn). This query will in clude subcats.</p>\n\n<p>Reference - <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\"><code>WP_Query</code></a></p>\n"
},
{
"answer_id": 217215,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 1,
"selected": true,
"text": "<p>Use <code>get_categories</code> first to get all the post categories to use in the form, then loop through them to display a multicheck input...</p>\n\n<pre><code>function hierarchical_category_inputs ($cat, $indent) {\n\n $cats = get_categories('hide_empty=false&orderby=name&order=ASC&parent='.$cat);\n $indent++;\n\n if ($cats) {\n foreach ($cats as $cat) {\n echo \"<input type='checkbox' name='cat-\".$cat->term_id.\"'\";\n echo \" style='margin-left: \".($indent*10).\"px;'> \".$cat->name.\"<br>\";\n hierarchical_category_inputs($cat->term_id, $indent);\n }\n }\n} \n\necho \"<form method='post'>\";\n// 0 for all categories, -1 so first indent is 0\nhierarchical_category_inputs(0,-1);\necho \"<input type='hidden' name='custom_catsearch' value='yes'>\";\necho \"<input type='submit' value='Search'>\";\necho \"</form>\";\n</code></pre>\n\n<p>Then in the search part you would assemble the array of ticked categories to pass to <code>WP_Query</code>:</p>\n\n<pre><code>function custom_catsearch_output() {\n $cats = array();\n foreach ($_POST as $key => $value) {\n // make sure the post key starts with cat-\n if (substr($key,0,4) == 'cat-') {\n // check for check of the checkbox\n if ($value == '1') {\n // get the cat id from after cat-\n $cats[] = substr($key,4,strlen($key));\n }\n }\n }\n\n $query = new WP_Query(array('cat' => $cats));\n\n print_r($query);\n // ... do something different with the results ...\n\n}\n</code></pre>\n"
}
] |
2016/02/09
|
[
"https://wordpress.stackexchange.com/questions/217126",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88373/"
] |
Hello I am really sorry if this has been asked before but I couldn't find the exact solution I need. So here's the problem I want to create a search in my Wordpress page. Whenever a user submits the form I want to create a query to search for posts by their categories or their parents/child categories. Here's an example:
[](https://i.stack.imgur.com/rR1gs.png)
So in MYSQL it would look something like this but I don't know how to do it in Wordpress with the help of WP\_Query since I am new to this.
```
SELECT * FROM posts
WHERE posts.category
LIKE '%John Doe%' OR posts.sub_category LIKE '%John Doe%'
```
I haven't figured out how the tables are connected so probably a few JOIN operations need to be made here but I hope someone understands what I am asking.
Any help would be appreciated.
Thanks in advance!
|
Use `get_categories` first to get all the post categories to use in the form, then loop through them to display a multicheck input...
```
function hierarchical_category_inputs ($cat, $indent) {
$cats = get_categories('hide_empty=false&orderby=name&order=ASC&parent='.$cat);
$indent++;
if ($cats) {
foreach ($cats as $cat) {
echo "<input type='checkbox' name='cat-".$cat->term_id."'";
echo " style='margin-left: ".($indent*10)."px;'> ".$cat->name."<br>";
hierarchical_category_inputs($cat->term_id, $indent);
}
}
}
echo "<form method='post'>";
// 0 for all categories, -1 so first indent is 0
hierarchical_category_inputs(0,-1);
echo "<input type='hidden' name='custom_catsearch' value='yes'>";
echo "<input type='submit' value='Search'>";
echo "</form>";
```
Then in the search part you would assemble the array of ticked categories to pass to `WP_Query`:
```
function custom_catsearch_output() {
$cats = array();
foreach ($_POST as $key => $value) {
// make sure the post key starts with cat-
if (substr($key,0,4) == 'cat-') {
// check for check of the checkbox
if ($value == '1') {
// get the cat id from after cat-
$cats[] = substr($key,4,strlen($key));
}
}
}
$query = new WP_Query(array('cat' => $cats));
print_r($query);
// ... do something different with the results ...
}
```
|
217,135 |
<p>I am trying to set a single page template that will apply to any page which URL begins with confirmation-.</p>
<p>For example (page names):</p>
<pre><code>confirmation-tt5,
confirmation-556,
</code></pre>
<p>Should I just create a <code>single-confirmation</code> or will I need a custom filter?</p>
|
[
{
"answer_id": 217137,
"author": "James",
"author_id": 71177,
"author_profile": "https://wordpress.stackexchange.com/users/71177",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];\nif (strpos($url,'confirmation') == true) {\n\n include(locate_template('page-confirmation.php'));\n\n}\n</code></pre>\n\n<p>I managed to come up with this solution, not very elegant though as this code needs to be put into default <code>page.php</code>, I would prefer a filter of some sort that does this dynamically.</p>\n"
},
{
"answer_id": 217139,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>We can make use of the <code>page_template</code> filter to achieve this. All we need to do is to make sure that <code>confirmation</code> is the first word in the page page title</p>\n\n<pre><code>add_filter( 'page_template', function ( $template )\n{\n // Get the current page object\n $post = get_queried_object();\n\n /**\n * Get the first instance of confirmation, if it is not 0, bail\n * We will be using the page name, which is the slug\n */\n if ( 0 !== stripos( $post->post_name, 'confirmation' ) )\n return $template;\n\n // We have confimation as first word, lets continue\n $locate_template = locate_template( 'page-confirmation.php' );\n\n // Check if $locate_template is not empty, if so, bail\n if ( !$locate_template )\n return $template;\n\n // page-confirmation.php exist, return it\n return $locate_template;\n});\n</code></pre>\n"
}
] |
2016/02/09
|
[
"https://wordpress.stackexchange.com/questions/217135",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71177/"
] |
I am trying to set a single page template that will apply to any page which URL begins with confirmation-.
For example (page names):
```
confirmation-tt5,
confirmation-556,
```
Should I just create a `single-confirmation` or will I need a custom filter?
|
We can make use of the `page_template` filter to achieve this. All we need to do is to make sure that `confirmation` is the first word in the page page title
```
add_filter( 'page_template', function ( $template )
{
// Get the current page object
$post = get_queried_object();
/**
* Get the first instance of confirmation, if it is not 0, bail
* We will be using the page name, which is the slug
*/
if ( 0 !== stripos( $post->post_name, 'confirmation' ) )
return $template;
// We have confimation as first word, lets continue
$locate_template = locate_template( 'page-confirmation.php' );
// Check if $locate_template is not empty, if so, bail
if ( !$locate_template )
return $template;
// page-confirmation.php exist, return it
return $locate_template;
});
```
|
217,141 |
<p>I set up a local environment to customize a friend's WP blog. However almost none of the images are being displayed.</p>
<p>The remote site's URL is <code>http://sitename.com</code> and my local virtual host is <code>http://sitename.dev</code>.</p>
<p>I have found a couple different cases when the images are not displayed:</p>
<ul>
<li>The src URL looks like this: <code>http://i1.wp.com/sitename.com/wp-content/uploads/xxxxxx</code> and opening this link on the browser shows the image correctly. However there's a <code>srcset</code> attribute with the URL <code>http://i1.wp.com/sitename.dev/wp-content/uploads/xxxxxx</code> and that causes a 504 HTML error because obviously there is no <code>http://i1.wp.com/sitename.dev</code>.</li>
<li>The other case just has a src URL like the previous <code>srcset</code>, it looks like <code>http://i1.wp.com/sitename.dev/wp-content/uploads/xxxxxx</code> so it is unable to load the resource.</li>
</ul>
<p>So it looks like the main problem is that <code>i1.wp.com</code> that is being prepended to my local URL and it's completely messing with the routes.</p>
<p>When editing posts from wp-admin all images are shown correctly. Well the featured image preview isn't displayed correcly because it tried prepending <code>i1.wp.com</code> again but when selecting the image from the gallery it is displayed correcty (and the URL is <code>http://sitename.dev/xxxxx</code>).</p>
<p>I have no idea where that prepended segment comes from but I would like to know how to either get rid of it or how to set up images correctly in my local environment.</p>
|
[
{
"answer_id": 217137,
"author": "James",
"author_id": 71177,
"author_profile": "https://wordpress.stackexchange.com/users/71177",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];\nif (strpos($url,'confirmation') == true) {\n\n include(locate_template('page-confirmation.php'));\n\n}\n</code></pre>\n\n<p>I managed to come up with this solution, not very elegant though as this code needs to be put into default <code>page.php</code>, I would prefer a filter of some sort that does this dynamically.</p>\n"
},
{
"answer_id": 217139,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>We can make use of the <code>page_template</code> filter to achieve this. All we need to do is to make sure that <code>confirmation</code> is the first word in the page page title</p>\n\n<pre><code>add_filter( 'page_template', function ( $template )\n{\n // Get the current page object\n $post = get_queried_object();\n\n /**\n * Get the first instance of confirmation, if it is not 0, bail\n * We will be using the page name, which is the slug\n */\n if ( 0 !== stripos( $post->post_name, 'confirmation' ) )\n return $template;\n\n // We have confimation as first word, lets continue\n $locate_template = locate_template( 'page-confirmation.php' );\n\n // Check if $locate_template is not empty, if so, bail\n if ( !$locate_template )\n return $template;\n\n // page-confirmation.php exist, return it\n return $locate_template;\n});\n</code></pre>\n"
}
] |
2016/02/09
|
[
"https://wordpress.stackexchange.com/questions/217141",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88376/"
] |
I set up a local environment to customize a friend's WP blog. However almost none of the images are being displayed.
The remote site's URL is `http://sitename.com` and my local virtual host is `http://sitename.dev`.
I have found a couple different cases when the images are not displayed:
* The src URL looks like this: `http://i1.wp.com/sitename.com/wp-content/uploads/xxxxxx` and opening this link on the browser shows the image correctly. However there's a `srcset` attribute with the URL `http://i1.wp.com/sitename.dev/wp-content/uploads/xxxxxx` and that causes a 504 HTML error because obviously there is no `http://i1.wp.com/sitename.dev`.
* The other case just has a src URL like the previous `srcset`, it looks like `http://i1.wp.com/sitename.dev/wp-content/uploads/xxxxxx` so it is unable to load the resource.
So it looks like the main problem is that `i1.wp.com` that is being prepended to my local URL and it's completely messing with the routes.
When editing posts from wp-admin all images are shown correctly. Well the featured image preview isn't displayed correcly because it tried prepending `i1.wp.com` again but when selecting the image from the gallery it is displayed correcty (and the URL is `http://sitename.dev/xxxxx`).
I have no idea where that prepended segment comes from but I would like to know how to either get rid of it or how to set up images correctly in my local environment.
|
We can make use of the `page_template` filter to achieve this. All we need to do is to make sure that `confirmation` is the first word in the page page title
```
add_filter( 'page_template', function ( $template )
{
// Get the current page object
$post = get_queried_object();
/**
* Get the first instance of confirmation, if it is not 0, bail
* We will be using the page name, which is the slug
*/
if ( 0 !== stripos( $post->post_name, 'confirmation' ) )
return $template;
// We have confimation as first word, lets continue
$locate_template = locate_template( 'page-confirmation.php' );
// Check if $locate_template is not empty, if so, bail
if ( !$locate_template )
return $template;
// page-confirmation.php exist, return it
return $locate_template;
});
```
|
217,154 |
<p>Is there a function I can use which will temporarily output the menu_position of every item in the admin menu?</p>
<p>While trying to reorganise the admin menu, the single largest thing slowing me down is trying to mentally keep track of which menu item is where.</p>
<p>Being able to see this info while im doing this would be so helpful!</p>
<p>Thanks</p>
|
[
{
"answer_id": 217137,
"author": "James",
"author_id": 71177,
"author_profile": "https://wordpress.stackexchange.com/users/71177",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];\nif (strpos($url,'confirmation') == true) {\n\n include(locate_template('page-confirmation.php'));\n\n}\n</code></pre>\n\n<p>I managed to come up with this solution, not very elegant though as this code needs to be put into default <code>page.php</code>, I would prefer a filter of some sort that does this dynamically.</p>\n"
},
{
"answer_id": 217139,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>We can make use of the <code>page_template</code> filter to achieve this. All we need to do is to make sure that <code>confirmation</code> is the first word in the page page title</p>\n\n<pre><code>add_filter( 'page_template', function ( $template )\n{\n // Get the current page object\n $post = get_queried_object();\n\n /**\n * Get the first instance of confirmation, if it is not 0, bail\n * We will be using the page name, which is the slug\n */\n if ( 0 !== stripos( $post->post_name, 'confirmation' ) )\n return $template;\n\n // We have confimation as first word, lets continue\n $locate_template = locate_template( 'page-confirmation.php' );\n\n // Check if $locate_template is not empty, if so, bail\n if ( !$locate_template )\n return $template;\n\n // page-confirmation.php exist, return it\n return $locate_template;\n});\n</code></pre>\n"
}
] |
2016/02/09
|
[
"https://wordpress.stackexchange.com/questions/217154",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77390/"
] |
Is there a function I can use which will temporarily output the menu\_position of every item in the admin menu?
While trying to reorganise the admin menu, the single largest thing slowing me down is trying to mentally keep track of which menu item is where.
Being able to see this info while im doing this would be so helpful!
Thanks
|
We can make use of the `page_template` filter to achieve this. All we need to do is to make sure that `confirmation` is the first word in the page page title
```
add_filter( 'page_template', function ( $template )
{
// Get the current page object
$post = get_queried_object();
/**
* Get the first instance of confirmation, if it is not 0, bail
* We will be using the page name, which is the slug
*/
if ( 0 !== stripos( $post->post_name, 'confirmation' ) )
return $template;
// We have confimation as first word, lets continue
$locate_template = locate_template( 'page-confirmation.php' );
// Check if $locate_template is not empty, if so, bail
if ( !$locate_template )
return $template;
// page-confirmation.php exist, return it
return $locate_template;
});
```
|
217,179 |
<p>I am developing a WordPress plugin, but before that I have checked the code for the few plugin already developed. I have seen a common approach to restrict the direct where the plugin developer starts the plugin code by the following line </p>
<pre><code>// If accessed directly, abort
if ( ! defined( 'WPINC' ) ) {
die;
}
</code></pre>
<p>This is in the plugin index file. My question is when we install the plugin this is the first file to be executed so where it is defined before and it is not abort the execution on the file ?</p>
|
[
{
"answer_id": 217197,
"author": "BillK",
"author_id": 87352,
"author_profile": "https://wordpress.stackexchange.com/users/87352",
"pm_score": 1,
"selected": false,
"text": "<p><code>WPINC</code> is defined by WP before plugins are loaded; so, the fact that it is already defined indicates the plugin is being loaded by WP rather than a direct request.</p>\n"
},
{
"answer_id": 217217,
"author": "Charles",
"author_id": 15605,
"author_profile": "https://wordpress.stackexchange.com/users/15605",
"pm_score": 4,
"selected": true,
"text": "<p><em>Question 1.</em> so where it is defined before<br />\n<em>Answer:</em><br /></p>\n\n<blockquote>\n <p>It is defined in WordPress core.</p>\n</blockquote>\n\n<p>Here a quick online <a href=\"https://core.trac.wordpress.org/browser/trunk/src/wp-settings.php#L18\" rel=\"noreferrer\">reference</a> or for a local reference take a look at the following file in the root of WordPress: <code>wp-settings.php</code>. In that file (<em>around line 18</em>) following code is shown:<br /></p>\n\n<blockquote>\n <p><code>define( 'WPINC', 'wp-includes' );</code></p>\n</blockquote>\n\n<hr>\n\n<p><em>Question 2.</em> and it is not abort the execution on the file<br />\n<em>Answer:</em><br /></p>\n\n<p>The use (<em>the goal so to say</em>) of it is to protect plugins from direct access<br />\n(<em>from the outside, <strong>preventing any unauthorized access</strong> to your code</em>) <br />\nTwo ways to achieve this protection, some developers use <strong><code>WPINC</code></strong> and others use <strong><code>ABSPATH</code></strong> as in:<br /></p>\n\n<ul>\n<li><code>if (!defined('ABSPATH')) exit;</code> <em>(or replace <code>exit</code> with <code>die(\"No cheating!\")</code> or other txt)</em></li>\n<li><code>if ( ! defined( 'WPINC' ) ) die;</code> <em>(or use <code>exit</code>in same way as above)</em></li>\n</ul>\n\n<p>Both defined as follow:<br /></p>\n\n<ul>\n<li><code>define( 'ABSPATH', dirname(dirname(__FILE__)) . '/' );</code></li>\n<li><code>define( 'WPINC', 'wp-includes' );</code></li>\n</ul>\n\n<p><code>dirname</code> (<em>generic PHP</em>) simply returns the directory from a full path.<br />\n <code>wp-includes</code> is pretty self explanatory.</p>\n\n<hr>\n\n<p>You are free to decide which to use. I personally think there is no real <em>right way</em> , both have the same purpose. I use only <code>ABSPATH</code> but it is all up to your personal preference.<br />\n<em>Just remember to add it directly below the header section or at least near the top of your plugin.</em></p>\n"
},
{
"answer_id": 318665,
"author": "Razon Komar Pal",
"author_id": 144761,
"author_profile": "https://wordpress.stackexchange.com/users/144761",
"pm_score": 0,
"selected": false,
"text": "<p>You can also use this one as well. It is defined in <a href=\"https://github.com/wp-plugins/akismet/blob/master/akismet.php#LC35\" rel=\"nofollow noreferrer\">Akismet Anti-Spam</a> Plugin.</p>\n\n<pre><code>// Make sure we don't expose any info if called directly\nif ( !function_exists( 'add_action' ) ) {\n echo 'Hi there! I\\'m just a plugin, not much I can do when called directly.';\n exit;\n}\n</code></pre>\n"
}
] |
2016/02/09
|
[
"https://wordpress.stackexchange.com/questions/217179",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83446/"
] |
I am developing a WordPress plugin, but before that I have checked the code for the few plugin already developed. I have seen a common approach to restrict the direct where the plugin developer starts the plugin code by the following line
```
// If accessed directly, abort
if ( ! defined( 'WPINC' ) ) {
die;
}
```
This is in the plugin index file. My question is when we install the plugin this is the first file to be executed so where it is defined before and it is not abort the execution on the file ?
|
*Question 1.* so where it is defined before
*Answer:*
>
> It is defined in WordPress core.
>
>
>
Here a quick online [reference](https://core.trac.wordpress.org/browser/trunk/src/wp-settings.php#L18) or for a local reference take a look at the following file in the root of WordPress: `wp-settings.php`. In that file (*around line 18*) following code is shown:
>
> `define( 'WPINC', 'wp-includes' );`
>
>
>
---
*Question 2.* and it is not abort the execution on the file
*Answer:*
The use (*the goal so to say*) of it is to protect plugins from direct access
(*from the outside, **preventing any unauthorized access** to your code*)
Two ways to achieve this protection, some developers use **`WPINC`** and others use **`ABSPATH`** as in:
* `if (!defined('ABSPATH')) exit;` *(or replace `exit` with `die("No cheating!")` or other txt)*
* `if ( ! defined( 'WPINC' ) ) die;` *(or use `exit`in same way as above)*
Both defined as follow:
* `define( 'ABSPATH', dirname(dirname(__FILE__)) . '/' );`
* `define( 'WPINC', 'wp-includes' );`
`dirname` (*generic PHP*) simply returns the directory from a full path.
`wp-includes` is pretty self explanatory.
---
You are free to decide which to use. I personally think there is no real *right way* , both have the same purpose. I use only `ABSPATH` but it is all up to your personal preference.
*Just remember to add it directly below the header section or at least near the top of your plugin.*
|
217,189 |
<p>I have made my own theme with shortcodes to WordPress.</p>
<p>In my filters I have:</p>
<pre><code>remove_filter('the_content', 'wpautop');
add_filter('the_content', 'wpautop', 99);
add_filter('the_content', 'shortcode_unautop', 100);
</code></pre>
<p>This should remove paragraph tags around and in my shortcodes.</p>
<p>My shortcode output (partial of the entire code):</p>
<pre><code>$output .= '
<div ' . implode(' ', $html_attributes) . '>
<a href="' . get_permalink() . '">
<div ' . implode(' ', $html_attributes_inner) . '>
' . $logo . '
<div class="button hidden-xs hidden-sm">Læs case</div>
<div class="content">
<div class="row">
<div class="col-md-8">
<h4 class="title">' . get_the_title() . '</h4>
<div class="spacer small"></div>
<div class="excerpt">' . get_post()->post_excerpt . '</div>
</div>
</div>
</div>
</div>
</a>
</div>
';
// Script newlines whitespace, tabs etc.
return str_replace(["\r", "\n", "\t"], '', '<div class="row cases">' . $output . '</div>');
</code></pre>
<p>This produces:</p>
<pre><code><div class="row cases">
<div class="col-xs-12"><a href="http://dev.youfront-hosting.dk/case/nori">
<div class="case" style="background-image: url(http://dev.youfront-hosting.dk/content/uploads/nori-restaurant-1120x500.jpg)">
<div class="button hidden-xs hidden-sm">Læs case</div>
<div class="content">
<div class="row">
<div class="col-md-8">
<h4 class="title">Nori</h4>
<div class="spacer small"></div>
<div class="excerpt"></div>
</div>
</div>
</div>
</div>
<p></a></div>
<div class="col-xs-12 col-md-6"><a href="http://dev.youfront-hosting.dk/case/an-ivy">
<div class="case" style="background-image: url(http://dev.youfront-hosting.dk/content/uploads/anivy-founders-545x500.jpg)"><img src="http://dev.youfront-hosting.dk/content/uploads/anivy-logo.png" alt="">
<div class="button hidden-xs hidden-sm">Læs case</div>
<div class="content">
<div class="row">
<div class="col-md-8">
<h4 class="title">AN-IVY. Nyt gentleman brand med stor passion for fashion, og klassisk herretøj</h4>
<div class="spacer small"></div>
<div class="excerpt">AN-IVY er et brand startet i 2013. De designer herrekollektioner der er inspireret af Ivy Leagues tradioner og moderne fashion. De har en stor passion for mode og klassisk herretøj.</div>
</div>
</div>
</div>
</div>
<p></a></div>
<div class="col-xs-12 col-md-6"><a href="http://dev.youfront-hosting.dk/case/powderstore">
<div class="case" style="background-image: url(http://dev.youfront-hosting.dk/content/uploads/team-youfront-545x500.jpg)">
<div class="button hidden-xs hidden-sm">Læs case</div>
<div class="content">
<div class="row">
<div class="col-md-8">
<h4 class="title">Powderstore</h4>
<div class="spacer small"></div>
<div class="excerpt"></div>
</div>
</div>
</div>
</div>
<p></a></div>
</div>
</div>
</code></pre>
<p>Note the additional <code><p></code> tags at line 15, 29 and 43.
The paragraph tags disappear if I remove the anchor tag in my shortcode, but that's not a solution I can use.</p>
|
[
{
"answer_id": 217304,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe try removing all the newlines from the output itself, since this is what is ultimately being messed with...</p>\n\n<pre><code>$output .= '<div ' . implode(' ', $html_attributes) . '>';\n$output .= '<a href=\"' . get_permalink() . '\">';\n$output .= '<div ' . implode(' ', $html_attributes_inner) . '>';\n$output .= $logo;\n</code></pre>\n\n<p>...and so forth. If the newlines are gone maybe wpautop will leave the shortcode output alone.</p>\n\n<p>otherwise, since it is a very specific and misformatted string output, you could always fix for it after the fact:</p>\n\n<pre><code>add_filter('the_content','shortcode_fix',110);\nfunction shortcode_fix($content) {\n return str_replace('<p></a></div>','</a></div>',$content);\n}\n</code></pre>\n\n<p>....</p>\n"
},
{
"answer_id": 217380,
"author": "andershagbard",
"author_id": 86744,
"author_profile": "https://wordpress.stackexchange.com/users/86744",
"pm_score": 2,
"selected": true,
"text": "<p>This is the solution:</p>\n\n<pre><code>function wpex_fix_shortcodes($content) {\n\n return strtr($content, [\n '<p>[' => '[',\n ']</p>' => ']',\n ']<br />' => ']'\n ]);\n\n}\n\nremove_filter('the_content', 'wpautop');\nremove_filter('the_content', 'do_shortcode', 11);\n\nadd_filter('the_content', 'wpautop', 100);\nadd_filter('the_content', 'wpex_fix_shortcodes', 105);\nadd_filter('the_content' , 'do_shortcode', 110);\n</code></pre>\n\n<p>This runs wpautop before do_shortcode, but removes the paragraph tags before and after the unformatted shortcodes, then runs do_shortcode.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>The solution above can also cause some HTML errors. Best practice would be to remove wpautop filter, and then add a shortcode which calls wpautop around content. Like this:</p>\n\n<pre><code>add_shortcode('text', function($attributes, $content = null)\n{\n\n // Output\n return do_shortcode(wpautop($content));\n\n});\n</code></pre>\n"
},
{
"answer_id": 341811,
"author": "KungFuJosh",
"author_id": 170995,
"author_profile": "https://wordpress.stackexchange.com/users/170995",
"pm_score": 2,
"selected": false,
"text": "<p>The above solution doesn't work if you're using Advanced Custom Fields. When using ACF, the following code does work:</p>\n\n<pre><code>remove_filter( 'the_content', 'wpautop' );\nremove_filter( 'acf_the_content', 'wpautop' );\nadd_filter( 'the_content', 'wpautop' , 99);\nadd_filter( 'acf_the_content', 'wpautop' , 100);\nadd_filter( 'the_content', 'shortcode_unautop',110 );\nadd_filter( 'acf_the_content', 'shortcode_unautop',111 );\n</code></pre>\n"
}
] |
2016/02/09
|
[
"https://wordpress.stackexchange.com/questions/217189",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86744/"
] |
I have made my own theme with shortcodes to WordPress.
In my filters I have:
```
remove_filter('the_content', 'wpautop');
add_filter('the_content', 'wpautop', 99);
add_filter('the_content', 'shortcode_unautop', 100);
```
This should remove paragraph tags around and in my shortcodes.
My shortcode output (partial of the entire code):
```
$output .= '
<div ' . implode(' ', $html_attributes) . '>
<a href="' . get_permalink() . '">
<div ' . implode(' ', $html_attributes_inner) . '>
' . $logo . '
<div class="button hidden-xs hidden-sm">Læs case</div>
<div class="content">
<div class="row">
<div class="col-md-8">
<h4 class="title">' . get_the_title() . '</h4>
<div class="spacer small"></div>
<div class="excerpt">' . get_post()->post_excerpt . '</div>
</div>
</div>
</div>
</div>
</a>
</div>
';
// Script newlines whitespace, tabs etc.
return str_replace(["\r", "\n", "\t"], '', '<div class="row cases">' . $output . '</div>');
```
This produces:
```
<div class="row cases">
<div class="col-xs-12"><a href="http://dev.youfront-hosting.dk/case/nori">
<div class="case" style="background-image: url(http://dev.youfront-hosting.dk/content/uploads/nori-restaurant-1120x500.jpg)">
<div class="button hidden-xs hidden-sm">Læs case</div>
<div class="content">
<div class="row">
<div class="col-md-8">
<h4 class="title">Nori</h4>
<div class="spacer small"></div>
<div class="excerpt"></div>
</div>
</div>
</div>
</div>
<p></a></div>
<div class="col-xs-12 col-md-6"><a href="http://dev.youfront-hosting.dk/case/an-ivy">
<div class="case" style="background-image: url(http://dev.youfront-hosting.dk/content/uploads/anivy-founders-545x500.jpg)"><img src="http://dev.youfront-hosting.dk/content/uploads/anivy-logo.png" alt="">
<div class="button hidden-xs hidden-sm">Læs case</div>
<div class="content">
<div class="row">
<div class="col-md-8">
<h4 class="title">AN-IVY. Nyt gentleman brand med stor passion for fashion, og klassisk herretøj</h4>
<div class="spacer small"></div>
<div class="excerpt">AN-IVY er et brand startet i 2013. De designer herrekollektioner der er inspireret af Ivy Leagues tradioner og moderne fashion. De har en stor passion for mode og klassisk herretøj.</div>
</div>
</div>
</div>
</div>
<p></a></div>
<div class="col-xs-12 col-md-6"><a href="http://dev.youfront-hosting.dk/case/powderstore">
<div class="case" style="background-image: url(http://dev.youfront-hosting.dk/content/uploads/team-youfront-545x500.jpg)">
<div class="button hidden-xs hidden-sm">Læs case</div>
<div class="content">
<div class="row">
<div class="col-md-8">
<h4 class="title">Powderstore</h4>
<div class="spacer small"></div>
<div class="excerpt"></div>
</div>
</div>
</div>
</div>
<p></a></div>
</div>
</div>
```
Note the additional `<p>` tags at line 15, 29 and 43.
The paragraph tags disappear if I remove the anchor tag in my shortcode, but that's not a solution I can use.
|
This is the solution:
```
function wpex_fix_shortcodes($content) {
return strtr($content, [
'<p>[' => '[',
']</p>' => ']',
']<br />' => ']'
]);
}
remove_filter('the_content', 'wpautop');
remove_filter('the_content', 'do_shortcode', 11);
add_filter('the_content', 'wpautop', 100);
add_filter('the_content', 'wpex_fix_shortcodes', 105);
add_filter('the_content' , 'do_shortcode', 110);
```
This runs wpautop before do\_shortcode, but removes the paragraph tags before and after the unformatted shortcodes, then runs do\_shortcode.
**EDIT**
The solution above can also cause some HTML errors. Best practice would be to remove wpautop filter, and then add a shortcode which calls wpautop around content. Like this:
```
add_shortcode('text', function($attributes, $content = null)
{
// Output
return do_shortcode(wpautop($content));
});
```
|
217,194 |
<p>I'm using HB Themes Aegaeus theme and it's great except for the fact that one of the shortcode elements (hb-box) is resizing the images. </p>
<p>(Obviously, automatically resizing site elements to fit a mobile device is one of the main reasons to use responsive design, but in this instance, it makes the image subjects look really, REALLY bad.)</p>
<p><a href="http://www.fullyhr.com/about/" rel="nofollow noreferrer">http://www.fullyhr.com/about/</a></p>
<p><a href="https://i.stack.imgur.com/M7NtW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/M7NtW.jpg" alt="enter image description here"></a></p>
<p><strong>How do I maintain the image size-ratio?</strong></p>
<p>This is the shortcode for the images in question <strong>on the page</strong>: </p>
<pre><code>[hb_image_box image="http://fullyhr.com/wp-content/uploads/2015/07/headshot_l_amanda.jpg" link="http://fullyhr.com/portfolio/amanda-mayo-sphr/"
title="Amanda Mayo" subtitle="SPHR, Founder, Sr HR Consultant"]
</code></pre>
<p>I have already tried the following custom css solutions:</p>
<pre><code>.custom-hb-box { width: 100% !important; display:block; height: auto !important; }
.custom-hb-box img { height: auto !important; width: 100% !important; }
</code></pre>
<p>However, these make the site time out with a "Website Not Available" error.</p>
<p>UPDATE
Here is the shortcode <strong>from the theme-shortcodes.php file:</strong> </p>
<pre><code>function hb_custom_box($atts, $content = null){
extract(shortcode_atts(array(
'title' =>'Title here',
'subtitle' => 'Subtitle here',
'image' =>'',
'link' =>'http://'
), $atts));
$image = hb_resize(null, $image, 460, 400, true);
$image = $image['url'];
$output = "
<div>
<a href='$link' class='custom-hb-box'>
<img src='$image' rel='Image'>
<div class='hb-custom-title'>
<span class='titt'>$title</span>
<span class='subtitt'>$subtitle</span>
</div>
<div class='hb-custom-glare'></div>
</a>
</div>";
return $output;
}
add_shortcode('hb_image_box', 'hb_custom_box');
</code></pre>
|
[
{
"answer_id": 217304,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe try removing all the newlines from the output itself, since this is what is ultimately being messed with...</p>\n\n<pre><code>$output .= '<div ' . implode(' ', $html_attributes) . '>';\n$output .= '<a href=\"' . get_permalink() . '\">';\n$output .= '<div ' . implode(' ', $html_attributes_inner) . '>';\n$output .= $logo;\n</code></pre>\n\n<p>...and so forth. If the newlines are gone maybe wpautop will leave the shortcode output alone.</p>\n\n<p>otherwise, since it is a very specific and misformatted string output, you could always fix for it after the fact:</p>\n\n<pre><code>add_filter('the_content','shortcode_fix',110);\nfunction shortcode_fix($content) {\n return str_replace('<p></a></div>','</a></div>',$content);\n}\n</code></pre>\n\n<p>....</p>\n"
},
{
"answer_id": 217380,
"author": "andershagbard",
"author_id": 86744,
"author_profile": "https://wordpress.stackexchange.com/users/86744",
"pm_score": 2,
"selected": true,
"text": "<p>This is the solution:</p>\n\n<pre><code>function wpex_fix_shortcodes($content) {\n\n return strtr($content, [\n '<p>[' => '[',\n ']</p>' => ']',\n ']<br />' => ']'\n ]);\n\n}\n\nremove_filter('the_content', 'wpautop');\nremove_filter('the_content', 'do_shortcode', 11);\n\nadd_filter('the_content', 'wpautop', 100);\nadd_filter('the_content', 'wpex_fix_shortcodes', 105);\nadd_filter('the_content' , 'do_shortcode', 110);\n</code></pre>\n\n<p>This runs wpautop before do_shortcode, but removes the paragraph tags before and after the unformatted shortcodes, then runs do_shortcode.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>The solution above can also cause some HTML errors. Best practice would be to remove wpautop filter, and then add a shortcode which calls wpautop around content. Like this:</p>\n\n<pre><code>add_shortcode('text', function($attributes, $content = null)\n{\n\n // Output\n return do_shortcode(wpautop($content));\n\n});\n</code></pre>\n"
},
{
"answer_id": 341811,
"author": "KungFuJosh",
"author_id": 170995,
"author_profile": "https://wordpress.stackexchange.com/users/170995",
"pm_score": 2,
"selected": false,
"text": "<p>The above solution doesn't work if you're using Advanced Custom Fields. When using ACF, the following code does work:</p>\n\n<pre><code>remove_filter( 'the_content', 'wpautop' );\nremove_filter( 'acf_the_content', 'wpautop' );\nadd_filter( 'the_content', 'wpautop' , 99);\nadd_filter( 'acf_the_content', 'wpautop' , 100);\nadd_filter( 'the_content', 'shortcode_unautop',110 );\nadd_filter( 'acf_the_content', 'shortcode_unautop',111 );\n</code></pre>\n"
}
] |
2016/02/09
|
[
"https://wordpress.stackexchange.com/questions/217194",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87187/"
] |
I'm using HB Themes Aegaeus theme and it's great except for the fact that one of the shortcode elements (hb-box) is resizing the images.
(Obviously, automatically resizing site elements to fit a mobile device is one of the main reasons to use responsive design, but in this instance, it makes the image subjects look really, REALLY bad.)
<http://www.fullyhr.com/about/>
[](https://i.stack.imgur.com/M7NtW.jpg)
**How do I maintain the image size-ratio?**
This is the shortcode for the images in question **on the page**:
```
[hb_image_box image="http://fullyhr.com/wp-content/uploads/2015/07/headshot_l_amanda.jpg" link="http://fullyhr.com/portfolio/amanda-mayo-sphr/"
title="Amanda Mayo" subtitle="SPHR, Founder, Sr HR Consultant"]
```
I have already tried the following custom css solutions:
```
.custom-hb-box { width: 100% !important; display:block; height: auto !important; }
.custom-hb-box img { height: auto !important; width: 100% !important; }
```
However, these make the site time out with a "Website Not Available" error.
UPDATE
Here is the shortcode **from the theme-shortcodes.php file:**
```
function hb_custom_box($atts, $content = null){
extract(shortcode_atts(array(
'title' =>'Title here',
'subtitle' => 'Subtitle here',
'image' =>'',
'link' =>'http://'
), $atts));
$image = hb_resize(null, $image, 460, 400, true);
$image = $image['url'];
$output = "
<div>
<a href='$link' class='custom-hb-box'>
<img src='$image' rel='Image'>
<div class='hb-custom-title'>
<span class='titt'>$title</span>
<span class='subtitt'>$subtitle</span>
</div>
<div class='hb-custom-glare'></div>
</a>
</div>";
return $output;
}
add_shortcode('hb_image_box', 'hb_custom_box');
```
|
This is the solution:
```
function wpex_fix_shortcodes($content) {
return strtr($content, [
'<p>[' => '[',
']</p>' => ']',
']<br />' => ']'
]);
}
remove_filter('the_content', 'wpautop');
remove_filter('the_content', 'do_shortcode', 11);
add_filter('the_content', 'wpautop', 100);
add_filter('the_content', 'wpex_fix_shortcodes', 105);
add_filter('the_content' , 'do_shortcode', 110);
```
This runs wpautop before do\_shortcode, but removes the paragraph tags before and after the unformatted shortcodes, then runs do\_shortcode.
**EDIT**
The solution above can also cause some HTML errors. Best practice would be to remove wpautop filter, and then add a shortcode which calls wpautop around content. Like this:
```
add_shortcode('text', function($attributes, $content = null)
{
// Output
return do_shortcode(wpautop($content));
});
```
|
217,210 |
<p>I ad a custom field to registration form:</p>
<pre><code>function wooc_extra_register_fields() {
<p class="form-row form-row-first">
<label for="billing_cpf"><?php _e( 'CPF', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="text" class="input-text" name="billing_cpf" id="billing_cpf" placeholder="Somente número" value="<?php if ( ! empty( $_POST['billing_cpf'] ) ) esc_attr_e( $_POST['billing_cpf'] ); ?>" />
</p>
add_action( 'woocommerce_register_form_start', 'wooc_extra_register_fields' );
</code></pre>
<p>And save:</p>
<pre><code>function wooc_save_extra_register_fields( $customer_id) {
if ( isset( $_POST['billing_cpf'] ) ) {
update_user_meta( $customer_id, 'billing_cpf', $_POST['billing_cpf'] );
}
}
add_action( 'woocommerce_created_customer', 'wooc_save_extra_register_fields' );
</code></pre>
<p>I see that registtration custom fields are saved into table <strong>wp_usermeta</strong>. I need to check if <strong>$_POST['billing_cpf']</strong> already exist into this table and deny saving.
Thanks for any help.</p>
|
[
{
"answer_id": 217218,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 1,
"selected": false,
"text": "<p>You should be using <code>add_user_meta</code> instead of <code>update_user_meta</code>:</p>\n\n<pre><code>if (isset($_POST['billing_cpf'])) {\n add_user_meta($customer_id, 'billing_cpf', $POST['billing_cpf'], true);\n}\n</code></pre>\n\n<p>As this will <strong>only</strong> add the meta if it <em>does not already exist</em> - no update.</p>\n\n<p>(This will prevent this field from being updatable - unless by you another way.)</p>\n\n<p>Note: normally you could use something like this to add and update in combo so that the field <strong>is</strong> updatable:</p>\n\n<pre><code>if (isset($_POST['billing_cpf'])) {\n if (!add_user_meta($customer_id, 'billing_cpf', $POST['billing_cpf'], true)) {\n update_user_meta($customer_id, 'billing_cpf', $POST['billing_cpf']);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 217404,
"author": "iperion300",
"author_id": 79901,
"author_profile": "https://wordpress.stackexchange.com/users/79901",
"pm_score": 0,
"selected": false,
"text": "<p>I read Codex document about <code>get_user_meta</code>... maybe it works. I made a test with the following code:</p>\n\n<pre><code><?php \n$user_last = get_user_meta( 51, 'billing_cpf', true );\necho '<p>The '. $key . ' value for user id ' . $user_id . ' is: ' . $user_last . '</p>'; \n?>\n</code></pre>\n\n<p>Someone nows how to get all values saved for all users? ($key = 'billing_cpf') </p>\n"
}
] |
2016/02/10
|
[
"https://wordpress.stackexchange.com/questions/217210",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/79901/"
] |
I ad a custom field to registration form:
```
function wooc_extra_register_fields() {
<p class="form-row form-row-first">
<label for="billing_cpf"><?php _e( 'CPF', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="text" class="input-text" name="billing_cpf" id="billing_cpf" placeholder="Somente número" value="<?php if ( ! empty( $_POST['billing_cpf'] ) ) esc_attr_e( $_POST['billing_cpf'] ); ?>" />
</p>
add_action( 'woocommerce_register_form_start', 'wooc_extra_register_fields' );
```
And save:
```
function wooc_save_extra_register_fields( $customer_id) {
if ( isset( $_POST['billing_cpf'] ) ) {
update_user_meta( $customer_id, 'billing_cpf', $_POST['billing_cpf'] );
}
}
add_action( 'woocommerce_created_customer', 'wooc_save_extra_register_fields' );
```
I see that registtration custom fields are saved into table **wp\_usermeta**. I need to check if **$\_POST['billing\_cpf']** already exist into this table and deny saving.
Thanks for any help.
|
You should be using `add_user_meta` instead of `update_user_meta`:
```
if (isset($_POST['billing_cpf'])) {
add_user_meta($customer_id, 'billing_cpf', $POST['billing_cpf'], true);
}
```
As this will **only** add the meta if it *does not already exist* - no update.
(This will prevent this field from being updatable - unless by you another way.)
Note: normally you could use something like this to add and update in combo so that the field **is** updatable:
```
if (isset($_POST['billing_cpf'])) {
if (!add_user_meta($customer_id, 'billing_cpf', $POST['billing_cpf'], true)) {
update_user_meta($customer_id, 'billing_cpf', $POST['billing_cpf']);
}
}
```
|
217,242 |
<p>For example, if I add this code to functions.php:</p>
<pre><code>$mysite_address_url="http://my-site.com";
</code></pre>
<p>And then add this to one of my .php template files(like index.php or header.php):</p>
<pre><code><?php echo($mysite_address_url); ?>
</code></pre>
<p>It won't work. Why is this happens and how can I achieve this with wordpress please?</p>
|
[
{
"answer_id": 217245,
"author": "forlogos",
"author_id": 20951,
"author_profile": "https://wordpress.stackexchange.com/users/20951",
"pm_score": 1,
"selected": false,
"text": "<p>WordPress theme files are called thru functions/classes, so variables declared in <code>functions.php</code> are not recognized by other theme files, until you specify you want to use the global value of the variable. Do so like this in your theme template files:</p>\n\n<pre><code>global $mysite_address_url;\n</code></pre>\n\n<p>you can then use <code>$mysite_address_url</code> as you'd like.</p>\n\n<p>To read more about PHP's variable scope, see <a href=\"http://php.net/manual/en/language.variables.scope.php\" rel=\"nofollow\">this</a></p>\n\n<p>Also, if you want to use your website's URL, it'd be better to use the <a href=\"https://codex.wordpress.org/Function_Reference/home_url\" rel=\"nofollow\"><code>home_url()</code> function</a></p>\n"
},
{
"answer_id": 217246,
"author": "Devendra Sharma",
"author_id": 70571,
"author_profile": "https://wordpress.stackexchange.com/users/70571",
"pm_score": 0,
"selected": false,
"text": "<p>I recommend you to store it in WordPress options table using function </p>\n\n<pre><code>add_option() \n</code></pre>\n\n<p>function as this is site specific data and not post/category specific.</p>\n"
}
] |
2016/02/10
|
[
"https://wordpress.stackexchange.com/questions/217242",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88444/"
] |
For example, if I add this code to functions.php:
```
$mysite_address_url="http://my-site.com";
```
And then add this to one of my .php template files(like index.php or header.php):
```
<?php echo($mysite_address_url); ?>
```
It won't work. Why is this happens and how can I achieve this with wordpress please?
|
WordPress theme files are called thru functions/classes, so variables declared in `functions.php` are not recognized by other theme files, until you specify you want to use the global value of the variable. Do so like this in your theme template files:
```
global $mysite_address_url;
```
you can then use `$mysite_address_url` as you'd like.
To read more about PHP's variable scope, see [this](http://php.net/manual/en/language.variables.scope.php)
Also, if you want to use your website's URL, it'd be better to use the [`home_url()` function](https://codex.wordpress.org/Function_Reference/home_url)
|
217,251 |
<p>I want to apply a function if post is updated and if post author id is not 1.
For this i tried many functions like</p>
<pre><code><?php if (get_the_modified_time() != get_the_time()) && ( $author_id != 1 ) : ?>
</code></pre>
<p>By this code <strong>if post is updated</strong> is working but <strong>if post author is not 1</strong> not working.
Please help me!</p>
|
[
{
"answer_id": 217253,
"author": "terminator",
"author_id": 55034,
"author_profile": "https://wordpress.stackexchange.com/users/55034",
"pm_score": 0,
"selected": false,
"text": "<p>this should work</p>\n\n<pre><code><?php if (get_the_modified_time() != get_the_time() && ( $author_id != 1 )): ?>\n</code></pre>\n"
},
{
"answer_id": 217256,
"author": "akarim",
"author_id": 75682,
"author_profile": "https://wordpress.stackexchange.com/users/75682",
"pm_score": 1,
"selected": false,
"text": "<p>Finally i find answer.\nThe perfect code is</p>\n\n<pre><code><?php $author_id = $post->post_author; if (get_the_modified_time() != get_the_time() && ( $author_id != 1 )): ?>\n</code></pre>\n\n<p>That's all.</p>\n"
},
{
"answer_id": 217260,
"author": "realloc",
"author_id": 6972,
"author_profile": "https://wordpress.stackexchange.com/users/6972",
"pm_score": 1,
"selected": false,
"text": "<p>With a global <em>$post</em> object you could check the conditions also like this:</p>\n\n<pre><code>global $post;\nif ( $post->post_date != $post->post_modified && $post->post_author != 1 ) :\n // your code\nendif;\n</code></pre>\n\n<p>But if you prefer to use just functions then you can do this:</p>\n\n<pre><code>if ( get_the_modified_time() != get_the_time() && get_the_author_meta( 'ID' ) != 1 ) :\n // your code\nendif;\n</code></pre>\n"
}
] |
2016/02/10
|
[
"https://wordpress.stackexchange.com/questions/217251",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75682/"
] |
I want to apply a function if post is updated and if post author id is not 1.
For this i tried many functions like
```
<?php if (get_the_modified_time() != get_the_time()) && ( $author_id != 1 ) : ?>
```
By this code **if post is updated** is working but **if post author is not 1** not working.
Please help me!
|
Finally i find answer.
The perfect code is
```
<?php $author_id = $post->post_author; if (get_the_modified_time() != get_the_time() && ( $author_id != 1 )): ?>
```
That's all.
|
217,293 |
<p>I am trying to redirect the user after login/signup to profile page, but I am not sure why is it not putting the user nickname in url.</p>
<pre><code>$current_user = wp_get_current_user();
function aloginuser( $user_id ) {
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id);
wp_redirect( "/profile/$current_user->user_login" );
exit;
}
add_action( 'user_register', 'aloginuser' );
</code></pre>
<p>It need to put site.com/profile/username</p>
|
[
{
"answer_id": 217273,
"author": "Vasim Shaikh",
"author_id": 87704,
"author_profile": "https://wordpress.stackexchange.com/users/87704",
"pm_score": 0,
"selected": false,
"text": "<p>Found out a quick and easy way to fix it.</p>\n\n<p>Follow these instructions:</p>\n\n<ol>\n<li>Create a new post</li>\n<li>Do not introduce anything at the \"Excerpt\" field (in fact, disable Advanced Editing)</li>\n<li>Write your post</li>\n<li>Introduce the following tag <code><!--more--></code> at the place where you want the text to break</li>\n</ol>\n\n<p>And there you have it!<br />\nYour post should now have something like (more...) or (read everything...) at the place where you included the tag.\nI am assuming you are still running wordpress with the php the_content tag in place.</p>\n\n<p>If you want to change what's inside the brackets, just go to Presentation>Theme Editor and edit the Main Template, and then find the_content tag and change it to something like:</p>\n\n<pre><code><?php the_content(__('(hey! Why not read the rest of this message, since you got this far?)')); ?>\n</code></pre>\n\n<p>Hope this helps.</p>\n\n<p>Cheers.</p>\n"
},
{
"answer_id": 217275,
"author": "Marie-Jo",
"author_id": 88329,
"author_profile": "https://wordpress.stackexchange.com/users/88329",
"pm_score": 0,
"selected": false,
"text": "<p>You've got the most useful part to your answer from Vasim with <code>$post->post_excerpt</code>. Then you need a test of the type of page you're in, i.e. if in single post show the post's content, if in index or archive, show only the <code>post_excerpt</code>.</p>\n"
},
{
"answer_id": 217312,
"author": "Charles",
"author_id": 15605,
"author_profile": "https://wordpress.stackexchange.com/users/15605",
"pm_score": 0,
"selected": false,
"text": "<p>First of all, did you create a <code>child theme</code>? Because doing this in a <code>Parent theme</code> the changes will be 'lost' as soon it will be updated!</p>\n\n<p>Steps to take:<br /></p>\n\n<ul>\n<li>Assuming you have a <code>child theme</code> or else you create one like shown\n<a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow\">here.</a></li>\n<li>Create also a folder in that child-theme named <code>template-parts</code></li>\n<li>Copy following 2 files into that folder(from the parent <code>template-parts</code> folder): <code>content.php</code> and <code>content-single.php</code></li>\n<li>Open <code>content.php</code> and you see:</li>\n<li>line 27 <code>the_content( sprintf(</code> <strong>Remove this line or add <code>//</code> in front of it</strong></li>\n<li>line 28 <code>__( 'Continue reading</code> bla bla, <strong>Remove it or add <code>//</code> in front of it</strong></li>\n<li>Line 29 <code>get_the_title()</code> <strong>Add a semicolon behind it like this <code>get_the_title();</code></strong></li>\n<li>Line 30 <code>) );</code> <strong>Remove it or add <code>//</code> in front of it</strong></li>\n<li>Save this file now</li>\n<li>Open <code>content-single.php</code></li>\n<li>On line 16 you see <code><?php twentysixteen_excerpt(); ?></code> <strong>Remove this line or do like this <code><?php //twentysixteen_excerpt(); ?></code> (Add 2 backslashes)</strong></li>\n<li>Save this file now</li>\n</ul>\n\n<p>Now you activate in the <code>admin panel</code> Tab <code>Appearance/Themes</code> the child-theme you created.</p>\n\n<p>If I have been correct and you did as shown, you have what you want :)<br />\nFrom now on add/edit all you want in <code>functions.php</code> and <code>style.css</code> IN that <strong>child-theme</strong> (and of course you can add other files also in that <code>child-theme</code></p>\n\n<p>Note: I have made just a quick test with changes as shown, but...if some still is messing up, let it know.</p>\n\n<p>Cheers</p>\n"
},
{
"answer_id": 217446,
"author": "EmadFathy",
"author_id": 88446,
"author_profile": "https://wordpress.stackexchange.com/users/88446",
"pm_score": -1,
"selected": true,
"text": "<p>For the record and for anyone who comes next.</p>\n\n<p>I found the issue. Although the excerpts is a native WordPress feature it is not supported -in the right way- by the \"official\" \"pre-installed\" themes like the twenty-xxx series.</p>\n\n<p>Not Supporting (in the right way) a native feature isn't a common sense!!! It is a bad behavior of the official theme to display the excerpt above the full-post!!.</p>\n\n<p>Excerpts supported correctly by some third party themes like FlatBox: <a href=\"https://wordpress.org/themes/flatbox/\" rel=\"nofollow\">https://wordpress.org/themes/flatbox/</a></p>\n\n<p>For whom tried to help me I appreciate your effort and thank you.</p>\n"
},
{
"answer_id": 222299,
"author": "Şivā SankĂr",
"author_id": 88701,
"author_profile": "https://wordpress.stackexchange.com/users/88701",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"https://codex.wordpress.org/Function_Reference/has_excerpt\" rel=\"nofollow\"><code>has_excerpt()</code></a> for this, which checks whether the post has a manually set excerpt. The sample code below uses this function:</p>\n\n<pre><code><?php if ( has_excerpt() ) : // Only show custom excerpts not autoexcerpts ?>\n <span class=\"entry-subtitle\"><?php echo get_the_excerpt(); ?></span>\n<?php endif; ?>\n</code></pre>\n"
}
] |
2016/02/10
|
[
"https://wordpress.stackexchange.com/questions/217293",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88477/"
] |
I am trying to redirect the user after login/signup to profile page, but I am not sure why is it not putting the user nickname in url.
```
$current_user = wp_get_current_user();
function aloginuser( $user_id ) {
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id);
wp_redirect( "/profile/$current_user->user_login" );
exit;
}
add_action( 'user_register', 'aloginuser' );
```
It need to put site.com/profile/username
|
For the record and for anyone who comes next.
I found the issue. Although the excerpts is a native WordPress feature it is not supported -in the right way- by the "official" "pre-installed" themes like the twenty-xxx series.
Not Supporting (in the right way) a native feature isn't a common sense!!! It is a bad behavior of the official theme to display the excerpt above the full-post!!.
Excerpts supported correctly by some third party themes like FlatBox: <https://wordpress.org/themes/flatbox/>
For whom tried to help me I appreciate your effort and thank you.
|
217,299 |
<p>I'd like to know if there is a way to store WP_Query results in variables that I can then go ahead and insert anywhere on the page outside of the loop. For instance, say I want to get the feature image urls of three latest posts and I want to set variables in a way akin to the following.(note that the code below is for illustration purposes only as I have no idea how to parse the results from the loop for each post)</p>
<pre><code>$featureImageFirst = wp_get_attachment_url();
$featureImageSecond = wp_get_attachment_url();
$featureImageThird = wp_get_attachment_url();
</code></pre>
<p>In response to Soren's help I did this:</p>
<p>Hi Soren, please have a look at my code. This is what is happening.</p>
<pre><code> <?php
// Get latest three posts
$args = [
'posts_per_page' => 3,
'orderby' => 'date',
'order' => 'DESC'
];
// Fetch posts
$query = new WP_Query( $args );
if( $query->have_posts() )
{
while ( $query->have_posts() )
{
$query->the_post();
$featureImage[$current_post] = wp_get_attachment_url( get_post_thumbnail_id() );
}
}
?>
<div><img src="<?php echo $featureImage[0]; ?>"></div>
</code></pre>
<p>And this is what I get</p>
<pre><code><div><img src></div>
</code></pre>
|
[
{
"answer_id": 217302,
"author": "Sören Wrede",
"author_id": 68682,
"author_profile": "https://wordpress.stackexchange.com/users/68682",
"pm_score": 1,
"selected": false,
"text": "<p><strong>A</strong>) You can store the url in an array. The index of the post currently being displayed is <code>$current_post</code>. So you can use it also as array index.</p>\n\n<pre><code>if ( have_posts() ) : while ( have_posts() ) : the_post(); \n if ( has_post_thumbnail() ) {\n $featureImage[$current_post] = wp_get_attachment_url( get_post_thumbnail_id() );\n }\n endwhile;\nendif;\n</code></pre>\n\n<p>After the Loop you have:</p>\n\n<pre><code>$featureImage[0] (value: http://example.org/thumbnail_of_post_1.jpg)\n\n$featureImage[1] (value: http://example.org/thumbnail_of_post_2.jpg)\n\n$featureImage[2] (value: http://example.org/thumbnail_of_post_3.jpg)\n</code></pre>\n\n<p><strong>B</strong>) You can use multiple queries on a page. See <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Multiple_Loops\" rel=\"nofollow\">here</a> in the Codex. </p>\n"
},
{
"answer_id": 217440,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>From what I read, you read the URL/path to the post thumbnails is an array. We need to look at a couple of things here to make this as lean and predictable as possible</p>\n\n<h2>IMPORTANT CONSIDERATIONS</h2>\n\n<ul>\n<li><p>We do need some way to make sure that we get the latest three posts which actually have thumbnails to avoid unexpected output and bugs. It is always important to code with a mindset that my code will be hacked and it will fail and it will have bugs. Once you have that mindset, then you look at your code from a different angle, which make you to ask questions like: <em>What if this specific poece of code returns an error, how will it affect my output, how will I handle such errors safely and reliable in an expected, predictable way without breaking something else on my site</em></p></li>\n<li><p>We only really need the post ID's from the three latest posts, so to save resources, why not only query for post ID's</p></li>\n<li><p>When you need lean, non-paginated, to the point queries like this, I always use <code>get_posts</code> as it breaks pagination legally. This makes your query faster, which really helps on sites with many posts. You can still use <code>WP_Query</code>, but then you would need to remember to pass <code>'no_found_rows' => true</code> to your query arguments (<em>which is exactly what <code>get_posts</code> does btw</em>). Another plus using <code>get_posts</code> is that it just return the <code>$posts</code> property from the <code>WP_Query</code> instance. But this is all just personal preference</p></li>\n</ul>\n\n<h2>THE CODE</h2>\n\n<p>I prefer to write functions for long pieces of code to keep my templates as simple and short as poosible. I can then just call my functions where I need them or even use <code>do_action()</code> calls in my templates and then hook my functions to that specific action</p>\n\n<p>Anyway, lets look at the function; (<strong><em>NOTE:</strong> The following is untested, needs PHP 5.4+ and canbe made more dynamic as needed</em>)</p>\n\n<pre><code>function get_latest_post_thumbnails_urls()\n{\n // Set an empty variable which will hold our array of URL's\n $output = [];\n\n // Set our query args\n $args = [\n 'posts_per_page' => 3,\n 'fields' => 'ids', // Only get post ID's\n 'meta_query' => [ // Get posts which has thumbnails only\n [\n 'key' => '_thumbnail_id',\n 'compare' => 'EXISTS'\n ]\n ],\n // Any additional parameters you might need\n ];\n $q = get_posts( $args );\n\n // ALWAYS make sure we have posts, else return $output\n if ( !$q )\n return $output;\n\n // Ok, we have posts, lets loop through them and create an array of URL's\n foreach ( $q as $id ) \n $output[] = wp_get_attachment_url( get_post_thumbnail_id( $id ) );\n\n // Return our array\n return $output;\n}\n</code></pre>\n\n<p>We can now use <code>get_latest_post_thumbnails_urls();</code> anywhere where we need it. </p>\n\n<h2>USAGE</h2>\n\n<p>We need to remember, our function might return an empty array, or an array with 1, 2, or 3 URL's, so we must always make sure about this before we try to use anything to avoid bugs and have unexpected failures</p>\n\n<p>This is a probable safe usecase we can use</p>\n\n<pre><code>$urls = get_latest_post_thumbnails_urls();\n// Make sure we do not have an empty array\n\nif ( $urls ) {\n foreach ( $urls as $url ) {\n // Do something with your thumbnail url\n echo $url . '</br>'; // For testing, remove this\n }\n}\n</code></pre>\n"
}
] |
2016/02/10
|
[
"https://wordpress.stackexchange.com/questions/217299",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84666/"
] |
I'd like to know if there is a way to store WP\_Query results in variables that I can then go ahead and insert anywhere on the page outside of the loop. For instance, say I want to get the feature image urls of three latest posts and I want to set variables in a way akin to the following.(note that the code below is for illustration purposes only as I have no idea how to parse the results from the loop for each post)
```
$featureImageFirst = wp_get_attachment_url();
$featureImageSecond = wp_get_attachment_url();
$featureImageThird = wp_get_attachment_url();
```
In response to Soren's help I did this:
Hi Soren, please have a look at my code. This is what is happening.
```
<?php
// Get latest three posts
$args = [
'posts_per_page' => 3,
'orderby' => 'date',
'order' => 'DESC'
];
// Fetch posts
$query = new WP_Query( $args );
if( $query->have_posts() )
{
while ( $query->have_posts() )
{
$query->the_post();
$featureImage[$current_post] = wp_get_attachment_url( get_post_thumbnail_id() );
}
}
?>
<div><img src="<?php echo $featureImage[0]; ?>"></div>
```
And this is what I get
```
<div><img src></div>
```
|
From what I read, you read the URL/path to the post thumbnails is an array. We need to look at a couple of things here to make this as lean and predictable as possible
IMPORTANT CONSIDERATIONS
------------------------
* We do need some way to make sure that we get the latest three posts which actually have thumbnails to avoid unexpected output and bugs. It is always important to code with a mindset that my code will be hacked and it will fail and it will have bugs. Once you have that mindset, then you look at your code from a different angle, which make you to ask questions like: *What if this specific poece of code returns an error, how will it affect my output, how will I handle such errors safely and reliable in an expected, predictable way without breaking something else on my site*
* We only really need the post ID's from the three latest posts, so to save resources, why not only query for post ID's
* When you need lean, non-paginated, to the point queries like this, I always use `get_posts` as it breaks pagination legally. This makes your query faster, which really helps on sites with many posts. You can still use `WP_Query`, but then you would need to remember to pass `'no_found_rows' => true` to your query arguments (*which is exactly what `get_posts` does btw*). Another plus using `get_posts` is that it just return the `$posts` property from the `WP_Query` instance. But this is all just personal preference
THE CODE
--------
I prefer to write functions for long pieces of code to keep my templates as simple and short as poosible. I can then just call my functions where I need them or even use `do_action()` calls in my templates and then hook my functions to that specific action
Anyway, lets look at the function; (***NOTE:*** The following is untested, needs PHP 5.4+ and canbe made more dynamic as needed)
```
function get_latest_post_thumbnails_urls()
{
// Set an empty variable which will hold our array of URL's
$output = [];
// Set our query args
$args = [
'posts_per_page' => 3,
'fields' => 'ids', // Only get post ID's
'meta_query' => [ // Get posts which has thumbnails only
[
'key' => '_thumbnail_id',
'compare' => 'EXISTS'
]
],
// Any additional parameters you might need
];
$q = get_posts( $args );
// ALWAYS make sure we have posts, else return $output
if ( !$q )
return $output;
// Ok, we have posts, lets loop through them and create an array of URL's
foreach ( $q as $id )
$output[] = wp_get_attachment_url( get_post_thumbnail_id( $id ) );
// Return our array
return $output;
}
```
We can now use `get_latest_post_thumbnails_urls();` anywhere where we need it.
USAGE
-----
We need to remember, our function might return an empty array, or an array with 1, 2, or 3 URL's, so we must always make sure about this before we try to use anything to avoid bugs and have unexpected failures
This is a probable safe usecase we can use
```
$urls = get_latest_post_thumbnails_urls();
// Make sure we do not have an empty array
if ( $urls ) {
foreach ( $urls as $url ) {
// Do something with your thumbnail url
echo $url . '</br>'; // For testing, remove this
}
}
```
|
217,331 |
<p>I have a multi-site platform and I'm trying to share the menu that I have in main with other sites that are located in different folders.</p>
<p>This is the PHP tag in the main that pulls the menu which I also need in the header of other:</p>
<pre><code><?php dokan_header_user_menu(); ?>
</code></pre>
<p>I tried using it as it is in the header of <code>/site2</code>, and it didn't work. I also tried this:</p>
<pre><code><?php
include $_SERVER['DOCUMENT_ROOT']."site.com/wp-content/themes/dokan/header.php";
?>
</code></pre>
<p>still no luck. Any tips will greatly be appreciated.</p>
<p>Cheers!</p>
|
[
{
"answer_id": 217335,
"author": "fischi",
"author_id": 15680,
"author_profile": "https://wordpress.stackexchange.com/users/15680",
"pm_score": 2,
"selected": true,
"text": "<h1>Outsource this function into a Plugin</h1>\n<p>If you want a specific function available across multiple themes, it is best to have it in a Plugin, and activate it networkwide.</p>\n<h2>Find the function</h2>\n<p>Locate the function in the theme where it is available. You now have two possibilities:</p>\n<ul>\n<li>Delete the function from the current theme</li>\n<li>Make a duplicate of this function to be used for other themes (recommended)</li>\n</ul>\n<h2>Create the plugin</h2>\n<p>Create a file in your plugins directory, <code>f711-custom-menu-function.php</code> or whatever you want your plugin to be called.</p>\n<p>Inside this file you create the plugin header:</p>\n<pre><code>/*\nPlugin Name: F711 Menu Function \nPlugin URI: http://yourdomain.com\nDescription: Using the menu function across different themes in my network\nVersion: 1.0\nAuthor: Dave_O\nAuthor URI: http://wordpress.stackexchange.com/users/58774/dave-o\nLicense: GPL2\nLicense URI: https://www.gnu.org/licenses/gpl-2.0.html\nDomain Path: /languages\nText Domain: f711-menu-function\n*/\n</code></pre>\n<p>Now your Plugin is ready to use.</p>\n<h2>Populating your plugin</h2>\n<p>Copy the menu function of your theme, and give it a specific prefix, for example like this:</p>\n<pre><code>function f711_dokan_header_user_menu() {\n // insert your functionality from the original function here\n}\n</code></pre>\n<h2>Activate your plugin</h2>\n<p>This is selfexplanatory. Just be sure to activate it networkwide</p>\n<h2>Using it in different themes</h2>\n<p>Now you can call <code>f711_dokan_header_user_menu()</code> in all the themes available in your network, using the exact same function.</p>\n<h2>Cleanup</h2>\n<p>Take your original theme where the function comes from, and alter the header to use the new plugin function. Afterwards you can remove the old themespecific function to avoid redundancies.</p>\n"
},
{
"answer_id": 264025,
"author": "Muhammad Abdullah",
"author_id": 117908,
"author_profile": "https://wordpress.stackexchange.com/users/117908",
"pm_score": 3,
"selected": false,
"text": "<p>That's an old question, here is another and easy solution for WORDPRESS MULTISITE MENU sharing across all network sites, </p>\n\n<p>Not only menu you can use the same method to share anything other then widgets across all the network sites.</p>\n\n<p>here is the solution : Edit your Header.php </p>\n\n<pre><code>//store the current blog_id - Use this function at the start of the function that you want to share\n\nglobal $blog_id;\n$current_blog_id = $blog_id;\n\n//switch to the main blog which will have an id of 1\nswitch_to_blog(1);\n\n//output the WordPress navigation menu - incase of menu-sharing use this\n\nwp_nav_menu( \n //add your arguments here\n);\n\n//switch back to the current blog being viewed - before ending of the function\n\nswitch_to_blog($current_blog_id); \n</code></pre>\n"
}
] |
2016/02/11
|
[
"https://wordpress.stackexchange.com/questions/217331",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58774/"
] |
I have a multi-site platform and I'm trying to share the menu that I have in main with other sites that are located in different folders.
This is the PHP tag in the main that pulls the menu which I also need in the header of other:
```
<?php dokan_header_user_menu(); ?>
```
I tried using it as it is in the header of `/site2`, and it didn't work. I also tried this:
```
<?php
include $_SERVER['DOCUMENT_ROOT']."site.com/wp-content/themes/dokan/header.php";
?>
```
still no luck. Any tips will greatly be appreciated.
Cheers!
|
Outsource this function into a Plugin
=====================================
If you want a specific function available across multiple themes, it is best to have it in a Plugin, and activate it networkwide.
Find the function
-----------------
Locate the function in the theme where it is available. You now have two possibilities:
* Delete the function from the current theme
* Make a duplicate of this function to be used for other themes (recommended)
Create the plugin
-----------------
Create a file in your plugins directory, `f711-custom-menu-function.php` or whatever you want your plugin to be called.
Inside this file you create the plugin header:
```
/*
Plugin Name: F711 Menu Function
Plugin URI: http://yourdomain.com
Description: Using the menu function across different themes in my network
Version: 1.0
Author: Dave_O
Author URI: http://wordpress.stackexchange.com/users/58774/dave-o
License: GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Domain Path: /languages
Text Domain: f711-menu-function
*/
```
Now your Plugin is ready to use.
Populating your plugin
----------------------
Copy the menu function of your theme, and give it a specific prefix, for example like this:
```
function f711_dokan_header_user_menu() {
// insert your functionality from the original function here
}
```
Activate your plugin
--------------------
This is selfexplanatory. Just be sure to activate it networkwide
Using it in different themes
----------------------------
Now you can call `f711_dokan_header_user_menu()` in all the themes available in your network, using the exact same function.
Cleanup
-------
Take your original theme where the function comes from, and alter the header to use the new plugin function. Afterwards you can remove the old themespecific function to avoid redundancies.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.