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
|
---|---|---|---|---|---|---|
227,001 |
<p>I'm trying to modify the <a href="https://wordpress.org/plugins/gd-mylist/" rel="nofollow">My Wish List plugin</a> so that I can retrieve some custom fields (I'm using the <a href="https://www.advancedcustomfields.com/" rel="nofollow">Advanced Custom Fields plugin</a> to create my custom fields in the admin end).</p>
<p>The plugin uses the custom query below to pull out specific data, but I want to retrieve each post's custom fields as well in that loop. I'm pretty clueless when it comes to MySQL, but I'm assuming I need to add a line to <code>SELECT</code> like this to the query to be able to retrieve custom fields as well right?:</p>
<pre><code>b.post_meta AS posts_meta,
</code></pre>
<p><strong>Here's the plugin's MySQL query in full:</strong></p>
<pre><code>$posts = $wpdb->get_results(
$wpdb->prepare(
'SELECT
b.ID AS posts_id,
b.post_title AS posts_title,
b.post_content AS posts_content,
b.post_date AS posts_date,
c.ID AS authors_id,
c.display_name AS authors_name
FROM '.$var_setting['table'].' a
LEFT JOIN '.$var_setting['table_posts'].' b
ON a.item_id = b.ID
LEFT JOIN '.$var_setting['table_users']." c
ON c.ID = b.post_author
WHERE
b.post_status = 'publish'
AND a.user_id = %s
ORDER BY b.post_title DESC",
$user_id
)
);
</code></pre>
<p><strong>And here's the foreach loop that the plugin uses to pull in the content to display:</strong></p>
<pre><code>if ($posts != null) {
if ($share_list == 'yes') {
$html = '';
$html = file_get_contents($templates_html['box_list_share'].$locale);
$permalink = get_permalink();
if (strpos($permalink, '?') !== false) {
$html = str_replace('##pageID##', $permalink.'&', $html);
} else {
$html = str_replace('##pageID##', $permalink.'?', $html);
}
$html = str_replace('##userID##', $user_id, $html);
echo($html);
}
if ($show_count == 'yes') {
$html = '';
$html = file_get_contents($templates_html['box_list_count'].$locale);
$count = $wpdb->num_rows;
$html = str_replace('##count##', $count, $html);
echo($html);
}
foreach ($posts as $post) {
$postId = $post->posts_id;
$postDate = get_the_date('F j, Y', $postId);
$postAuthorId = $post->authors_id;
$postAuthorName = $post->authors_name;
$postContent = $post->posts_content;
$postImage = wp_get_attachment_url(get_post_thumbnail_id($postId));
$postTitle = $post->posts_title;
$portTitleLang = extract_title($postTitle);
$postUrl = get_permalink($postId);
/* BEGIN : OSU EDIT */
$postACF_sc = get_post_meta($postId, 'sc_link'); /* trying to get a specific custom field for each post */
/* END : OSU EDIT */
$args = array(
'styletarget' => 'mylist',
'item_id' => $postId,
);
$html = '';
$html = file_get_contents($templates_html['box_list'].$locale);
$html = str_replace('##postUrl##', $postUrl, $html);
/* BEGIN : OSU EDIT */
$html = str_replace('##postACF_sc##', $postACF_sc, $html); /* These str_replace() are how the plugin lets you add things like ##postUrl## using its templating system to display the permalink via AJAX */
/* END : OSU EDIT */
$html = str_replace('##postImage##', $postImage, $html);
if (strpos($postTitle, '<!--:') !== false || strpos($postTitle, '[:') !== false) { //means use mqtranlate or qtranlate-x
$html = str_replace('##postTitle##', $portTitleLang[$lang], $html);
} else {
$html = str_replace('##postTitle##', $postTitle, $html);
}
$html = str_replace('##postDate##', $postDate, $html);
$html = str_replace('##postAuthorName##', $postAuthorName, $html);
$html = str_replace('##postContent##', $postContent, $html);
$html = str_replace('##postBtn##', gd_show_mylist_btn($args), $html);
echo($html);
}
} else {
$html = file_get_contents($templates_html['box_list_empty'].$locale);
echo($html);
}
</code></pre>
|
[
{
"answer_id": 227002,
"author": "Karthikeyani Srijish",
"author_id": 86125,
"author_profile": "https://wordpress.stackexchange.com/users/86125",
"pm_score": 5,
"selected": true,
"text": "<p>No, it is not possible to create third level menu in admin panel. If you look at the definition of <strong>add_submenu_page</strong>, you need to mention the parent slug name. <strong>For eg:</strong></p>\n\n<pre><code>add_menu_page ( 'Test Menu', 'Test Menu', 'read', 'testmainmenu', '', '' );\nadd_submenu_page ( 'testmainmenu', 'Test Menu', 'Child1', 'read', 'child1', '');\n</code></pre>\n\n<p>The first parameter of the <strong>add_submenu_page</strong> will be parent slug name. So you may think we can write <strong>child1</strong> as <em>parent slug name</em> to create the third level. <strong>Eg:</strong></p>\n\n<pre><code>add_submenu_page ( 'child1', 'Test Menu', 'Child2', 'read', 'child2', '');\n</code></pre>\n\n<p>But this will not work. Look at the parameters definition and source section in this <a href=\"https://developer.wordpress.org/reference/functions/add_submenu_page/\" rel=\"noreferrer\">link</a>. It clearly states that, you can only use the name of '<strong>main menu of the plugin</strong>' or the <strong>file name</strong> of the WordPress plugin in <strong>parent slug name</strong>. So it is not possible to create submenus more than once in admin panel. However, you can create <em>n</em> number of sub menus in front end. To know more about creating menus and sub menus in front end, <a href=\"https://www.elegantthemes.com/blog/tips-tricks/how-to-create-custom-menu-structures-in-wordpress\" rel=\"noreferrer\">refer</a></p>\n"
},
{
"answer_id": 381236,
"author": "Olekk",
"author_id": 200125,
"author_profile": "https://wordpress.stackexchange.com/users/200125",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote it myself using JS. It's just for one project and I didn't want to spend much time on it, so you have to adjust it for your personal needs ;)</p>\n<p>It hides chosen menu elements and creates a button which toggles them.</p>\n<p>You add it to the end of file\n/wp-admin/menu-header.php</p>\n<pre><code><script>\n // Here is list of classes of chosen menu elements you want to toggle - li.menu-icon-slug\n let my_products = document.querySelectorAll("li.menu-icon-okna, li.menu-icon-drzwi, li.menu-icon-bramy_garazowe");\n \n my_products.forEach(prod => {\n prod.style.backgroundColor = "#283338";\n })\n \n // "Produkty" is a text on a toggling button, change it\n let my_button = jQuery('<li class="menu-top"><a class="menu-top"><div class="wp-menu-image dashicons-before dashicons-admin-post"></div><div class="wp-menu-name">Produkty</div></a></li>')[0];\n\n document.querySelector("ul#adminmenu").insertBefore(my_button, my_products[0]);\n\n function toggleProducts() {\n my_products.forEach(prod => {\n if(prod.style.display != "none") prod.style.display = "none";\n else prod.style.display = "block";\n })\n }\n toggleProducts();\n\n my_button.querySelector("a").addEventListener("click", toggleProducts);\n\n</script>\n\n</code></pre>\n<p>.\n.\nwith no jQuery:</p>\n<pre><code><script>\n // Here is list of classes of chosen menu elements you want to toggle - li.menu-icon-slug\n let my_products = document.querySelectorAll("li.menu-icon-okna, li.menu-icon-drzwi, li.menu-icon-bramy_garazowe");\n\n my_products.forEach(prod => {\n prod.style.backgroundColor = "#283338";\n })\n\n let prod_li = document.createElement("li");\n prod_li.classList.add("menu-top");\n\n let prod_a = document.createElement("a");\n prod_a.classList.add("menu-top");\n\n let prod_div1 = document.createElement("div");\n prod_div1.classList.add("wp-menu-image","dashicons-before","dashicons-admin-post")\n\n let prod_div2 = document.createElement("div");\n prod_div2.classList.add("wp-menu-name");\n\n // Text on a button:\n prod_div2.appendChild(document.createTextNode("Produkty"));\n\n prod_a.append(prod_div1, prod_div2);\n prod_li.append(prod_a);\n\n document.querySelector("ul#adminmenu").insertBefore(prod_li, my_products[0]);\n\n function toggleProducts() {\n my_products.forEach(prod => {\n if(prod.style.display != "none") prod.style.display = "none";\n else prod.style.display = "block";\n })\n }\n toggleProducts();\n\n prod_a.addEventListener("click", toggleProducts);\n\n</script>\n\n</code></pre>\n"
}
] |
2016/05/18
|
[
"https://wordpress.stackexchange.com/questions/227001",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/2685/"
] |
I'm trying to modify the [My Wish List plugin](https://wordpress.org/plugins/gd-mylist/) so that I can retrieve some custom fields (I'm using the [Advanced Custom Fields plugin](https://www.advancedcustomfields.com/) to create my custom fields in the admin end).
The plugin uses the custom query below to pull out specific data, but I want to retrieve each post's custom fields as well in that loop. I'm pretty clueless when it comes to MySQL, but I'm assuming I need to add a line to `SELECT` like this to the query to be able to retrieve custom fields as well right?:
```
b.post_meta AS posts_meta,
```
**Here's the plugin's MySQL query in full:**
```
$posts = $wpdb->get_results(
$wpdb->prepare(
'SELECT
b.ID AS posts_id,
b.post_title AS posts_title,
b.post_content AS posts_content,
b.post_date AS posts_date,
c.ID AS authors_id,
c.display_name AS authors_name
FROM '.$var_setting['table'].' a
LEFT JOIN '.$var_setting['table_posts'].' b
ON a.item_id = b.ID
LEFT JOIN '.$var_setting['table_users']." c
ON c.ID = b.post_author
WHERE
b.post_status = 'publish'
AND a.user_id = %s
ORDER BY b.post_title DESC",
$user_id
)
);
```
**And here's the foreach loop that the plugin uses to pull in the content to display:**
```
if ($posts != null) {
if ($share_list == 'yes') {
$html = '';
$html = file_get_contents($templates_html['box_list_share'].$locale);
$permalink = get_permalink();
if (strpos($permalink, '?') !== false) {
$html = str_replace('##pageID##', $permalink.'&', $html);
} else {
$html = str_replace('##pageID##', $permalink.'?', $html);
}
$html = str_replace('##userID##', $user_id, $html);
echo($html);
}
if ($show_count == 'yes') {
$html = '';
$html = file_get_contents($templates_html['box_list_count'].$locale);
$count = $wpdb->num_rows;
$html = str_replace('##count##', $count, $html);
echo($html);
}
foreach ($posts as $post) {
$postId = $post->posts_id;
$postDate = get_the_date('F j, Y', $postId);
$postAuthorId = $post->authors_id;
$postAuthorName = $post->authors_name;
$postContent = $post->posts_content;
$postImage = wp_get_attachment_url(get_post_thumbnail_id($postId));
$postTitle = $post->posts_title;
$portTitleLang = extract_title($postTitle);
$postUrl = get_permalink($postId);
/* BEGIN : OSU EDIT */
$postACF_sc = get_post_meta($postId, 'sc_link'); /* trying to get a specific custom field for each post */
/* END : OSU EDIT */
$args = array(
'styletarget' => 'mylist',
'item_id' => $postId,
);
$html = '';
$html = file_get_contents($templates_html['box_list'].$locale);
$html = str_replace('##postUrl##', $postUrl, $html);
/* BEGIN : OSU EDIT */
$html = str_replace('##postACF_sc##', $postACF_sc, $html); /* These str_replace() are how the plugin lets you add things like ##postUrl## using its templating system to display the permalink via AJAX */
/* END : OSU EDIT */
$html = str_replace('##postImage##', $postImage, $html);
if (strpos($postTitle, '<!--:') !== false || strpos($postTitle, '[:') !== false) { //means use mqtranlate or qtranlate-x
$html = str_replace('##postTitle##', $portTitleLang[$lang], $html);
} else {
$html = str_replace('##postTitle##', $postTitle, $html);
}
$html = str_replace('##postDate##', $postDate, $html);
$html = str_replace('##postAuthorName##', $postAuthorName, $html);
$html = str_replace('##postContent##', $postContent, $html);
$html = str_replace('##postBtn##', gd_show_mylist_btn($args), $html);
echo($html);
}
} else {
$html = file_get_contents($templates_html['box_list_empty'].$locale);
echo($html);
}
```
|
No, it is not possible to create third level menu in admin panel. If you look at the definition of **add\_submenu\_page**, you need to mention the parent slug name. **For eg:**
```
add_menu_page ( 'Test Menu', 'Test Menu', 'read', 'testmainmenu', '', '' );
add_submenu_page ( 'testmainmenu', 'Test Menu', 'Child1', 'read', 'child1', '');
```
The first parameter of the **add\_submenu\_page** will be parent slug name. So you may think we can write **child1** as *parent slug name* to create the third level. **Eg:**
```
add_submenu_page ( 'child1', 'Test Menu', 'Child2', 'read', 'child2', '');
```
But this will not work. Look at the parameters definition and source section in this [link](https://developer.wordpress.org/reference/functions/add_submenu_page/). It clearly states that, you can only use the name of '**main menu of the plugin**' or the **file name** of the WordPress plugin in **parent slug name**. So it is not possible to create submenus more than once in admin panel. However, you can create *n* number of sub menus in front end. To know more about creating menus and sub menus in front end, [refer](https://www.elegantthemes.com/blog/tips-tricks/how-to-create-custom-menu-structures-in-wordpress)
|
227,003 |
<p>I have a simple function, which returns the content of a page with the given pageID:</p>
<pre><code>function get_page_content(){
$id = $_REQUEST['id'];
$page_data = get_page($id);
echo apply_filters('the_content', $page_data->post_content);
//echo do_shortcode($page_data -> post_content);
wp_die();
}
add_action( 'wp_ajax_nopriv_get_page_content', 'get_page_content' );
add_action( 'wp_ajax_get_page_content', 'get_page_content' );
</code></pre>
<p>But after an Update of WP and some Plugins the returned content still containes unresolved shortcodes like so:</p>
<pre><code>[vc_row row_type=“row“ use_row_as_full_screen_section=“no“ type=“grid“ text_align=“left“ background_image_as_pattern=“without_pattern“][vc_column width=“1/1″]
</code></pre>
<p>The shortcodes come from a Plugin called <strong>Visual Composer</strong> (which got updated in the process to the latest version)</p>
<p><strong>Question:</strong>
How can i render the shortcodes befor i return the content?
I tried both</p>
<pre><code>echo apply_filters('the_content', $page_data->post_content);
</code></pre>
<p>and</p>
<pre><code>echo do_shortcode($page_data -> post_content);
</code></pre>
|
[
{
"answer_id": 227028,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p><code>the_content</code> is usually \"executed\" in the context of a loop when all relevant global data is set. You should try to mimic it by using code like</p>\n\n<pre><code>function get_page_content(){\n global $post;\n\n $id = $_REQUEST['id'];\n\n $post = get_page($id);\n setup_postdata($post);\n echo apply_filters('the_content', $post->post_content);\n //echo do_shortcode($page_data -> post_content);\n wp_die();\n}\nadd_action( 'wp_ajax_nopriv_get_page_content', 'get_page_content' );\nadd_action( 'wp_ajax_get_page_content', 'get_page_content' );\n</code></pre>\n\n<p>This may or may not be enough depending on the specific checks the plugin does, and you might need to construct the main query object probably by using <a href=\"https://developer.wordpress.org/reference/functions/query_posts/\" rel=\"nofollow\">query_posts</a> (one of the very rare cases in which it is ok to use that function).</p>\n"
},
{
"answer_id": 230092,
"author": "Dhinju Divakaran",
"author_id": 96981,
"author_profile": "https://wordpress.stackexchange.com/users/96981",
"pm_score": 4,
"selected": true,
"text": "<p>Since version 4.9 visual composer added shortcode lazy loading. To use VC shortcodes on AJAX content use this function before printing the content <code>WPBMap::addAllMappedShortcodes();</code>. So below code may help you,</p>\n\n<pre><code>function get_page_content(){\n\n $id = $_REQUEST['id'];\n\n $page_data = get_page($id);\n\n WPBMap::addAllMappedShortcodes();\n\n echo apply_filters('the_content', $page_data->post_content);\n wp_die();\n}\nadd_action( 'wp_ajax_nopriv_get_page_content', 'get_page_content' );\nadd_action( 'wp_ajax_get_page_content', 'get_page_content' );\n</code></pre>\n"
}
] |
2016/05/18
|
[
"https://wordpress.stackexchange.com/questions/227003",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63609/"
] |
I have a simple function, which returns the content of a page with the given pageID:
```
function get_page_content(){
$id = $_REQUEST['id'];
$page_data = get_page($id);
echo apply_filters('the_content', $page_data->post_content);
//echo do_shortcode($page_data -> post_content);
wp_die();
}
add_action( 'wp_ajax_nopriv_get_page_content', 'get_page_content' );
add_action( 'wp_ajax_get_page_content', 'get_page_content' );
```
But after an Update of WP and some Plugins the returned content still containes unresolved shortcodes like so:
```
[vc_row row_type=“row“ use_row_as_full_screen_section=“no“ type=“grid“ text_align=“left“ background_image_as_pattern=“without_pattern“][vc_column width=“1/1″]
```
The shortcodes come from a Plugin called **Visual Composer** (which got updated in the process to the latest version)
**Question:**
How can i render the shortcodes befor i return the content?
I tried both
```
echo apply_filters('the_content', $page_data->post_content);
```
and
```
echo do_shortcode($page_data -> post_content);
```
|
Since version 4.9 visual composer added shortcode lazy loading. To use VC shortcodes on AJAX content use this function before printing the content `WPBMap::addAllMappedShortcodes();`. So below code may help you,
```
function get_page_content(){
$id = $_REQUEST['id'];
$page_data = get_page($id);
WPBMap::addAllMappedShortcodes();
echo apply_filters('the_content', $page_data->post_content);
wp_die();
}
add_action( 'wp_ajax_nopriv_get_page_content', 'get_page_content' );
add_action( 'wp_ajax_get_page_content', 'get_page_content' );
```
|
227,006 |
<p>I created page templates that use the page slug, for example, <code>page-contact.php</code>, <code>page-gallery.php</code> etc. or page id, for example, <code>page-2.php</code>, <code>page-11.php</code> etc.</p>
<p>How can I move these templates to a subfolder, for example <code>/mytheme/pages/</code>?</p>
|
[
{
"answer_id": 227036,
"author": "Landing on Jupiter",
"author_id": 74534,
"author_profile": "https://wordpress.stackexchange.com/users/74534",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress will recognize template files in /YOUR_THEME/page-templates/: <a href=\"https://developer.wordpress.org/themes/basics/organizing-theme-files/#page-templates-folder\" rel=\"nofollow\">https://developer.wordpress.org/themes/basics/organizing-theme-files/#page-templates-folder</a></p>\n"
},
{
"answer_id": 227053,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 3,
"selected": false,
"text": "<p>/YOUR_THEME/page-templates/ will only work for custom page templates assigned on the admin page edit screen, not for page-$slug or page-$id named templates.</p>\n\n<p>The correct filter hook in my view is page_template, but you don't (I assume!) want to throw out any other possible templates for your pages, not least because you're bound to have some pages on your site for which you haven't made a /my-sub-dir/page-$slug.php template file.</p>\n\n<p>The page_template filter hook is called just after WP has found a template for the page using the standard template hierarchy. It would be handy if there was a filter to let you inject your additional template into the right part of the template hierarchy, but in the absence of that we'll need to replicate the search for page templates from WordPress's own get_page_template() function, found in /wp-includes/template.php:</p>\n\n<pre><code>function get_page_template() {\n $id = get_queried_object_id();\n $template = get_page_template_slug();\n $pagename = get_query_var('pagename');\n\n if ( ! $pagename && $id ) {\n // If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object\n $post = get_queried_object();\n if ( $post )\n $pagename = $post->post_name;\n }\n\n $templates = array();\n if ( $template && 0 === validate_file( $template ) )\n $templates[] = $template;\n if ( $pagename )\n $templates[] = \"page-$pagename.php\";\n if ( $id )\n $templates[] = \"page-$id.php\";\n $templates[] = 'page.php';\n\n return get_query_template( 'page', $templates );\n}\n</code></pre>\n\n<p>This function builds an array of possible templates for Pages. get_query_template() then uses locate_template() to run through the array and return the filename of the first template found.</p>\n\n<p>As we can't hook into the list of proposed templates, we'll sadly have to duplicate some of this work.</p>\n\n<p>Here's our own function:</p>\n\n<pre><code>function tbdn_get_page_template() {\n $id = get_queried_object_id();\n $template = get_page_template_slug();\n $pagename = get_query_var('pagename');\n\n if ( ! $pagename && $id ) {\n // If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object\n $post = get_queried_object();\n if ( $post )\n $pagename = $post->post_name;\n }\n\n $templates = array();\n\n if ( $template && 0 === validate_file( $template ) )\n $templates[] = $template;\n // if there's a custom template then still give that priority\n\n if ( $pagename )\n $templates[] = \"our-sub-dir/page-$pagename.php\";\n // change the default search for the page-$slug template to use our directory\n // you could also look in the theme root directory either before or after this\n\n if ( $id )\n $templates[] = \"our-sub-dir/page-$id.php\";\n $templates[] = 'page.php';\n\n /* Don't call get_query_template again!!!\n // return get_query_template( 'page', $templates );\n We also reproduce the key code of get_query_template() - we don't want to call it or we'll get stuck in a loop .\n We can remove lines of code that we know won't apply for pages, leaving us with...\n */\n\n $template = locate_template( $templates );\n\n return $template;\n}\n\nadd_filter( 'page_template', 'tbdn_get_page_template' );\n</code></pre>\n\n<p>Caveats:</p>\n\n<p>1 - I haven't tested this, but if you're up to messing around with the template hierarchy then you should certainly be able to follow, test & adjust my code which is mostly copied from WP anyway.</p>\n\n<p>2 - If future core code ever changes the template hierarchy for pages then the code above will go out-of-date.</p>\n"
},
{
"answer_id": 312624,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n<p>I posted the details on <a href=\"https://wordpress.stackexchange.com/a/312611/110572\">this answer</a>. Here, the CODE is adjusted based on two specific differences of this question:</p>\n<ol>\n<li><p>Move page templates to sub-directory without fall back. For example, it'll check <code>THEME/sub-directory/page-{slug}.php</code>, but it'll <strong>not</strong> check <code>THEME/page-{slug}.php</code>, because that's what the OP asked. However, the option with fallback in the other answer is better, especially in case of child theme (as the parent theme may depend on the fallback).</p>\n</li>\n<li><p>It'll move both <code>page-{slug}.php</code> and <code>page-{id}.php</code> to the sub-directory.</p>\n</li>\n</ol>\n</blockquote>\n<hr />\n<h2>Filter Hook to use:</h2>\n<p>The best way to move page templates to a sub-directory, say <code>/THEME/page-templates/</code>, is to use the <strong><code>page_template_hierarchy</code></strong> filter hook.</p>\n<blockquote>\n<p><em><strong>Note:</strong></em> the original filter hook is <strong><a href=\"https://developer.wordpress.org/reference/hooks/type_template_hierarchy/\" rel=\"nofollow noreferrer\">{$type}_template_hierarchy</a></strong>, which becomes <code>page_template_hierarchy</code> when <code>$type</code> is <code>page</code>.</p>\n</blockquote>\n<h2>Sample CODE:</h2>\n<pre><code><?php\n/*\nPlugin Name: WPSE Page Template move to Sub Directory\nPlugin URI: https://wordpress.stackexchange.com/a/227006/110572\nDescription: WPSE Page Template move to a Sub Directory\nVersion: 1.0.0\nAuthor: Fayaz Ahmed\nAuthor URI: https://www.fayazmiraz.com/\n*/\n\n// defining the sub-directory so that it can be easily accessed from elsewhere as well.\ndefine( 'WPSE_PAGE_TEMPLATE_SUB_DIR', 'page-templates' );\n\nfunction wpse227006_page_template_add_subdir( $templates = array() ) {\n // Generally this doesn't happen, unless another plugin / theme does modifications\n // of their own. In that case, it's better not to mess with it again with our code.\n if( empty( $templates ) || ! is_array( $templates ) || count( $templates ) < 3 )\n return $templates;\n\n $page_tpl_idx = 0;\n $cnt = count( $templates );\n if( $templates[0] === get_page_template_slug() ) {\n // if there is custom template, then our page-{slug}.php template is at the next index \n $page_tpl_idx = 1;\n }\n\n // the last one in $templates is page.php, so\n // all but the last one in $templates starting from $page_tpl_idx will be moved to sub-directory\n for( $i = $page_tpl_idx; $i < $cnt - 1; $i++ ) {\n $templates[$i] = WPSE_PAGE_TEMPLATE_SUB_DIR . '/' . $templates[$i];\n }\n\n return $templates;\n}\n// the original filter hook is {$type}_template_hierarchy,\n// wihch is located in wp-includes/template.php file\nadd_filter( 'page_template_hierarchy', 'wpse227006_page_template_add_subdir' );\n</code></pre>\n"
}
] |
2016/05/18
|
[
"https://wordpress.stackexchange.com/questions/227006",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94295/"
] |
I created page templates that use the page slug, for example, `page-contact.php`, `page-gallery.php` etc. or page id, for example, `page-2.php`, `page-11.php` etc.
How can I move these templates to a subfolder, for example `/mytheme/pages/`?
|
/YOUR\_THEME/page-templates/ will only work for custom page templates assigned on the admin page edit screen, not for page-$slug or page-$id named templates.
The correct filter hook in my view is page\_template, but you don't (I assume!) want to throw out any other possible templates for your pages, not least because you're bound to have some pages on your site for which you haven't made a /my-sub-dir/page-$slug.php template file.
The page\_template filter hook is called just after WP has found a template for the page using the standard template hierarchy. It would be handy if there was a filter to let you inject your additional template into the right part of the template hierarchy, but in the absence of that we'll need to replicate the search for page templates from WordPress's own get\_page\_template() function, found in /wp-includes/template.php:
```
function get_page_template() {
$id = get_queried_object_id();
$template = get_page_template_slug();
$pagename = get_query_var('pagename');
if ( ! $pagename && $id ) {
// If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object
$post = get_queried_object();
if ( $post )
$pagename = $post->post_name;
}
$templates = array();
if ( $template && 0 === validate_file( $template ) )
$templates[] = $template;
if ( $pagename )
$templates[] = "page-$pagename.php";
if ( $id )
$templates[] = "page-$id.php";
$templates[] = 'page.php';
return get_query_template( 'page', $templates );
}
```
This function builds an array of possible templates for Pages. get\_query\_template() then uses locate\_template() to run through the array and return the filename of the first template found.
As we can't hook into the list of proposed templates, we'll sadly have to duplicate some of this work.
Here's our own function:
```
function tbdn_get_page_template() {
$id = get_queried_object_id();
$template = get_page_template_slug();
$pagename = get_query_var('pagename');
if ( ! $pagename && $id ) {
// If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object
$post = get_queried_object();
if ( $post )
$pagename = $post->post_name;
}
$templates = array();
if ( $template && 0 === validate_file( $template ) )
$templates[] = $template;
// if there's a custom template then still give that priority
if ( $pagename )
$templates[] = "our-sub-dir/page-$pagename.php";
// change the default search for the page-$slug template to use our directory
// you could also look in the theme root directory either before or after this
if ( $id )
$templates[] = "our-sub-dir/page-$id.php";
$templates[] = 'page.php';
/* Don't call get_query_template again!!!
// return get_query_template( 'page', $templates );
We also reproduce the key code of get_query_template() - we don't want to call it or we'll get stuck in a loop .
We can remove lines of code that we know won't apply for pages, leaving us with...
*/
$template = locate_template( $templates );
return $template;
}
add_filter( 'page_template', 'tbdn_get_page_template' );
```
Caveats:
1 - I haven't tested this, but if you're up to messing around with the template hierarchy then you should certainly be able to follow, test & adjust my code which is mostly copied from WP anyway.
2 - If future core code ever changes the template hierarchy for pages then the code above will go out-of-date.
|
227,007 |
<p>I'm having issues with images getting badly compressed when uploaded to my site. It's not an issue with photographs, but is very noticeable for images with solid blocks of colour and text.</p>
<p>I've uploaded a PNG with a solid grey background overlaid with white text, and it's being badly compressed when WordPress resizes it to the various alternative sizes.</p>
<p><a href="http://www.wondercompany.co.uk/wp-content/uploads/2016/05/tc1.png" rel="nofollow">Original image</a></p>
<p><a href="http://www.wondercompany.co.uk/wp-content/uploads/2016/05/tc1-1024x682.png" rel="nofollow">Large featured image size</a></p>
<p>Unfortunately I don't have enough reputation to post more than 2 links, but you can see in the resized Large version that the text has become very blurry, and the solid grey background has a noticeable strobe to it.</p>
<p>I know you can turn off / adjust the level of JPG image compression, but as far as I know WordPress shouldn't be compressing PNGs at all, so I'm at a loss to figure out what's going on.</p>
<p>What could be causing this? Is this potentially an issue with the compression / resize software on my server? Or is there a way to tell WordPress not to compress PNGs, like there is with JPEGs?</p>
|
[
{
"answer_id": 227036,
"author": "Landing on Jupiter",
"author_id": 74534,
"author_profile": "https://wordpress.stackexchange.com/users/74534",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress will recognize template files in /YOUR_THEME/page-templates/: <a href=\"https://developer.wordpress.org/themes/basics/organizing-theme-files/#page-templates-folder\" rel=\"nofollow\">https://developer.wordpress.org/themes/basics/organizing-theme-files/#page-templates-folder</a></p>\n"
},
{
"answer_id": 227053,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 3,
"selected": false,
"text": "<p>/YOUR_THEME/page-templates/ will only work for custom page templates assigned on the admin page edit screen, not for page-$slug or page-$id named templates.</p>\n\n<p>The correct filter hook in my view is page_template, but you don't (I assume!) want to throw out any other possible templates for your pages, not least because you're bound to have some pages on your site for which you haven't made a /my-sub-dir/page-$slug.php template file.</p>\n\n<p>The page_template filter hook is called just after WP has found a template for the page using the standard template hierarchy. It would be handy if there was a filter to let you inject your additional template into the right part of the template hierarchy, but in the absence of that we'll need to replicate the search for page templates from WordPress's own get_page_template() function, found in /wp-includes/template.php:</p>\n\n<pre><code>function get_page_template() {\n $id = get_queried_object_id();\n $template = get_page_template_slug();\n $pagename = get_query_var('pagename');\n\n if ( ! $pagename && $id ) {\n // If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object\n $post = get_queried_object();\n if ( $post )\n $pagename = $post->post_name;\n }\n\n $templates = array();\n if ( $template && 0 === validate_file( $template ) )\n $templates[] = $template;\n if ( $pagename )\n $templates[] = \"page-$pagename.php\";\n if ( $id )\n $templates[] = \"page-$id.php\";\n $templates[] = 'page.php';\n\n return get_query_template( 'page', $templates );\n}\n</code></pre>\n\n<p>This function builds an array of possible templates for Pages. get_query_template() then uses locate_template() to run through the array and return the filename of the first template found.</p>\n\n<p>As we can't hook into the list of proposed templates, we'll sadly have to duplicate some of this work.</p>\n\n<p>Here's our own function:</p>\n\n<pre><code>function tbdn_get_page_template() {\n $id = get_queried_object_id();\n $template = get_page_template_slug();\n $pagename = get_query_var('pagename');\n\n if ( ! $pagename && $id ) {\n // If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object\n $post = get_queried_object();\n if ( $post )\n $pagename = $post->post_name;\n }\n\n $templates = array();\n\n if ( $template && 0 === validate_file( $template ) )\n $templates[] = $template;\n // if there's a custom template then still give that priority\n\n if ( $pagename )\n $templates[] = \"our-sub-dir/page-$pagename.php\";\n // change the default search for the page-$slug template to use our directory\n // you could also look in the theme root directory either before or after this\n\n if ( $id )\n $templates[] = \"our-sub-dir/page-$id.php\";\n $templates[] = 'page.php';\n\n /* Don't call get_query_template again!!!\n // return get_query_template( 'page', $templates );\n We also reproduce the key code of get_query_template() - we don't want to call it or we'll get stuck in a loop .\n We can remove lines of code that we know won't apply for pages, leaving us with...\n */\n\n $template = locate_template( $templates );\n\n return $template;\n}\n\nadd_filter( 'page_template', 'tbdn_get_page_template' );\n</code></pre>\n\n<p>Caveats:</p>\n\n<p>1 - I haven't tested this, but if you're up to messing around with the template hierarchy then you should certainly be able to follow, test & adjust my code which is mostly copied from WP anyway.</p>\n\n<p>2 - If future core code ever changes the template hierarchy for pages then the code above will go out-of-date.</p>\n"
},
{
"answer_id": 312624,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n<p>I posted the details on <a href=\"https://wordpress.stackexchange.com/a/312611/110572\">this answer</a>. Here, the CODE is adjusted based on two specific differences of this question:</p>\n<ol>\n<li><p>Move page templates to sub-directory without fall back. For example, it'll check <code>THEME/sub-directory/page-{slug}.php</code>, but it'll <strong>not</strong> check <code>THEME/page-{slug}.php</code>, because that's what the OP asked. However, the option with fallback in the other answer is better, especially in case of child theme (as the parent theme may depend on the fallback).</p>\n</li>\n<li><p>It'll move both <code>page-{slug}.php</code> and <code>page-{id}.php</code> to the sub-directory.</p>\n</li>\n</ol>\n</blockquote>\n<hr />\n<h2>Filter Hook to use:</h2>\n<p>The best way to move page templates to a sub-directory, say <code>/THEME/page-templates/</code>, is to use the <strong><code>page_template_hierarchy</code></strong> filter hook.</p>\n<blockquote>\n<p><em><strong>Note:</strong></em> the original filter hook is <strong><a href=\"https://developer.wordpress.org/reference/hooks/type_template_hierarchy/\" rel=\"nofollow noreferrer\">{$type}_template_hierarchy</a></strong>, which becomes <code>page_template_hierarchy</code> when <code>$type</code> is <code>page</code>.</p>\n</blockquote>\n<h2>Sample CODE:</h2>\n<pre><code><?php\n/*\nPlugin Name: WPSE Page Template move to Sub Directory\nPlugin URI: https://wordpress.stackexchange.com/a/227006/110572\nDescription: WPSE Page Template move to a Sub Directory\nVersion: 1.0.0\nAuthor: Fayaz Ahmed\nAuthor URI: https://www.fayazmiraz.com/\n*/\n\n// defining the sub-directory so that it can be easily accessed from elsewhere as well.\ndefine( 'WPSE_PAGE_TEMPLATE_SUB_DIR', 'page-templates' );\n\nfunction wpse227006_page_template_add_subdir( $templates = array() ) {\n // Generally this doesn't happen, unless another plugin / theme does modifications\n // of their own. In that case, it's better not to mess with it again with our code.\n if( empty( $templates ) || ! is_array( $templates ) || count( $templates ) < 3 )\n return $templates;\n\n $page_tpl_idx = 0;\n $cnt = count( $templates );\n if( $templates[0] === get_page_template_slug() ) {\n // if there is custom template, then our page-{slug}.php template is at the next index \n $page_tpl_idx = 1;\n }\n\n // the last one in $templates is page.php, so\n // all but the last one in $templates starting from $page_tpl_idx will be moved to sub-directory\n for( $i = $page_tpl_idx; $i < $cnt - 1; $i++ ) {\n $templates[$i] = WPSE_PAGE_TEMPLATE_SUB_DIR . '/' . $templates[$i];\n }\n\n return $templates;\n}\n// the original filter hook is {$type}_template_hierarchy,\n// wihch is located in wp-includes/template.php file\nadd_filter( 'page_template_hierarchy', 'wpse227006_page_template_add_subdir' );\n</code></pre>\n"
}
] |
2016/05/18
|
[
"https://wordpress.stackexchange.com/questions/227007",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93875/"
] |
I'm having issues with images getting badly compressed when uploaded to my site. It's not an issue with photographs, but is very noticeable for images with solid blocks of colour and text.
I've uploaded a PNG with a solid grey background overlaid with white text, and it's being badly compressed when WordPress resizes it to the various alternative sizes.
[Original image](http://www.wondercompany.co.uk/wp-content/uploads/2016/05/tc1.png)
[Large featured image size](http://www.wondercompany.co.uk/wp-content/uploads/2016/05/tc1-1024x682.png)
Unfortunately I don't have enough reputation to post more than 2 links, but you can see in the resized Large version that the text has become very blurry, and the solid grey background has a noticeable strobe to it.
I know you can turn off / adjust the level of JPG image compression, but as far as I know WordPress shouldn't be compressing PNGs at all, so I'm at a loss to figure out what's going on.
What could be causing this? Is this potentially an issue with the compression / resize software on my server? Or is there a way to tell WordPress not to compress PNGs, like there is with JPEGs?
|
/YOUR\_THEME/page-templates/ will only work for custom page templates assigned on the admin page edit screen, not for page-$slug or page-$id named templates.
The correct filter hook in my view is page\_template, but you don't (I assume!) want to throw out any other possible templates for your pages, not least because you're bound to have some pages on your site for which you haven't made a /my-sub-dir/page-$slug.php template file.
The page\_template filter hook is called just after WP has found a template for the page using the standard template hierarchy. It would be handy if there was a filter to let you inject your additional template into the right part of the template hierarchy, but in the absence of that we'll need to replicate the search for page templates from WordPress's own get\_page\_template() function, found in /wp-includes/template.php:
```
function get_page_template() {
$id = get_queried_object_id();
$template = get_page_template_slug();
$pagename = get_query_var('pagename');
if ( ! $pagename && $id ) {
// If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object
$post = get_queried_object();
if ( $post )
$pagename = $post->post_name;
}
$templates = array();
if ( $template && 0 === validate_file( $template ) )
$templates[] = $template;
if ( $pagename )
$templates[] = "page-$pagename.php";
if ( $id )
$templates[] = "page-$id.php";
$templates[] = 'page.php';
return get_query_template( 'page', $templates );
}
```
This function builds an array of possible templates for Pages. get\_query\_template() then uses locate\_template() to run through the array and return the filename of the first template found.
As we can't hook into the list of proposed templates, we'll sadly have to duplicate some of this work.
Here's our own function:
```
function tbdn_get_page_template() {
$id = get_queried_object_id();
$template = get_page_template_slug();
$pagename = get_query_var('pagename');
if ( ! $pagename && $id ) {
// If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object
$post = get_queried_object();
if ( $post )
$pagename = $post->post_name;
}
$templates = array();
if ( $template && 0 === validate_file( $template ) )
$templates[] = $template;
// if there's a custom template then still give that priority
if ( $pagename )
$templates[] = "our-sub-dir/page-$pagename.php";
// change the default search for the page-$slug template to use our directory
// you could also look in the theme root directory either before or after this
if ( $id )
$templates[] = "our-sub-dir/page-$id.php";
$templates[] = 'page.php';
/* Don't call get_query_template again!!!
// return get_query_template( 'page', $templates );
We also reproduce the key code of get_query_template() - we don't want to call it or we'll get stuck in a loop .
We can remove lines of code that we know won't apply for pages, leaving us with...
*/
$template = locate_template( $templates );
return $template;
}
add_filter( 'page_template', 'tbdn_get_page_template' );
```
Caveats:
1 - I haven't tested this, but if you're up to messing around with the template hierarchy then you should certainly be able to follow, test & adjust my code which is mostly copied from WP anyway.
2 - If future core code ever changes the template hierarchy for pages then the code above will go out-of-date.
|
227,029 |
<p>I'm trying to write a simple permission admin page plugin.
So far I made a page with every role where I can check a certain menu page to be disabled from menu. I simply get <code>global $menu</code> and save to option encoded to JSON array. </p>
<p>Example:</p>
<pre><code> array(2) {
["sub_administrator"]=>
array(11) {
[0]=>
string(10) "menu-posts"
[1]=>
string(19) "toplevel_page_wpcf7"
[2]=>
string(15) "menu-appearance"
[3]=>
string(12) "menu-plugins"
[4]=>
string(10) "menu-tools"
[5]=>
string(13) "menu-settings"
[6]=>
string(32) "toplevel_page_edit?post_type=acf"
[7]=>
string(30) "toplevel_page_bwp_capt_general"
[8]=>
string(40) "toplevel_page_mr_permissions_admin_pages"
[9]=>
string(23) "toplevel_page_Wordfence"
[10]=>
string(28) "toplevel_page_wp-user-avatar"
}
}
</code></pre>
<p>Later using <code>admin_menu</code> hook I remove from display a certain menu item</p>
<pre><code>function mr_permissions_roles_admin_menu_restriction() {
echo'<pre>';
global $menu;
$restricted=array();
$current_user=wp_get_current_user();
$role_restriction=get_option('mr_permissions_roles');
$role_restriction=(array)json_decode($role_restriction);
$role=$current_user->roles[0];
if(!empty($role_restriction[$role]))
{
$restricted=$role_restriction[$role];
}
foreach ( $menu as $item => $data ) {
if ( ! isset( $data[5] ) ) {
continue; // Move along if the current $item doesn't have a slug.
} elseif ( in_array( $data[5], $restricted ) ) {
unset( $menu[$item] ); // Remove the current $item from the $menu.
}
}
echo'</pre>';
}
add_action( 'admin_menu', 'mr_permissions_roles_admin_menu_restriction',20);
</code></pre>
<p>That's the easy part here.</p>
<p>Now I want before every admin page to load check if user has plugin permission to go to page (people still can go to page by url).</p>
<p>I made something that works but not everywhere. I explain under code.</p>
<pre><code>function mr_permissions_roles_admin_page_restriction($screen)
{
global $menu;
$current_user=wp_get_current_user();
$role_restriction=get_option('mr_permissions_roles');
$role_restriction=(array)json_decode($role_restriction);
$role=$current_user->roles[0];
if(in_array($screen->base,$role_restriction[$role]))
exit('<!DOCTYPE html> <!-- Ticket #11289, IE bug fix: always pad the error page with enough characters such that it is greater than 512 bytes, even after gzip compression abcdefghijklmnopqrstuvwxyz1234567890aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz11223344556677889900abacbcbdcdcededfefegfgfhghgihihjijikjkjlklkmlmlnmnmononpopoqpqprqrqsrsrtstsubcbcdcdedefefgfabcadefbghicjkldmnoepqrfstugvwxhyz1i234j567k890laabmbccnddeoeffpgghqhiirjjksklltmmnunoovppqwqrrxsstytuuzvvw0wxx1yyz2z113223434455666777889890091abc2def3ghi4jkl5mno6pqr7stu8vwx9yz11aab2bcc3dd4ee5ff6gg7hh8ii9j0jk1kl2lmm3nnoo4p5pq6qrr7ss8tt9uuvv0wwx1x2yyzz13aba4cbcb5dcdc6dedfef8egf9gfh0ghg1ihi2hji3jik4jkj5lkl6kml7mln8mnm9ono --> <html xmlns="http://www.w3.org/1999/xhtml" lang="pl-PL"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width"> <title>WordPress &rsaquo; Błąd</title> <style type="text/css"> html { background: #f1f1f1; } body { background: #fff; color: #444; font-family: "Open Sans", sans-serif; margin: 2em auto; padding: 1em 2em; max-width: 700px; -webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.13); box-shadow: 0 1px 3px rgba(0,0,0,0.13); } h1 { border-bottom: 1px solid #dadada; clear: both; color: #666; font: 24px "Open Sans", sans-serif; margin: 30px 0 0 0; padding: 0; padding-bottom: 7px; } #error-page { margin-top: 50px; } #error-page p { font-size: 14px; line-height: 1.5; margin: 25px 0 20px; } #error-page code { font-family: Consolas, Monaco, monospace; } ul li { margin-bottom: 10px; font-size: 14px; } a { color: #0073aa; } a:hover, a:active { color: #00a0d2; } a:focus { color: #124964; -webkit-box-shadow: 0 0 0 1px #5b9dd9, 0 0 2px 1px rgba(30, 140, 190, .8); box-shadow: 0 0 0 1px #5b9dd9, 0 0 2px 1px rgba(30, 140, 190, .8); outline: none; } .button { background: #f7f7f7; border: 1px solid #ccc; color: #555; display: inline-block; text-decoration: none; font-size: 13px; line-height: 26px; height: 28px; margin: 0; padding: 0 10px 1px; cursor: pointer; -webkit-border-radius: 3px; -webkit-appearance: none; border-radius: 3px; white-space: nowrap; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; -webkit-box-shadow: 0 1px 0 #ccc; box-shadow: 0 1px 0 #ccc; vertical-align: top; } .button.button-large { height: 30px; line-height: 28px; padding: 0 12px 2px; } .button:hover, .button:focus { background: #fafafa; border-color: #999; color: #23282d; } .button:focus { border-color: #5b9dd9; -webkit-box-shadow: 0 0 3px rgba( 0, 115, 170, .8 ); box-shadow: 0 0 3px rgba( 0, 115, 170, .8 ); outline: none; } .button:active { background: #eee; border-color: #999; -webkit-box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 ); box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 ); -webkit-transform: translateY(1px); -ms-transform: translateY(1px); transform: translateY(1px); } </style> </head> <body id="error-page"> <p>Nie posiadasz wystarczających uprawnień, by wejść na tę stronę.</p></body> </html> ');
if($current_user->ID!=38)
{
echo '<pre>';
//var_dump($screen);
echo '</pre>';
}
}
add_action('current_screen','mr_permissions_roles_admin_page_restriction');
</code></pre>
<p>I found that <code>current_screen</code> hook. Well hook which I wanted but not exactly. For example to post menu item slug is <code>menu-posts</code>. In <code>$screen</code> variable and $menu variable there no single thing I can compare. For custom admin menu pages it works well. $menu slug is in $screen->base so I can compare it. But when it comes to built-in pages it doesn't work. So here are a few questions which may solve my problem.</p>
<ol>
<li><p>How to get admin menu item. Then I can save it in a different way and compare differently.</p></li>
<li><p>Is there any way I can get more data from <code>current_screen</code>.</p></li>
<li><p>Any other ideas?</p></li>
<li><p>(bonus) How can I get submenu pages for example for posts. <code>global $menu</code> doesn't have it. I would like to add to my plugin possibility to disable access to submenu pages (a few of them not all for example)</p></li>
</ol>
<p>I even tried to look into database for any information but couldn't find anything. </p>
<p>I also made a custom page to edit every user to let them add posts to one or few of my custom_posts. So for default Editor have no right to custom_posts. When I want to make someone who will for example add companies (custom_post) I go to users and I check checkbox and save. From now on this user with role editor can edit companies but others editors can't.</p>
|
[
{
"answer_id": 227036,
"author": "Landing on Jupiter",
"author_id": 74534,
"author_profile": "https://wordpress.stackexchange.com/users/74534",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress will recognize template files in /YOUR_THEME/page-templates/: <a href=\"https://developer.wordpress.org/themes/basics/organizing-theme-files/#page-templates-folder\" rel=\"nofollow\">https://developer.wordpress.org/themes/basics/organizing-theme-files/#page-templates-folder</a></p>\n"
},
{
"answer_id": 227053,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 3,
"selected": false,
"text": "<p>/YOUR_THEME/page-templates/ will only work for custom page templates assigned on the admin page edit screen, not for page-$slug or page-$id named templates.</p>\n\n<p>The correct filter hook in my view is page_template, but you don't (I assume!) want to throw out any other possible templates for your pages, not least because you're bound to have some pages on your site for which you haven't made a /my-sub-dir/page-$slug.php template file.</p>\n\n<p>The page_template filter hook is called just after WP has found a template for the page using the standard template hierarchy. It would be handy if there was a filter to let you inject your additional template into the right part of the template hierarchy, but in the absence of that we'll need to replicate the search for page templates from WordPress's own get_page_template() function, found in /wp-includes/template.php:</p>\n\n<pre><code>function get_page_template() {\n $id = get_queried_object_id();\n $template = get_page_template_slug();\n $pagename = get_query_var('pagename');\n\n if ( ! $pagename && $id ) {\n // If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object\n $post = get_queried_object();\n if ( $post )\n $pagename = $post->post_name;\n }\n\n $templates = array();\n if ( $template && 0 === validate_file( $template ) )\n $templates[] = $template;\n if ( $pagename )\n $templates[] = \"page-$pagename.php\";\n if ( $id )\n $templates[] = \"page-$id.php\";\n $templates[] = 'page.php';\n\n return get_query_template( 'page', $templates );\n}\n</code></pre>\n\n<p>This function builds an array of possible templates for Pages. get_query_template() then uses locate_template() to run through the array and return the filename of the first template found.</p>\n\n<p>As we can't hook into the list of proposed templates, we'll sadly have to duplicate some of this work.</p>\n\n<p>Here's our own function:</p>\n\n<pre><code>function tbdn_get_page_template() {\n $id = get_queried_object_id();\n $template = get_page_template_slug();\n $pagename = get_query_var('pagename');\n\n if ( ! $pagename && $id ) {\n // If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object\n $post = get_queried_object();\n if ( $post )\n $pagename = $post->post_name;\n }\n\n $templates = array();\n\n if ( $template && 0 === validate_file( $template ) )\n $templates[] = $template;\n // if there's a custom template then still give that priority\n\n if ( $pagename )\n $templates[] = \"our-sub-dir/page-$pagename.php\";\n // change the default search for the page-$slug template to use our directory\n // you could also look in the theme root directory either before or after this\n\n if ( $id )\n $templates[] = \"our-sub-dir/page-$id.php\";\n $templates[] = 'page.php';\n\n /* Don't call get_query_template again!!!\n // return get_query_template( 'page', $templates );\n We also reproduce the key code of get_query_template() - we don't want to call it or we'll get stuck in a loop .\n We can remove lines of code that we know won't apply for pages, leaving us with...\n */\n\n $template = locate_template( $templates );\n\n return $template;\n}\n\nadd_filter( 'page_template', 'tbdn_get_page_template' );\n</code></pre>\n\n<p>Caveats:</p>\n\n<p>1 - I haven't tested this, but if you're up to messing around with the template hierarchy then you should certainly be able to follow, test & adjust my code which is mostly copied from WP anyway.</p>\n\n<p>2 - If future core code ever changes the template hierarchy for pages then the code above will go out-of-date.</p>\n"
},
{
"answer_id": 312624,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n<p>I posted the details on <a href=\"https://wordpress.stackexchange.com/a/312611/110572\">this answer</a>. Here, the CODE is adjusted based on two specific differences of this question:</p>\n<ol>\n<li><p>Move page templates to sub-directory without fall back. For example, it'll check <code>THEME/sub-directory/page-{slug}.php</code>, but it'll <strong>not</strong> check <code>THEME/page-{slug}.php</code>, because that's what the OP asked. However, the option with fallback in the other answer is better, especially in case of child theme (as the parent theme may depend on the fallback).</p>\n</li>\n<li><p>It'll move both <code>page-{slug}.php</code> and <code>page-{id}.php</code> to the sub-directory.</p>\n</li>\n</ol>\n</blockquote>\n<hr />\n<h2>Filter Hook to use:</h2>\n<p>The best way to move page templates to a sub-directory, say <code>/THEME/page-templates/</code>, is to use the <strong><code>page_template_hierarchy</code></strong> filter hook.</p>\n<blockquote>\n<p><em><strong>Note:</strong></em> the original filter hook is <strong><a href=\"https://developer.wordpress.org/reference/hooks/type_template_hierarchy/\" rel=\"nofollow noreferrer\">{$type}_template_hierarchy</a></strong>, which becomes <code>page_template_hierarchy</code> when <code>$type</code> is <code>page</code>.</p>\n</blockquote>\n<h2>Sample CODE:</h2>\n<pre><code><?php\n/*\nPlugin Name: WPSE Page Template move to Sub Directory\nPlugin URI: https://wordpress.stackexchange.com/a/227006/110572\nDescription: WPSE Page Template move to a Sub Directory\nVersion: 1.0.0\nAuthor: Fayaz Ahmed\nAuthor URI: https://www.fayazmiraz.com/\n*/\n\n// defining the sub-directory so that it can be easily accessed from elsewhere as well.\ndefine( 'WPSE_PAGE_TEMPLATE_SUB_DIR', 'page-templates' );\n\nfunction wpse227006_page_template_add_subdir( $templates = array() ) {\n // Generally this doesn't happen, unless another plugin / theme does modifications\n // of their own. In that case, it's better not to mess with it again with our code.\n if( empty( $templates ) || ! is_array( $templates ) || count( $templates ) < 3 )\n return $templates;\n\n $page_tpl_idx = 0;\n $cnt = count( $templates );\n if( $templates[0] === get_page_template_slug() ) {\n // if there is custom template, then our page-{slug}.php template is at the next index \n $page_tpl_idx = 1;\n }\n\n // the last one in $templates is page.php, so\n // all but the last one in $templates starting from $page_tpl_idx will be moved to sub-directory\n for( $i = $page_tpl_idx; $i < $cnt - 1; $i++ ) {\n $templates[$i] = WPSE_PAGE_TEMPLATE_SUB_DIR . '/' . $templates[$i];\n }\n\n return $templates;\n}\n// the original filter hook is {$type}_template_hierarchy,\n// wihch is located in wp-includes/template.php file\nadd_filter( 'page_template_hierarchy', 'wpse227006_page_template_add_subdir' );\n</code></pre>\n"
}
] |
2016/05/18
|
[
"https://wordpress.stackexchange.com/questions/227029",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87889/"
] |
I'm trying to write a simple permission admin page plugin.
So far I made a page with every role where I can check a certain menu page to be disabled from menu. I simply get `global $menu` and save to option encoded to JSON array.
Example:
```
array(2) {
["sub_administrator"]=>
array(11) {
[0]=>
string(10) "menu-posts"
[1]=>
string(19) "toplevel_page_wpcf7"
[2]=>
string(15) "menu-appearance"
[3]=>
string(12) "menu-plugins"
[4]=>
string(10) "menu-tools"
[5]=>
string(13) "menu-settings"
[6]=>
string(32) "toplevel_page_edit?post_type=acf"
[7]=>
string(30) "toplevel_page_bwp_capt_general"
[8]=>
string(40) "toplevel_page_mr_permissions_admin_pages"
[9]=>
string(23) "toplevel_page_Wordfence"
[10]=>
string(28) "toplevel_page_wp-user-avatar"
}
}
```
Later using `admin_menu` hook I remove from display a certain menu item
```
function mr_permissions_roles_admin_menu_restriction() {
echo'<pre>';
global $menu;
$restricted=array();
$current_user=wp_get_current_user();
$role_restriction=get_option('mr_permissions_roles');
$role_restriction=(array)json_decode($role_restriction);
$role=$current_user->roles[0];
if(!empty($role_restriction[$role]))
{
$restricted=$role_restriction[$role];
}
foreach ( $menu as $item => $data ) {
if ( ! isset( $data[5] ) ) {
continue; // Move along if the current $item doesn't have a slug.
} elseif ( in_array( $data[5], $restricted ) ) {
unset( $menu[$item] ); // Remove the current $item from the $menu.
}
}
echo'</pre>';
}
add_action( 'admin_menu', 'mr_permissions_roles_admin_menu_restriction',20);
```
That's the easy part here.
Now I want before every admin page to load check if user has plugin permission to go to page (people still can go to page by url).
I made something that works but not everywhere. I explain under code.
```
function mr_permissions_roles_admin_page_restriction($screen)
{
global $menu;
$current_user=wp_get_current_user();
$role_restriction=get_option('mr_permissions_roles');
$role_restriction=(array)json_decode($role_restriction);
$role=$current_user->roles[0];
if(in_array($screen->base,$role_restriction[$role]))
exit('<!DOCTYPE html> <!-- Ticket #11289, IE bug fix: always pad the error page with enough characters such that it is greater than 512 bytes, even after gzip compression abcdefghijklmnopqrstuvwxyz1234567890aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz11223344556677889900abacbcbdcdcededfefegfgfhghgihihjijikjkjlklkmlmlnmnmononpopoqpqprqrqsrsrtstsubcbcdcdedefefgfabcadefbghicjkldmnoepqrfstugvwxhyz1i234j567k890laabmbccnddeoeffpgghqhiirjjksklltmmnunoovppqwqrrxsstytuuzvvw0wxx1yyz2z113223434455666777889890091abc2def3ghi4jkl5mno6pqr7stu8vwx9yz11aab2bcc3dd4ee5ff6gg7hh8ii9j0jk1kl2lmm3nnoo4p5pq6qrr7ss8tt9uuvv0wwx1x2yyzz13aba4cbcb5dcdc6dedfef8egf9gfh0ghg1ihi2hji3jik4jkj5lkl6kml7mln8mnm9ono --> <html xmlns="http://www.w3.org/1999/xhtml" lang="pl-PL"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width"> <title>WordPress › Błąd</title> <style type="text/css"> html { background: #f1f1f1; } body { background: #fff; color: #444; font-family: "Open Sans", sans-serif; margin: 2em auto; padding: 1em 2em; max-width: 700px; -webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.13); box-shadow: 0 1px 3px rgba(0,0,0,0.13); } h1 { border-bottom: 1px solid #dadada; clear: both; color: #666; font: 24px "Open Sans", sans-serif; margin: 30px 0 0 0; padding: 0; padding-bottom: 7px; } #error-page { margin-top: 50px; } #error-page p { font-size: 14px; line-height: 1.5; margin: 25px 0 20px; } #error-page code { font-family: Consolas, Monaco, monospace; } ul li { margin-bottom: 10px; font-size: 14px; } a { color: #0073aa; } a:hover, a:active { color: #00a0d2; } a:focus { color: #124964; -webkit-box-shadow: 0 0 0 1px #5b9dd9, 0 0 2px 1px rgba(30, 140, 190, .8); box-shadow: 0 0 0 1px #5b9dd9, 0 0 2px 1px rgba(30, 140, 190, .8); outline: none; } .button { background: #f7f7f7; border: 1px solid #ccc; color: #555; display: inline-block; text-decoration: none; font-size: 13px; line-height: 26px; height: 28px; margin: 0; padding: 0 10px 1px; cursor: pointer; -webkit-border-radius: 3px; -webkit-appearance: none; border-radius: 3px; white-space: nowrap; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; -webkit-box-shadow: 0 1px 0 #ccc; box-shadow: 0 1px 0 #ccc; vertical-align: top; } .button.button-large { height: 30px; line-height: 28px; padding: 0 12px 2px; } .button:hover, .button:focus { background: #fafafa; border-color: #999; color: #23282d; } .button:focus { border-color: #5b9dd9; -webkit-box-shadow: 0 0 3px rgba( 0, 115, 170, .8 ); box-shadow: 0 0 3px rgba( 0, 115, 170, .8 ); outline: none; } .button:active { background: #eee; border-color: #999; -webkit-box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 ); box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 ); -webkit-transform: translateY(1px); -ms-transform: translateY(1px); transform: translateY(1px); } </style> </head> <body id="error-page"> <p>Nie posiadasz wystarczających uprawnień, by wejść na tę stronę.</p></body> </html> ');
if($current_user->ID!=38)
{
echo '<pre>';
//var_dump($screen);
echo '</pre>';
}
}
add_action('current_screen','mr_permissions_roles_admin_page_restriction');
```
I found that `current_screen` hook. Well hook which I wanted but not exactly. For example to post menu item slug is `menu-posts`. In `$screen` variable and $menu variable there no single thing I can compare. For custom admin menu pages it works well. $menu slug is in $screen->base so I can compare it. But when it comes to built-in pages it doesn't work. So here are a few questions which may solve my problem.
1. How to get admin menu item. Then I can save it in a different way and compare differently.
2. Is there any way I can get more data from `current_screen`.
3. Any other ideas?
4. (bonus) How can I get submenu pages for example for posts. `global $menu` doesn't have it. I would like to add to my plugin possibility to disable access to submenu pages (a few of them not all for example)
I even tried to look into database for any information but couldn't find anything.
I also made a custom page to edit every user to let them add posts to one or few of my custom\_posts. So for default Editor have no right to custom\_posts. When I want to make someone who will for example add companies (custom\_post) I go to users and I check checkbox and save. From now on this user with role editor can edit companies but others editors can't.
|
/YOUR\_THEME/page-templates/ will only work for custom page templates assigned on the admin page edit screen, not for page-$slug or page-$id named templates.
The correct filter hook in my view is page\_template, but you don't (I assume!) want to throw out any other possible templates for your pages, not least because you're bound to have some pages on your site for which you haven't made a /my-sub-dir/page-$slug.php template file.
The page\_template filter hook is called just after WP has found a template for the page using the standard template hierarchy. It would be handy if there was a filter to let you inject your additional template into the right part of the template hierarchy, but in the absence of that we'll need to replicate the search for page templates from WordPress's own get\_page\_template() function, found in /wp-includes/template.php:
```
function get_page_template() {
$id = get_queried_object_id();
$template = get_page_template_slug();
$pagename = get_query_var('pagename');
if ( ! $pagename && $id ) {
// If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object
$post = get_queried_object();
if ( $post )
$pagename = $post->post_name;
}
$templates = array();
if ( $template && 0 === validate_file( $template ) )
$templates[] = $template;
if ( $pagename )
$templates[] = "page-$pagename.php";
if ( $id )
$templates[] = "page-$id.php";
$templates[] = 'page.php';
return get_query_template( 'page', $templates );
}
```
This function builds an array of possible templates for Pages. get\_query\_template() then uses locate\_template() to run through the array and return the filename of the first template found.
As we can't hook into the list of proposed templates, we'll sadly have to duplicate some of this work.
Here's our own function:
```
function tbdn_get_page_template() {
$id = get_queried_object_id();
$template = get_page_template_slug();
$pagename = get_query_var('pagename');
if ( ! $pagename && $id ) {
// If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object
$post = get_queried_object();
if ( $post )
$pagename = $post->post_name;
}
$templates = array();
if ( $template && 0 === validate_file( $template ) )
$templates[] = $template;
// if there's a custom template then still give that priority
if ( $pagename )
$templates[] = "our-sub-dir/page-$pagename.php";
// change the default search for the page-$slug template to use our directory
// you could also look in the theme root directory either before or after this
if ( $id )
$templates[] = "our-sub-dir/page-$id.php";
$templates[] = 'page.php';
/* Don't call get_query_template again!!!
// return get_query_template( 'page', $templates );
We also reproduce the key code of get_query_template() - we don't want to call it or we'll get stuck in a loop .
We can remove lines of code that we know won't apply for pages, leaving us with...
*/
$template = locate_template( $templates );
return $template;
}
add_filter( 'page_template', 'tbdn_get_page_template' );
```
Caveats:
1 - I haven't tested this, but if you're up to messing around with the template hierarchy then you should certainly be able to follow, test & adjust my code which is mostly copied from WP anyway.
2 - If future core code ever changes the template hierarchy for pages then the code above will go out-of-date.
|
227,037 |
<p>Right now, when I click on a menu item in the wordpress admin menu, the section that that page belongs to is automatically expanded.</p>
<p>For instance, if I click on a link in the Settings section then the whole Settings section is expanded:</p>
<p><a href="https://i.stack.imgur.com/jnYlU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jnYlU.png" alt="enter image description here"></a></p>
<p>If, on the other hand, I click on a link in the Appearance menu then the whole Appearance section is expanded:</p>
<p><a href="https://i.stack.imgur.com/SRfJM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SRfJM.png" alt="enter image description here"></a></p>
<p>Is there a function or action that disables that feature? That is to say, I do NOT want these sections to be expanded, but to remain closed like all of the other sections - i.e., like this:</p>
<p><a href="https://i.stack.imgur.com/Iiyny.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Iiyny.png" alt="enter image description here"></a></p>
|
[
{
"answer_id": 227045,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 1,
"selected": false,
"text": "<p>I see two options here - override the CSS, or remove the \"active\" classes with JavaScript (sadly there is no action/filter that we can do this server-side) - I opted for the JS approach, it's cleaner, leaner and meaner:</p>\n\n<pre><code>function wpse_227037_remove_menu_classes() {\n echo '<script>jQuery( \".wp-has-current-submenu.wp-menu-open\" ).removeClass( \"wp-has-current-submenu wp-menu-open\" ).addClass( \"wp-not-current-submenu\" );</script>';\n}\n\nadd_action( 'adminmenu', 'wpse_227037_remove_menu_classes' );\n</code></pre>\n\n<p>The <code>adminmenu</code> action fires <em>right</em> after the menu HTML, so the code will execute the moment all admin nodes are in the DOM.</p>\n"
},
{
"answer_id": 296919,
"author": "fires3as0n",
"author_id": 129431,
"author_profile": "https://wordpress.stackexchange.com/users/129431",
"pm_score": 0,
"selected": false,
"text": "<p>I have found the solution to this problem</p>\n\n<p>Suggested by @TheDeadMedic jQuery class removing is only partial cure, because flyouts will still appear on click (left or right).\nTo say more, they will still appear on click even if you completely disable JavaScript in your browser (idk how that works, but it does)</p>\n\n<p>I've already posted my answer on the other thread on stackexchange <a href=\"https://wordpress.stackexchange.com/questions/30899/how-to-disable-admin-flyout-menus\">here</a> and on wordpress forums <a href=\"https://wordpress.org/support/topic/disable-flyout-popup-menus-in-backend/#post-10076636\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>In short, adding overflow: hidden to menus container hides them both on hover and click events</p>\n\n<pre><code>#adminmenuwrap {\noverflow: hidden;\n}\n</code></pre>\n"
}
] |
2016/05/18
|
[
"https://wordpress.stackexchange.com/questions/227037",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94279/"
] |
Right now, when I click on a menu item in the wordpress admin menu, the section that that page belongs to is automatically expanded.
For instance, if I click on a link in the Settings section then the whole Settings section is expanded:
[](https://i.stack.imgur.com/jnYlU.png)
If, on the other hand, I click on a link in the Appearance menu then the whole Appearance section is expanded:
[](https://i.stack.imgur.com/SRfJM.png)
Is there a function or action that disables that feature? That is to say, I do NOT want these sections to be expanded, but to remain closed like all of the other sections - i.e., like this:
[](https://i.stack.imgur.com/Iiyny.png)
|
I see two options here - override the CSS, or remove the "active" classes with JavaScript (sadly there is no action/filter that we can do this server-side) - I opted for the JS approach, it's cleaner, leaner and meaner:
```
function wpse_227037_remove_menu_classes() {
echo '<script>jQuery( ".wp-has-current-submenu.wp-menu-open" ).removeClass( "wp-has-current-submenu wp-menu-open" ).addClass( "wp-not-current-submenu" );</script>';
}
add_action( 'adminmenu', 'wpse_227037_remove_menu_classes' );
```
The `adminmenu` action fires *right* after the menu HTML, so the code will execute the moment all admin nodes are in the DOM.
|
227,038 |
<p>I have a fully functional Wordpress site and I want the to create a new separate website that displays the posts from the wordpress site using the Wordpress Rest API.
I understand that typing <a href="http://my-website/wp-json/wp/v2/posts" rel="nofollow">http://my-website/wp-json/wp/v2/posts</a> into a browser shows me this information but I want to code it into the new separate site. I don't even know where to start! Does anyone know how to help?</p>
|
[
{
"answer_id": 227045,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 1,
"selected": false,
"text": "<p>I see two options here - override the CSS, or remove the \"active\" classes with JavaScript (sadly there is no action/filter that we can do this server-side) - I opted for the JS approach, it's cleaner, leaner and meaner:</p>\n\n<pre><code>function wpse_227037_remove_menu_classes() {\n echo '<script>jQuery( \".wp-has-current-submenu.wp-menu-open\" ).removeClass( \"wp-has-current-submenu wp-menu-open\" ).addClass( \"wp-not-current-submenu\" );</script>';\n}\n\nadd_action( 'adminmenu', 'wpse_227037_remove_menu_classes' );\n</code></pre>\n\n<p>The <code>adminmenu</code> action fires <em>right</em> after the menu HTML, so the code will execute the moment all admin nodes are in the DOM.</p>\n"
},
{
"answer_id": 296919,
"author": "fires3as0n",
"author_id": 129431,
"author_profile": "https://wordpress.stackexchange.com/users/129431",
"pm_score": 0,
"selected": false,
"text": "<p>I have found the solution to this problem</p>\n\n<p>Suggested by @TheDeadMedic jQuery class removing is only partial cure, because flyouts will still appear on click (left or right).\nTo say more, they will still appear on click even if you completely disable JavaScript in your browser (idk how that works, but it does)</p>\n\n<p>I've already posted my answer on the other thread on stackexchange <a href=\"https://wordpress.stackexchange.com/questions/30899/how-to-disable-admin-flyout-menus\">here</a> and on wordpress forums <a href=\"https://wordpress.org/support/topic/disable-flyout-popup-menus-in-backend/#post-10076636\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>In short, adding overflow: hidden to menus container hides them both on hover and click events</p>\n\n<pre><code>#adminmenuwrap {\noverflow: hidden;\n}\n</code></pre>\n"
}
] |
2016/05/18
|
[
"https://wordpress.stackexchange.com/questions/227038",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93762/"
] |
I have a fully functional Wordpress site and I want the to create a new separate website that displays the posts from the wordpress site using the Wordpress Rest API.
I understand that typing <http://my-website/wp-json/wp/v2/posts> into a browser shows me this information but I want to code it into the new separate site. I don't even know where to start! Does anyone know how to help?
|
I see two options here - override the CSS, or remove the "active" classes with JavaScript (sadly there is no action/filter that we can do this server-side) - I opted for the JS approach, it's cleaner, leaner and meaner:
```
function wpse_227037_remove_menu_classes() {
echo '<script>jQuery( ".wp-has-current-submenu.wp-menu-open" ).removeClass( "wp-has-current-submenu wp-menu-open" ).addClass( "wp-not-current-submenu" );</script>';
}
add_action( 'adminmenu', 'wpse_227037_remove_menu_classes' );
```
The `adminmenu` action fires *right* after the menu HTML, so the code will execute the moment all admin nodes are in the DOM.
|
227,059 |
<p>I am using Events Manager to control my Events, but Essential Grids to display previews of these events in various places throughout my site. An example of this is <a href="http://staging-dbmax.transitiongraphics.co.uk/events/" rel="nofollow">http://staging-dbmax.transitiongraphics.co.uk/events/</a>.</p>
<p>Essentially I am trying to get Essential Grids to recognise the Date Field of the event and sort the grid accordingly. Whilst hiding events that are in the past.</p>
<p>Thus far through research I have managed to isolate the grids and pull in the date, whilst hiding older events. However it doesn't quite work. Some of the events do not place correctly in the grid.</p>
<p>To achieve what I have so far I did the following:</p>
<p>Added parameters field under source tab of Essential Grids:</p>
<pre><code>( 'meta_query' => array( array( 'meta_key' => '_event_start_date' , 'meta_value' => $today, 'compare' => '>=' , 'type' => 'date')) , 'orderby' => 'meta_value' , ) ); ?>
</code></pre>
<p>Added the following to my Functions PHP file:</p>
<pre><code>add_filter('essgrid_query_caching', 'eg_disable_caching', 10, 2);
function eg_disable_caching($do_cache, $grid_id){ //disable caching for the particular grid
if($grid_id == 43 || $grid_id == 48 || $grid_id == 50){ //replace 1 with your desired grid id
return false;
}
return true;
}
add_filter('essgrid_get_posts', 'eg_modify_query', 10, 2);
function eg_modify_query($query, $grid_id){
if($grid_id == 43 || $grid_id == 48){ //replace 1 with your desired grid id
$query['meta_query'] = array( 'key' => '_start_ts', 'value' => current_time('timestamp'), 'compare' => '>=', 'type'=>'numeric' );
$query['meta_key'] = '_start_ts';
$query['meta_value'] = current_time('timestamp');
$query['meta_value_num'] = current_time('timestamp');
$query['meta_compare'] = '>=';
}
if($grid_id == 50){ //replace 1 with your desired grid id
$query['meta_query'] = array( 'key' => '_start_ts', 'value' => current_time('timestamp'), 'compare' => '<=', 'type'=>'numeric' );
$query['meta_key'] = '_start_ts';
$query['meta_value'] = current_time('timestamp');
$query['meta_value_num'] = current_time('timestamp');
$query['meta_compare'] = '<=';
}
return $query;
}
</code></pre>
<p>And finally, this HTML goes in the skin of the Grid to pull the date in from Events Manager:</p>
<pre><code>[event post_id="%post_id%"]#_EVENTDATES[/event]
</code></pre>
<p>Obvously if anyone has a better solution, I'd be happy to use that instead, otherwise, there something in the above which is not sorting correctly?</p>
|
[
{
"answer_id": 236290,
"author": "Marc",
"author_id": 101209,
"author_profile": "https://wordpress.stackexchange.com/users/101209",
"pm_score": 0,
"selected": false,
"text": "<p>It didn't work for me at first and I found out Essential Grid must have changed something. The shortcodes now need single quote instead of double quotes in the skin editor:</p>\n\n<pre><code>[event post_id='%post_id%']\n</code></pre>\n"
},
{
"answer_id": 237806,
"author": "Marc",
"author_id": 101210,
"author_profile": "https://wordpress.stackexchange.com/users/101210",
"pm_score": 2,
"selected": false,
"text": "<p>After researching this quite a bit I managed to sort the Events Manager events by date in the <a href=\"https://www.themepunch.com/portfolio/essential-grid-wordpress-plugin/\" rel=\"nofollow\">Essential Grid plugin</a>.</p>\n\n<p>If you started with the solution above, you can delete the added parameters field under source tab of Essential Grids, it's not needed anymore.</p>\n\n<p>So here's what I have in <code>functions.php</code>. <strong>Note</strong>: I have grid 1 & 2 used for current events and sorted by ascending \"event start date\" and I suppose grid 99 would work for past events in descending order, but I did not test it.</p>\n\n<pre><code>/******************************************************************\n * Querry for Essential Grid to work with events\n ******************************************************************/\nadd_filter('essgrid_query_caching', 'eg_disable_caching', 10, 2);\n\nfunction eg_disable_caching($do_cache, $grid_id){ //disable caching for the particular grid\n if($grid_id == 1 || $grid_id == 2 || $grid_id == 99){ //replace 99 with other grid id - see below\n return false;\n }\n return true;\n}\n\nadd_filter('essgrid_get_posts', 'eg_modify_query', 10, 2);\n//This is for future events\nfunction eg_modify_query($query, $grid_id){\n if($grid_id == 1 || $grid_id == 2){ //replace with your grid id\n $query['meta_query'] = array( 'key' => '_start_ts', 'value' => current_time('timestamp'), 'compare' => '>=', 'type'=>'numeric' );\n $query['meta_key'] = '_start_ts';\n $query['meta_value'] = current_time('timestamp');\n $query['meta_value_num'] = current_time('timestamp');\n $query['meta_compare'] = '>=';\n $query['order'] = 'ASC';\n $query['orderby'] = 'meta_value';\n }\n//This is for past events\n if($grid_id == 99){ //replace 99 with your desired grid id\n $query['meta_query'] = array( 'key' => '_start_ts', 'value' => current_time('timestamp'), 'compare' => '<=', 'type'=>'numeric' );\n $query['meta_key'] = '_start_ts';\n $query['meta_value'] = current_time('timestamp');\n $query['meta_value_num'] = current_time('timestamp');\n $query['meta_compare'] = '<=';\n $query['order'] = 'DESC';\n $query['orderby'] = 'meta_value';\n }\nreturn $query;\n}\n</code></pre>\n\n<p>And this is the HTML that goes in my grid to get the content of the events:</p>\n\n<pre><code>[event post_id='%post_id%']\n<span style=\"font-weight: bold;color: #597eba;\">Date:</span> #_EVENTDATES<br>\n<span style=\"font-weight: bold;color: #597eba;\">Time:</span> #_EVENTTIMES<br>\n<span style=\"font-weight: bold;color: #597eba;\">Location:</span> #_LOCATIONTOWN (#_LOCATIONSTATE)\n[/event]\n</code></pre>\n\n<p>You can use any Events Manager shortcodes for events or locations within the <code>[event]</code> tags. </p>\n\n<p>I hope this can be useful for someone else.</p>\n"
},
{
"answer_id": 250074,
"author": "Torsten",
"author_id": 109461,
"author_profile": "https://wordpress.stackexchange.com/users/109461",
"pm_score": 0,
"selected": false,
"text": "<p>Works also like this:</p>\n\n<ol>\n<li><p>Set a reference meta for _event_start_date (alphabetic) in Essential Grids \"Meta Data Handling\" menu section </p></li>\n<li><p>Put the above Code in your theme's (or better: child theme's) function.php </p></li>\n<li><p>Then go to your essential grid item under tab \"Nav-Filter-Sort\" and choose Event Start Date for sorting.</p></li>\n</ol>\n"
}
] |
2016/05/18
|
[
"https://wordpress.stackexchange.com/questions/227059",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91013/"
] |
I am using Events Manager to control my Events, but Essential Grids to display previews of these events in various places throughout my site. An example of this is <http://staging-dbmax.transitiongraphics.co.uk/events/>.
Essentially I am trying to get Essential Grids to recognise the Date Field of the event and sort the grid accordingly. Whilst hiding events that are in the past.
Thus far through research I have managed to isolate the grids and pull in the date, whilst hiding older events. However it doesn't quite work. Some of the events do not place correctly in the grid.
To achieve what I have so far I did the following:
Added parameters field under source tab of Essential Grids:
```
( 'meta_query' => array( array( 'meta_key' => '_event_start_date' , 'meta_value' => $today, 'compare' => '>=' , 'type' => 'date')) , 'orderby' => 'meta_value' , ) ); ?>
```
Added the following to my Functions PHP file:
```
add_filter('essgrid_query_caching', 'eg_disable_caching', 10, 2);
function eg_disable_caching($do_cache, $grid_id){ //disable caching for the particular grid
if($grid_id == 43 || $grid_id == 48 || $grid_id == 50){ //replace 1 with your desired grid id
return false;
}
return true;
}
add_filter('essgrid_get_posts', 'eg_modify_query', 10, 2);
function eg_modify_query($query, $grid_id){
if($grid_id == 43 || $grid_id == 48){ //replace 1 with your desired grid id
$query['meta_query'] = array( 'key' => '_start_ts', 'value' => current_time('timestamp'), 'compare' => '>=', 'type'=>'numeric' );
$query['meta_key'] = '_start_ts';
$query['meta_value'] = current_time('timestamp');
$query['meta_value_num'] = current_time('timestamp');
$query['meta_compare'] = '>=';
}
if($grid_id == 50){ //replace 1 with your desired grid id
$query['meta_query'] = array( 'key' => '_start_ts', 'value' => current_time('timestamp'), 'compare' => '<=', 'type'=>'numeric' );
$query['meta_key'] = '_start_ts';
$query['meta_value'] = current_time('timestamp');
$query['meta_value_num'] = current_time('timestamp');
$query['meta_compare'] = '<=';
}
return $query;
}
```
And finally, this HTML goes in the skin of the Grid to pull the date in from Events Manager:
```
[event post_id="%post_id%"]#_EVENTDATES[/event]
```
Obvously if anyone has a better solution, I'd be happy to use that instead, otherwise, there something in the above which is not sorting correctly?
|
After researching this quite a bit I managed to sort the Events Manager events by date in the [Essential Grid plugin](https://www.themepunch.com/portfolio/essential-grid-wordpress-plugin/).
If you started with the solution above, you can delete the added parameters field under source tab of Essential Grids, it's not needed anymore.
So here's what I have in `functions.php`. **Note**: I have grid 1 & 2 used for current events and sorted by ascending "event start date" and I suppose grid 99 would work for past events in descending order, but I did not test it.
```
/******************************************************************
* Querry for Essential Grid to work with events
******************************************************************/
add_filter('essgrid_query_caching', 'eg_disable_caching', 10, 2);
function eg_disable_caching($do_cache, $grid_id){ //disable caching for the particular grid
if($grid_id == 1 || $grid_id == 2 || $grid_id == 99){ //replace 99 with other grid id - see below
return false;
}
return true;
}
add_filter('essgrid_get_posts', 'eg_modify_query', 10, 2);
//This is for future events
function eg_modify_query($query, $grid_id){
if($grid_id == 1 || $grid_id == 2){ //replace with your grid id
$query['meta_query'] = array( 'key' => '_start_ts', 'value' => current_time('timestamp'), 'compare' => '>=', 'type'=>'numeric' );
$query['meta_key'] = '_start_ts';
$query['meta_value'] = current_time('timestamp');
$query['meta_value_num'] = current_time('timestamp');
$query['meta_compare'] = '>=';
$query['order'] = 'ASC';
$query['orderby'] = 'meta_value';
}
//This is for past events
if($grid_id == 99){ //replace 99 with your desired grid id
$query['meta_query'] = array( 'key' => '_start_ts', 'value' => current_time('timestamp'), 'compare' => '<=', 'type'=>'numeric' );
$query['meta_key'] = '_start_ts';
$query['meta_value'] = current_time('timestamp');
$query['meta_value_num'] = current_time('timestamp');
$query['meta_compare'] = '<=';
$query['order'] = 'DESC';
$query['orderby'] = 'meta_value';
}
return $query;
}
```
And this is the HTML that goes in my grid to get the content of the events:
```
[event post_id='%post_id%']
<span style="font-weight: bold;color: #597eba;">Date:</span> #_EVENTDATES<br>
<span style="font-weight: bold;color: #597eba;">Time:</span> #_EVENTTIMES<br>
<span style="font-weight: bold;color: #597eba;">Location:</span> #_LOCATIONTOWN (#_LOCATIONSTATE)
[/event]
```
You can use any Events Manager shortcodes for events or locations within the `[event]` tags.
I hope this can be useful for someone else.
|
227,079 |
<p>In the admin section, the commments bubble is on the left side of the toolbar. I know how to remove the bubble. What I can't figure out is how to move it to the right hand side of the toolbar (next to 'Howdy, [username]).</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 227082,
"author": "JediTricks007",
"author_id": 49017,
"author_profile": "https://wordpress.stackexchange.com/users/49017",
"pm_score": 1,
"selected": false,
"text": "<p>One way to move it to the very right would be like this:</p>\n\n<pre><code>#wp-admin-bar-comments {\n float: right !important;\n}\n</code></pre>\n\n<p>This will put it to the right of the Howdy message. I am not 100% sure if you want it on a specific side.</p>\n"
},
{
"answer_id": 227084,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": true,
"text": "<p>After you have removed the comments bubble, you <a href=\"https://codex.wordpress.org/Class_Reference/WP_Admin_Bar/add_node\" rel=\"nofollow\">add it again</a>. The trick is that in the <code>$args</code> of <code>add_node</code> you have to set <code>parent</code> to <code>top-secondary</code>.</p>\n\n<p>So it will look like this:</p>\n\n<pre><code>add_action( 'admin_bar_menu', 'wpse227079_toolbar_link_to_bubble', 999 );\n\n function wpse227079_toolbar_link_to_bubble ( $wp_admin_bar ) {\n $args = array(\n 'id' => 'wp-admin-bar-comments',\n 'parent'=> 'top-secondary',\n 'title' => 'QQ',\n 'href' => 'QQ',\n 'meta' => array( 'class' => 'QQ' )\n );\n $wp_admin_bar->add_node( $args );\n }\n</code></pre>\n\n<p>Title needs the full html of the bubble, href the link where it is going and meta the class for the list item. You'll have to delve into the source code of the admin bar to find the right QQ's for the bubble.</p>\n"
},
{
"answer_id": 227141,
"author": "Moshe",
"author_id": 94279,
"author_profile": "https://wordpress.stackexchange.com/users/94279",
"pm_score": 1,
"selected": false,
"text": "<p>Based on <a href=\"https://wordpress.stackexchange.com/questions/227079/how-to-move-the-comments-bubble-to-the-right-side-of-the-toolbar/227084#227084\">cjbj's answer above</a>, this is what I did...</p>\n\n<p>I went to /wp-includes/admin-bar.php and copied the relevant code with a slight modification (see below) into my plugin. Here is the end result:</p>\n\n<pre><code>if ( !current_user_can('edit_posts') )\n return;\n\n$awaiting_mod = wp_count_comments();\n$awaiting_mod = $awaiting_mod->moderated;\n$awaiting_text = sprintf( _n( '%s comment awaiting moderation', '%s comments awaiting moderation', $awaiting_mod ), number_format_i18n( $awaiting_mod ) );\n\n$icon = '<span class=\"ab-icon\"></span>';\n$title = '<span id=\"ab-awaiting-mod\" class=\"ab-label awaiting-mod pending-count count-' . $awaiting_mod . '\" aria-hidden=\"true\">' . number_format_i18n( $awaiting_mod ) . '</span>';\n$title .= '<span class=\"screen-reader-text\">' . $awaiting_text . '</span>';\n\n$wp_admin_bar->add_menu( array(\n 'id' => 'comments',\n 'parent' => 'top-secondary',\n 'title' => $icon . $title,\n 'href' => admin_url('edit-comments.php'),\n) );\n</code></pre>\n\n<p>All I did was add the 'parent' => 'top-secondary' line (as per cjbj's suggestion). This does exactly what I need it to do.</p>\n"
}
] |
2016/05/18
|
[
"https://wordpress.stackexchange.com/questions/227079",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94279/"
] |
In the admin section, the commments bubble is on the left side of the toolbar. I know how to remove the bubble. What I can't figure out is how to move it to the right hand side of the toolbar (next to 'Howdy, [username]).
Any ideas?
|
After you have removed the comments bubble, you [add it again](https://codex.wordpress.org/Class_Reference/WP_Admin_Bar/add_node). The trick is that in the `$args` of `add_node` you have to set `parent` to `top-secondary`.
So it will look like this:
```
add_action( 'admin_bar_menu', 'wpse227079_toolbar_link_to_bubble', 999 );
function wpse227079_toolbar_link_to_bubble ( $wp_admin_bar ) {
$args = array(
'id' => 'wp-admin-bar-comments',
'parent'=> 'top-secondary',
'title' => 'QQ',
'href' => 'QQ',
'meta' => array( 'class' => 'QQ' )
);
$wp_admin_bar->add_node( $args );
}
```
Title needs the full html of the bubble, href the link where it is going and meta the class for the list item. You'll have to delve into the source code of the admin bar to find the right QQ's for the bubble.
|
227,115 |
<p>I am new to wordpress. I am running wordpress setup on <code>http://localhost/wordpress/</code>. I am facing two problems right now:</p>
<ul>
<li>Only the logged in users can access the site. So, I am trying to redirect the guest from home page to login page using the following code which is somehow isn't working:</li>
</ul>
<blockquote>
<p>Path: <code>wp-content/themes/twentysixteen/header.php</code></p>
</blockquote>
<pre><code> <?php
if(get_permalink() != wp_login_url() && !is_user_logged_in()){
wp_redirect( wp_login_url() ); exit;
}
?>
</code></pre>
<p>Since the above code wasn't working, I tried to move on by letting the user to login manually by clicking on the <code>login</code> button. Here is the working code:</p>
<pre><code><?php
if(get_permalink() != wp_login_url() && !is_user_logged_in()){
// wp_redirect( wp_login_url() ); exit;
?>
<a href="<?php echo wp_login_url( get_permalink() ); ?>" title="Login">Login</a>
<?php
}
?>
</code></pre>
<ul>
<li>From above code, when guest clicked on login he/she was redirecting to login page and When the user is logs in, the page is redirecting to wordpress admin i.e <code>wp-admin</code> instead of home page i.e <code>http://localhost/wordpress</code>.</li>
</ul>
<h3>What I am trying to do is:</h3>
<ul>
<li>Redirect the guest from home page to login page, if the user isn't logged in.</li>
<li>And then redirect the user from login page to home page instead of wp-admin, when user logs in.</li>
</ul>
|
[
{
"answer_id": 227119,
"author": "Balas",
"author_id": 17849,
"author_profile": "https://wordpress.stackexchange.com/users/17849",
"pm_score": 1,
"selected": false,
"text": "<p>You can use following code to check home page or not:</p>\n\n<pre><code> if(is_home() && !is_user_logged_in()){\n wp_redirect( wp_login_url() ); exit;\n }\n</code></pre>\n"
},
{
"answer_id": 227121,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": false,
"text": "<p>If I understood correctly, you need to check if the user is logged in, if not, redirect it to login page. If the user logs in succesfully, he should be redirected to the page he was trying to see. You can do this by using the <code>redirect</code> argument of <a href=\"https://codex.wordpress.org/Function_Reference/wp_login_url\" rel=\"nofollow\"><code>wp_login_url()</code></a>. </p>\n\n<p>This code should work (not tested):</p>\n\n<pre><code>add_action( 'init', 'cyb_restrict_guest_access' );\nfunction cyb_restrict_guest_access() {\n global $wp;\n if( ! is_user_logged_in() && ! cyb_is_login_page() ) {\n wp_redirect( wp_login_url( site_url( $wp->request ) ) );\n exit;\n }\n}\n\nfunction cyb_is_login_page() {\n return in_array($GLOBALS['pagenow'], array('wp-login.php'));\n}\n</code></pre>\n"
},
{
"answer_id": 227167,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 1,
"selected": false,
"text": "<p>This in your header.php or before the get_header() call in any template will redirect a user who isn't logged in and who tries to reach any page of your site to the login page:</p>\n\n<pre><code>if( !is_user_logged_in() ) {\n wp_redirect( wp_login_url() );\n exit;\n}\n</code></pre>\n\n<p>This will redirect all users to the home page after login:</p>\n\n<pre><code>function tbdn_login_redirect( $redirect_url ) {\n\n return home_url();\n\n}\n\nadd_filter( 'login_redirect', 'tbdn_login_redirect' );\n</code></pre>\n\n<p>Note that it doesn't restrict a logged in user from accessing admin screens if they know the URL or if their login has the admin bar enabled.</p>\n"
},
{
"answer_id": 390895,
"author": "Siddika",
"author_id": 136350,
"author_profile": "https://wordpress.stackexchange.com/users/136350",
"pm_score": 0,
"selected": false,
"text": "<p>If your 'Login' page is a 'Page Template', you can use '<code>template_redirect</code>' hook. The following code in your <code>functions.php</code> will get you these:</p>\n<ul>\n<li>Redirect the guest from home page to login page, if the user isn't\nlogged in.</li>\n<li>And redirect the user from login page to home page when user logs in.</li>\n</ul>\n<p>Add the following in your functions file:</p>\n<pre><code>add_action( 'template_redirect', 'ft_redirect_user' );\nfunction ft_redirect_user() {\n //Redirect the guest from home page to login page, if the user isn't logged in. And redirect the user from login page to home page when user logs in.\n if ( ! is_user_logged_in() && is_front_page() ) {\n $return_url = esc_url( home_url( '/login-page-slug/' ) ); //change the 'login-page-slug' to your actual page slug of your login page.\n wp_redirect( $return_url );\n exit;\n } elseif ( is_user_logged_in() && is_page( 'login-page-slug' ) ) { //change the 'login-page-slug' to your actual page slug of your login page.\n $return_url = esc_url( home_url('/') );\n wp_redirect( $return_url );\n exit;\n }\n}\n</code></pre>\n"
}
] |
2016/05/19
|
[
"https://wordpress.stackexchange.com/questions/227115",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27751/"
] |
I am new to wordpress. I am running wordpress setup on `http://localhost/wordpress/`. I am facing two problems right now:
* Only the logged in users can access the site. So, I am trying to redirect the guest from home page to login page using the following code which is somehow isn't working:
>
> Path: `wp-content/themes/twentysixteen/header.php`
>
>
>
```
<?php
if(get_permalink() != wp_login_url() && !is_user_logged_in()){
wp_redirect( wp_login_url() ); exit;
}
?>
```
Since the above code wasn't working, I tried to move on by letting the user to login manually by clicking on the `login` button. Here is the working code:
```
<?php
if(get_permalink() != wp_login_url() && !is_user_logged_in()){
// wp_redirect( wp_login_url() ); exit;
?>
<a href="<?php echo wp_login_url( get_permalink() ); ?>" title="Login">Login</a>
<?php
}
?>
```
* From above code, when guest clicked on login he/she was redirecting to login page and When the user is logs in, the page is redirecting to wordpress admin i.e `wp-admin` instead of home page i.e `http://localhost/wordpress`.
### What I am trying to do is:
* Redirect the guest from home page to login page, if the user isn't logged in.
* And then redirect the user from login page to home page instead of wp-admin, when user logs in.
|
If I understood correctly, you need to check if the user is logged in, if not, redirect it to login page. If the user logs in succesfully, he should be redirected to the page he was trying to see. You can do this by using the `redirect` argument of [`wp_login_url()`](https://codex.wordpress.org/Function_Reference/wp_login_url).
This code should work (not tested):
```
add_action( 'init', 'cyb_restrict_guest_access' );
function cyb_restrict_guest_access() {
global $wp;
if( ! is_user_logged_in() && ! cyb_is_login_page() ) {
wp_redirect( wp_login_url( site_url( $wp->request ) ) );
exit;
}
}
function cyb_is_login_page() {
return in_array($GLOBALS['pagenow'], array('wp-login.php'));
}
```
|
227,124 |
<p>In my application user can publish a custom post from front end . And later admin or capable user can update or delete the post . What I want to do , is to determine if that post is seen by admin or capable user from a dashboard . A post meta "is_seen" is attached to my post , by default it is false . I want to make it true if admin or capable user open the post in edit mode . In short I want to do something when "Edit" link is clicked. </p>
|
[
{
"answer_id": 227119,
"author": "Balas",
"author_id": 17849,
"author_profile": "https://wordpress.stackexchange.com/users/17849",
"pm_score": 1,
"selected": false,
"text": "<p>You can use following code to check home page or not:</p>\n\n<pre><code> if(is_home() && !is_user_logged_in()){\n wp_redirect( wp_login_url() ); exit;\n }\n</code></pre>\n"
},
{
"answer_id": 227121,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": false,
"text": "<p>If I understood correctly, you need to check if the user is logged in, if not, redirect it to login page. If the user logs in succesfully, he should be redirected to the page he was trying to see. You can do this by using the <code>redirect</code> argument of <a href=\"https://codex.wordpress.org/Function_Reference/wp_login_url\" rel=\"nofollow\"><code>wp_login_url()</code></a>. </p>\n\n<p>This code should work (not tested):</p>\n\n<pre><code>add_action( 'init', 'cyb_restrict_guest_access' );\nfunction cyb_restrict_guest_access() {\n global $wp;\n if( ! is_user_logged_in() && ! cyb_is_login_page() ) {\n wp_redirect( wp_login_url( site_url( $wp->request ) ) );\n exit;\n }\n}\n\nfunction cyb_is_login_page() {\n return in_array($GLOBALS['pagenow'], array('wp-login.php'));\n}\n</code></pre>\n"
},
{
"answer_id": 227167,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 1,
"selected": false,
"text": "<p>This in your header.php or before the get_header() call in any template will redirect a user who isn't logged in and who tries to reach any page of your site to the login page:</p>\n\n<pre><code>if( !is_user_logged_in() ) {\n wp_redirect( wp_login_url() );\n exit;\n}\n</code></pre>\n\n<p>This will redirect all users to the home page after login:</p>\n\n<pre><code>function tbdn_login_redirect( $redirect_url ) {\n\n return home_url();\n\n}\n\nadd_filter( 'login_redirect', 'tbdn_login_redirect' );\n</code></pre>\n\n<p>Note that it doesn't restrict a logged in user from accessing admin screens if they know the URL or if their login has the admin bar enabled.</p>\n"
},
{
"answer_id": 390895,
"author": "Siddika",
"author_id": 136350,
"author_profile": "https://wordpress.stackexchange.com/users/136350",
"pm_score": 0,
"selected": false,
"text": "<p>If your 'Login' page is a 'Page Template', you can use '<code>template_redirect</code>' hook. The following code in your <code>functions.php</code> will get you these:</p>\n<ul>\n<li>Redirect the guest from home page to login page, if the user isn't\nlogged in.</li>\n<li>And redirect the user from login page to home page when user logs in.</li>\n</ul>\n<p>Add the following in your functions file:</p>\n<pre><code>add_action( 'template_redirect', 'ft_redirect_user' );\nfunction ft_redirect_user() {\n //Redirect the guest from home page to login page, if the user isn't logged in. And redirect the user from login page to home page when user logs in.\n if ( ! is_user_logged_in() && is_front_page() ) {\n $return_url = esc_url( home_url( '/login-page-slug/' ) ); //change the 'login-page-slug' to your actual page slug of your login page.\n wp_redirect( $return_url );\n exit;\n } elseif ( is_user_logged_in() && is_page( 'login-page-slug' ) ) { //change the 'login-page-slug' to your actual page slug of your login page.\n $return_url = esc_url( home_url('/') );\n wp_redirect( $return_url );\n exit;\n }\n}\n</code></pre>\n"
}
] |
2016/05/19
|
[
"https://wordpress.stackexchange.com/questions/227124",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/56654/"
] |
In my application user can publish a custom post from front end . And later admin or capable user can update or delete the post . What I want to do , is to determine if that post is seen by admin or capable user from a dashboard . A post meta "is\_seen" is attached to my post , by default it is false . I want to make it true if admin or capable user open the post in edit mode . In short I want to do something when "Edit" link is clicked.
|
If I understood correctly, you need to check if the user is logged in, if not, redirect it to login page. If the user logs in succesfully, he should be redirected to the page he was trying to see. You can do this by using the `redirect` argument of [`wp_login_url()`](https://codex.wordpress.org/Function_Reference/wp_login_url).
This code should work (not tested):
```
add_action( 'init', 'cyb_restrict_guest_access' );
function cyb_restrict_guest_access() {
global $wp;
if( ! is_user_logged_in() && ! cyb_is_login_page() ) {
wp_redirect( wp_login_url( site_url( $wp->request ) ) );
exit;
}
}
function cyb_is_login_page() {
return in_array($GLOBALS['pagenow'], array('wp-login.php'));
}
```
|
227,136 |
<p>I want to show the whole content of every page in feed .I search for it and found some plugin but I could not solve my problem.</p>
<p>I want when I enter <code>http://swissaudio.com/craftsmanship/feed</code> it provides me the page content in feed. How can I do that?</p>
|
[
{
"answer_id": 227397,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 4,
"selected": true,
"text": "<p>First set the post type to display on main feed page i.e. <code>/feed</code> using <code>pre_get_posts</code> hook</p>\n\n<pre><code>$q->set('post_type', array('post', 'page'));\n</code></pre>\n\n<p>On individual page WordPress shows comment feed then set it to <code>false</code> and display page content in feed.</p>\n\n<pre><code>$q->is_comment_feed = false;\n</code></pre>\n\n<p>In feed template WordPress calls <code>the_excerpt_rss()</code> which calls <code>get_the_excerpt()</code> so using <code>excerpt_length</code> filter change the length to max.</p>\n\n<p>Complete Example:-</p>\n\n<pre><code>add_action('pre_get_posts', 'wpse_227136_feed_content');\n/**\n * Set post type in feed content and remove comment feed\n * @param type $q WP Query\n */\nfunction wpse_227136_feed_content($q) {\n //Check if it main query and for feed\n if ($q->is_main_query() && $q->is_feed()) {\n //Set the post types which you want default is post\n $q->set('post_type', array('post', 'page'));\n }\n\n //Check if it feed request and for single page \n if ($q->is_main_query() && $q->is_feed() && $q->is_page()) {\n //Set the comment feed to false\n $q->is_comment_feed = false;\n }\n}\n\nadd_filter( 'excerpt_length', 'wpse_227136_excerpt_length', 999 );\n/**\n * Filter the except length to full content.\n *\n * @param int $length Excerpt length.\n * @return int $length modified excerpt length.\n */\nfunction wpse_227136_excerpt_length( $length ) {\n if (is_feed() && !get_option('rss_use_excerpt')) {\n return PHP_INT_MAX;\n }\n\n return $length;\n}\n</code></pre>\n"
},
{
"answer_id": 227398,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>This may not be ideal, but it is a beginning. First make sure that the full content is in the feed:</p>\n\n<pre><code>function fullcontentfeed($content) {\n global $post;\n $content = $post->post_content;\n return $content;\n }\nadd_filter('the_excerpt_rss', 'fullcontentfeed');\n</code></pre>\n\n<p>You should then see the full feed at this url</p>\n\n<p><a href=\"http://swissaudio.com/craftsmanship/feed/?withoutcomments=1\">http://swissaudio.com/craftsmanship/feed/?withoutcomments=1</a></p>\n\n<p>You can then use <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\"><code>add_rewrite_rule</code></a> to redirect visitors from /feed/. Far from ideal, but maybe a start for somebody else to work on.</p>\n"
},
{
"answer_id": 227455,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 2,
"selected": false,
"text": "<p>As mentioned by @Sumit, you need to turn off the comments feed for a page (which I find really strange since by default comments are off on pages?) ... this is what I ended up with (allowing for getting the page comments feed with <code>?withcomments=1</code> if wanted):</p>\n\n<pre><code>add_action('pre_get_posts', 'rss_page_feed_full_content');\n\nfunction rss_page_feed_full_content($q) {\n // Check if it feed request and for single page\n if ($q->is_main_query() && $q->is_feed() && $q->is_page()) {\n //Set the comment feed to false\n $q->set('post_type', array('page'));\n // allow for page comments feed via ?withcomments=1\n if ( (isset($_GET['withcomments'])) && ($_GET['withcomments'] == '1') ) {return;}\n $q->is_comment_feed = false;\n }\n}\n</code></pre>\n\n<p>But for displaying the page content, since the feed template actually checks <code>rss_use_excerpt</code> to decide whether to display full text or summary (set on Settings -> Reading page) then this needs to be overridden if you want the full content to display for a page feed (so that you can have the main option set to whatever you like for posts.) Otherwise whatever else you do the content may end up in the description field of the feed instead of the content field.</p>\n\n<pre><code>add_filter('pre_option_rss_use_excerpt', 'page_rss_excerpt_option');\n\nfunction page_rss_excerpt_option($option) {\n // force full content output for pages\n if (is_page()) {return '0';}\n return $option;\n}\n</code></pre>\n\n<p>And finally, to get the RSS description field to display a page excerpt, you <em>might</em> have to do this (which is basically a copy of <code>wp_trim_excerpt</code> without <code>strip_shortcodes</code>) - well, I did anyway but it might be due to some weird shortcode behaviour on the page I was testing:</p>\n\n<pre><code>add_filter('the_excerpt_rss','rss_page_excerpt');\n\nfunction rss_page_excerpt($excerpt) {\n if (is_page()) {\n global $post; $text = $post->post_content;\n // removed this line otherwise got blank\n // $text = strip_shortcodes( $text );\n $text = apply_filters( 'the_content', $text );\n $text = str_replace(']]>', ']]&gt;', $text);\n $excerpt_length = apply_filters( 'excerpt_length', 55 );\n $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[&hellip;]' );\n $excerpt = wp_trim_words( $text, $excerpt_length, $excerpt_more );\n }\n return $excerpt;\n}\n</code></pre>\n"
}
] |
2016/05/19
|
[
"https://wordpress.stackexchange.com/questions/227136",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84928/"
] |
I want to show the whole content of every page in feed .I search for it and found some plugin but I could not solve my problem.
I want when I enter `http://swissaudio.com/craftsmanship/feed` it provides me the page content in feed. How can I do that?
|
First set the post type to display on main feed page i.e. `/feed` using `pre_get_posts` hook
```
$q->set('post_type', array('post', 'page'));
```
On individual page WordPress shows comment feed then set it to `false` and display page content in feed.
```
$q->is_comment_feed = false;
```
In feed template WordPress calls `the_excerpt_rss()` which calls `get_the_excerpt()` so using `excerpt_length` filter change the length to max.
Complete Example:-
```
add_action('pre_get_posts', 'wpse_227136_feed_content');
/**
* Set post type in feed content and remove comment feed
* @param type $q WP Query
*/
function wpse_227136_feed_content($q) {
//Check if it main query and for feed
if ($q->is_main_query() && $q->is_feed()) {
//Set the post types which you want default is post
$q->set('post_type', array('post', 'page'));
}
//Check if it feed request and for single page
if ($q->is_main_query() && $q->is_feed() && $q->is_page()) {
//Set the comment feed to false
$q->is_comment_feed = false;
}
}
add_filter( 'excerpt_length', 'wpse_227136_excerpt_length', 999 );
/**
* Filter the except length to full content.
*
* @param int $length Excerpt length.
* @return int $length modified excerpt length.
*/
function wpse_227136_excerpt_length( $length ) {
if (is_feed() && !get_option('rss_use_excerpt')) {
return PHP_INT_MAX;
}
return $length;
}
```
|
227,144 |
<p>I have a custom post type called 'game' with some ACF fields. One of the fields is a Post Object(called review_link) that accepts posts from a category called 'reviews'. One other field is a taxonomy field(called gametags) looking for the post_tag taxonomy of the 'posts' </p>
<p>This is what I am trying to achieve:</p>
<ol>
<li><p>Whenever you are reading a post (post_type=post) within the category Reviews to be able to add information to the sidebar, from the Game (post_type=game) which has this specific post in the Post Object field.</p></li>
<li><p>Whenever you are reading a post (post_type=post) from any category, to be able to get that posts tags, and look in the Games (post_type=game) ACF fields, and specifically in the taxonomy field, to find any matching tags, and then show some Game info.</p></li>
</ol>
<p>My code for case 1 is the following and it works great:</p>
<pre><code>$reviewID = $post->ID;
if(in_category('reviews') ) {
$reviewArgs = array(
'post_type' => 'game',
'meta_query' => array(
array(
'key' => 'review_link',
'value' => ''.$reviewID.'',
'compare' => 'LIKE'
)
)
);
}
</code></pre>
<p>Now for case 2 I have tried the following:</p>
<pre><code>$tag_ids = wp_get_post_tags( $post->ID, array( 'fields' => 'ids' ) );
$reviewArgs = array(
'post_type' => 'game',
'meta_query' => array(
array(
'key' => 'gametags',
'value' => $tag_ids,
'compare' => 'IN'
)
)
);
</code></pre>
<p>The $tag_ids for an example post are: 818,436,435,43,46,77. If I replace the $tag_ids in the above code with 435 it matches. But if I try to add it like an array it doesn't. I have also tried serializing the array, looping the array etc. None of it works. I could make an array of meta queries but the thing is the number of tags in each post are random. I have also tried converting the array to a string and using'LIKE' instead of 'IN' and nothing.</p>
<p>Actually the above code throws a warning:
Warning: trim() expects parameter 1 to be string, array given in /.../public_html/wp-includes/class-wp-meta-query.php on line 594</p>
<p>I have tried almost everything to make case 2 work and could not. From what I realize the meta_query is not working as expected when the meta value is an array, although the Codex specifies that it can be an array. All the above code is placed in sidebar.php.</p>
<p>Any hints tips would be appriciated</p>
<p>Thanks in advance</p>
|
[
{
"answer_id": 227151,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 2,
"selected": true,
"text": "<p>I don't know if you can get one array to compare to the other directly, but you can create a loop to set up a <code>meta_query</code> array that will check for each of the IDs within the field separately:</p>\n\n<pre><code>$tag_ids = wp_get_post_tags( $post->ID, array( 'fields' => 'ids' ) );\n\n$meta_query = array('relation' => 'OR');\n\nforeach ($tags_ids as $tag_id) {\n $meta_query[] = array(\n 'key' => 'gametags',\n 'value' => $tag_id,\n 'compare' => 'IN'\n );\n}\n\n$reviewArgs = array(\n 'post_type' => 'game',\n 'meta_query' => $meta_query\n);\n</code></pre>\n\n<p>Note: this could produce errors if no tags are set for the post so you might want to add some alternative handling for that case.</p>\n\n<p>EDIT: try this to test for the exact matches later...</p>\n\n<pre><code>$review_query = new WP_Query( $reviewArgs ); \nwhile( $review_query->have_posts() ) { \n $review_query->the_post(); \n global $post; $checkmatch = false;\n $gametags = get_post_meta($post->ID,'gametags');\n if (!is_array($gametags)) {$gametags = explode(',',$gametags);}\n foreach ($tags_ids as $tag_id) {\n if (in_array($tag_id,$gametags)) {$checkmatch = true;}\n }\n if ($checkmatch) {\n // echo output\n }\n}\n</code></pre>\n"
},
{
"answer_id": 227161,
"author": "bagpipper",
"author_id": 80397,
"author_profile": "https://wordpress.stackexchange.com/users/80397",
"pm_score": 0,
"selected": false,
"text": "<p>Since <code>$tag_ids = wp_get_post_tags( $post->ID, array( 'fields' => 'ids' ) );</code> returns an array, you should be able to use it like</p>\n\n<pre><code>$reviewArgs = array(\n 'post_type' => 'game',\n 'meta_query' => array(\n array(\n 'key' => 'gametags',\n 'value' => $tag_ids,\n 'compare' => 'IN'\n )\n ) \n);\n</code></pre>\n\n<p>Do you have the metakeys gametags for the post-type games?\nAlso are you using the WP_Query? Or get_posts()?</p>\n"
}
] |
2016/05/19
|
[
"https://wordpress.stackexchange.com/questions/227144",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3639/"
] |
I have a custom post type called 'game' with some ACF fields. One of the fields is a Post Object(called review\_link) that accepts posts from a category called 'reviews'. One other field is a taxonomy field(called gametags) looking for the post\_tag taxonomy of the 'posts'
This is what I am trying to achieve:
1. Whenever you are reading a post (post\_type=post) within the category Reviews to be able to add information to the sidebar, from the Game (post\_type=game) which has this specific post in the Post Object field.
2. Whenever you are reading a post (post\_type=post) from any category, to be able to get that posts tags, and look in the Games (post\_type=game) ACF fields, and specifically in the taxonomy field, to find any matching tags, and then show some Game info.
My code for case 1 is the following and it works great:
```
$reviewID = $post->ID;
if(in_category('reviews') ) {
$reviewArgs = array(
'post_type' => 'game',
'meta_query' => array(
array(
'key' => 'review_link',
'value' => ''.$reviewID.'',
'compare' => 'LIKE'
)
)
);
}
```
Now for case 2 I have tried the following:
```
$tag_ids = wp_get_post_tags( $post->ID, array( 'fields' => 'ids' ) );
$reviewArgs = array(
'post_type' => 'game',
'meta_query' => array(
array(
'key' => 'gametags',
'value' => $tag_ids,
'compare' => 'IN'
)
)
);
```
The $tag\_ids for an example post are: 818,436,435,43,46,77. If I replace the $tag\_ids in the above code with 435 it matches. But if I try to add it like an array it doesn't. I have also tried serializing the array, looping the array etc. None of it works. I could make an array of meta queries but the thing is the number of tags in each post are random. I have also tried converting the array to a string and using'LIKE' instead of 'IN' and nothing.
Actually the above code throws a warning:
Warning: trim() expects parameter 1 to be string, array given in /.../public\_html/wp-includes/class-wp-meta-query.php on line 594
I have tried almost everything to make case 2 work and could not. From what I realize the meta\_query is not working as expected when the meta value is an array, although the Codex specifies that it can be an array. All the above code is placed in sidebar.php.
Any hints tips would be appriciated
Thanks in advance
|
I don't know if you can get one array to compare to the other directly, but you can create a loop to set up a `meta_query` array that will check for each of the IDs within the field separately:
```
$tag_ids = wp_get_post_tags( $post->ID, array( 'fields' => 'ids' ) );
$meta_query = array('relation' => 'OR');
foreach ($tags_ids as $tag_id) {
$meta_query[] = array(
'key' => 'gametags',
'value' => $tag_id,
'compare' => 'IN'
);
}
$reviewArgs = array(
'post_type' => 'game',
'meta_query' => $meta_query
);
```
Note: this could produce errors if no tags are set for the post so you might want to add some alternative handling for that case.
EDIT: try this to test for the exact matches later...
```
$review_query = new WP_Query( $reviewArgs );
while( $review_query->have_posts() ) {
$review_query->the_post();
global $post; $checkmatch = false;
$gametags = get_post_meta($post->ID,'gametags');
if (!is_array($gametags)) {$gametags = explode(',',$gametags);}
foreach ($tags_ids as $tag_id) {
if (in_array($tag_id,$gametags)) {$checkmatch = true;}
}
if ($checkmatch) {
// echo output
}
}
```
|
227,148 |
<p>My theme has a lot of templates. Most of them contain messages in the usual way:</p>
<pre><code>echo __('This is the message','mytextdomain')
</code></pre>
<p>This has several disadvantages. For instance, if I want to change the Read More message I have to browse all files to see if it is there. There's a larger risk of typos and it is more difficult to check for consistency in the messages. So, is there a way to concentrate messages in one place?</p>
<p>Also I wonder about performance. For every page load WP loads the complete textdomain, only to find a translation that is always the same. Especially on the front end this doesn't sound efficient. So, is there a way to have proper localization without repeating the process all the time?</p>
|
[
{
"answer_id": 227149,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": -1,
"selected": false,
"text": "<p>There is an easy way to get around this problem. Store all frontend messages as options of your theme. Let's define an option 'messages':</p>\n\n<pre><code>add_option('messages',array());\n</code></pre>\n\n<p>Now we must populate this option. Let's define the defaults:</p>\n\n<pre><code>$theme_messages_defaults = array (\n 'read-more' => __('Read more','tekko'),\n 'next-page' => __('Next page','tekko'),\n ... and so on ...\n )\n</code></pre>\n\n<p>Now, we have to transfer the defaults to the option. We want to do this only at first install, when the translation files have been updated or when the user switches languages. When this test passes run this function:</p>\n\n<pre><code>function run_only_at_install_or_new_version {\n global $theme_messages_defaults;\n var $messages = array();\n foreach ($theme_messages_defaults as $message_key => $message_val) {\n $messages[$message_key] = $theme_messages_defaults[$message_val];\n }\n update_option('messages',$messages);\n}\n</code></pre>\n\n<p>Given that the option is an array, we need a slightly different <code>get_option</code> function:</p>\n\n<pre><code>function mytheme_get_message_option ($message_key) {\n $messages = get_option('messages');\n $message = $messages[$message_key];\n return $message;\n}\n</code></pre>\n\n<p>In your templates replace all your echo statements like this:</p>\n\n<pre><code>mytheme_get_message_option('read-more');\n</code></pre>\n\n<p>Don't forget you won't need the textdomain on the frontend anymore, so add a condition in your function file:</p>\n\n<pre><code>if (is_admin()) load_theme_textdomain ('mytheme', 'path/to/languages');\n</code></pre>\n\n<p>Now you have all your messages in one place and are preventing unnecessary translation actions. Actually you have even more possibilities. You can add the messages to your option pages and have your clients change the texts without having to change templates. Hey, if you use mods in stead of options, you can even add them to the theme customizer. Beware that you would have to add an extra condition to <code>run_only_at_install_or_new_version</code> to prevent overriding client messages when the theme is updated.</p>\n\n<p><strong>Note:</strong> The above is adapted from a more complex setup I use myself, so there may be some typos. If you're at this stage debugging it shouldn't be a problem.</p>\n"
},
{
"answer_id": 227200,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 2,
"selected": false,
"text": "<p>In my opinion you are focusing on a wrong issue in this case.</p>\n\n<blockquote>\n <p>For instance, if I want to change the Read More message I have to browse all files to see if it is there.</p>\n</blockquote>\n\n<p>This doesn't indicate localization problem. This indicates <em>templating</em> problem. </p>\n\n<p>What if you want to change <em>markup</em> of Read More of whatever else? Do you have to do this in multiple places as well? Then it's more about how templates are structured and duplication in them.</p>\n\n<p>Not that WordPress is particularly <em>good</em> at that, but still worth a consideration.</p>\n\n<blockquote>\n <p>Also I wonder about performance. For every page load WP loads the complete textdomain, only to find a translation that is always the same. Especially on the front end this doesn't sound efficient. </p>\n</blockquote>\n\n<p>You make a typical mistake of <em>wondering</em> instead of <em>measuring</em>.</p>\n\n<p>There are certainly performance implications to localization in WordPress. However <em>core</em> already does plenty of it to load localization for <em>itself</em>.</p>\n\n<p>If your theme doesn't approach or exceed WP core in size of necessary translations then you are probably fine. If you want to be sure — profile performance and get sure. :) Wondering just wastes your time on hypotheticals that might not <em>need</em> to be addressed.</p>\n"
}
] |
2016/05/19
|
[
"https://wordpress.stackexchange.com/questions/227148",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75495/"
] |
My theme has a lot of templates. Most of them contain messages in the usual way:
```
echo __('This is the message','mytextdomain')
```
This has several disadvantages. For instance, if I want to change the Read More message I have to browse all files to see if it is there. There's a larger risk of typos and it is more difficult to check for consistency in the messages. So, is there a way to concentrate messages in one place?
Also I wonder about performance. For every page load WP loads the complete textdomain, only to find a translation that is always the same. Especially on the front end this doesn't sound efficient. So, is there a way to have proper localization without repeating the process all the time?
|
In my opinion you are focusing on a wrong issue in this case.
>
> For instance, if I want to change the Read More message I have to browse all files to see if it is there.
>
>
>
This doesn't indicate localization problem. This indicates *templating* problem.
What if you want to change *markup* of Read More of whatever else? Do you have to do this in multiple places as well? Then it's more about how templates are structured and duplication in them.
Not that WordPress is particularly *good* at that, but still worth a consideration.
>
> Also I wonder about performance. For every page load WP loads the complete textdomain, only to find a translation that is always the same. Especially on the front end this doesn't sound efficient.
>
>
>
You make a typical mistake of *wondering* instead of *measuring*.
There are certainly performance implications to localization in WordPress. However *core* already does plenty of it to load localization for *itself*.
If your theme doesn't approach or exceed WP core in size of necessary translations then you are probably fine. If you want to be sure — profile performance and get sure. :) Wondering just wastes your time on hypotheticals that might not *need* to be addressed.
|
227,150 |
<p>I'm building a gallery page for a website and want to use the images from post types as background images with lightboxes. The code im using currently is this:</p>
<pre><code><div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<div id="inner-content" class="wrap cf">
<?php
$loop = new WP_Query( array(
'post_type' => 'sympathy-flowers',
'order' => 'ASC',
'posts_per_page' => -1
));
?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="b33" style="background-image: url("<?php echo the_field('image'); ?>;">
<p>Hello World!</p>
</div>
<?php endwhile; wp_reset_query(); ?>
</div>
</div><!-- #content -->
</div><!-- #primary -->
</code></pre>
<p>When I refresh the page, it brings through the p tag, however the background-image is not working, how would I fix this?</p>
<p>Problem has since been fixed.</p>
|
[
{
"answer_id": 227153,
"author": "bagpipper",
"author_id": 80397,
"author_profile": "https://wordpress.stackexchange.com/users/80397",
"pm_score": 1,
"selected": false,
"text": "<p>Well it seems you are using ACF. The you need not echo <code>the_field()</code> only echo <code>get_field('')</code> </p>\n"
},
{
"answer_id": 227155,
"author": "Sumeet Gohel",
"author_id": 92729,
"author_profile": "https://wordpress.stackexchange.com/users/92729",
"pm_score": 0,
"selected": false,
"text": "<p>You could get done by adding code as below.</p>\n\n<pre><code><div class=\"container\" style=\"background-image: url('<?php echo get_field('image',get_the_ID());?>)'\">\n</code></pre>\n"
},
{
"answer_id": 227160,
"author": "Nefro",
"author_id": 86801,
"author_profile": "https://wordpress.stackexchange.com/users/86801",
"pm_score": 0,
"selected": false,
"text": "<p>Please check first what you get from <code>the_field('image');</code></p>\n\n<pre><code>$img = get_field('image');\n\nvar_dump( $img );\n</code></pre>\n\n<p>Maybe it's just output array with id, url, width, ..</p>\n\n<p>and fix html</p>\n\n<pre><code> <div class=\"b33\" style=\"background-image: url(<?php echo get_field('image');?>);\">\n</code></pre>\n"
}
] |
2016/05/19
|
[
"https://wordpress.stackexchange.com/questions/227150",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94367/"
] |
I'm building a gallery page for a website and want to use the images from post types as background images with lightboxes. The code im using currently is this:
```
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<div id="inner-content" class="wrap cf">
<?php
$loop = new WP_Query( array(
'post_type' => 'sympathy-flowers',
'order' => 'ASC',
'posts_per_page' => -1
));
?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="b33" style="background-image: url("<?php echo the_field('image'); ?>;">
<p>Hello World!</p>
</div>
<?php endwhile; wp_reset_query(); ?>
</div>
</div><!-- #content -->
</div><!-- #primary -->
```
When I refresh the page, it brings through the p tag, however the background-image is not working, how would I fix this?
Problem has since been fixed.
|
Well it seems you are using ACF. The you need not echo `the_field()` only echo `get_field('')`
|
227,165 |
<p>My goal is to get wp_editor working in a simple widget which the admin can use to add text content on an admin options page.</p>
<p>Here we go in wp-admin/widgets.php everything looks sooo good right.
<a href="https://i.stack.imgur.com/NIQYd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NIQYd.png" alt="enter image description here"></a></p>
<p>When we try to save... Oh no..... Buttons are gone and the Visual tab no longer works
<a href="https://i.stack.imgur.com/krLNS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/krLNS.png" alt="enter image description here"></a></p>
<p>When I look at the HTML it appears as though after updating TinyMCE just decides it doesn't need to load any buttons... Any ideas?</p>
<p>Edit: here's the source for the plugin I wrote that's throwing this error</p>
<pre><code>add_action('widgets_init', 'string_example_name_init');
function string_example_name_init()
{
register_widget('string_example_name');
}
class string_example_name extends WP_Widget
{
public function __construct()
{
$widget_details = array(
'classname' => 'string_example_name',
'description' => 'String Example Name'
);
parent::__construct('string_example_name', 'String Example Name', $widget_details);
}
public function form($instance)
{
$textcontent = '';
if( !empty( $instance['textcontent'] ) ) {
$textcontent = $instance['textcontent'];
}
?>
<div class="string-arena-gods" id="texxxt">
<?php
$rand = rand( 0, 999 );
$ed_id = $this->get_field_id( 'wp_editor_' . $rand );
$ed_name = $this->get_field_name( 'wp_editor_' . $rand );
printf(
'<input type="hidden" id="%s" name="%s" value="%d" />',
$this->get_field_id( 'the_random_number' ),
$this->get_field_name( 'the_random_number' ),
$rand
);
$content = 'Hello World!';
$editor_id = $ed_id;
$settings = array(
'media_buttons' => false,
'textarea_rows' => 3,
'textarea_name' => $ed_name,
'teeny' => true,
);
wp_editor( $content, $editor_id, $settings );
?>
</div>
<div class='mfc-text'>
</div>
<?php
echo $args['after_widget'];
}
public function update( $new_instance, $old_instance ) {
$rand = (int) $new_instance['the_random_number'];
$editor_content = $new_instance[ 'wp_editor_' . $rand ];
$new_instance['wp_editor_' . $rand] = $editor_content;
return $new_instance;
}
public function widget( $args, $instance ) {
extract( $args );
$textcontent = apply_filters( 'textcontent', $instance['textcontent'] );
?>
<div class="string widget flex">
<?php
?>
</div>
<?php
}
}
</code></pre>
|
[
{
"answer_id": 227153,
"author": "bagpipper",
"author_id": 80397,
"author_profile": "https://wordpress.stackexchange.com/users/80397",
"pm_score": 1,
"selected": false,
"text": "<p>Well it seems you are using ACF. The you need not echo <code>the_field()</code> only echo <code>get_field('')</code> </p>\n"
},
{
"answer_id": 227155,
"author": "Sumeet Gohel",
"author_id": 92729,
"author_profile": "https://wordpress.stackexchange.com/users/92729",
"pm_score": 0,
"selected": false,
"text": "<p>You could get done by adding code as below.</p>\n\n<pre><code><div class=\"container\" style=\"background-image: url('<?php echo get_field('image',get_the_ID());?>)'\">\n</code></pre>\n"
},
{
"answer_id": 227160,
"author": "Nefro",
"author_id": 86801,
"author_profile": "https://wordpress.stackexchange.com/users/86801",
"pm_score": 0,
"selected": false,
"text": "<p>Please check first what you get from <code>the_field('image');</code></p>\n\n<pre><code>$img = get_field('image');\n\nvar_dump( $img );\n</code></pre>\n\n<p>Maybe it's just output array with id, url, width, ..</p>\n\n<p>and fix html</p>\n\n<pre><code> <div class=\"b33\" style=\"background-image: url(<?php echo get_field('image');?>);\">\n</code></pre>\n"
}
] |
2016/05/19
|
[
"https://wordpress.stackexchange.com/questions/227165",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88364/"
] |
My goal is to get wp\_editor working in a simple widget which the admin can use to add text content on an admin options page.
Here we go in wp-admin/widgets.php everything looks sooo good right.
[](https://i.stack.imgur.com/NIQYd.png)
When we try to save... Oh no..... Buttons are gone and the Visual tab no longer works
[](https://i.stack.imgur.com/krLNS.png)
When I look at the HTML it appears as though after updating TinyMCE just decides it doesn't need to load any buttons... Any ideas?
Edit: here's the source for the plugin I wrote that's throwing this error
```
add_action('widgets_init', 'string_example_name_init');
function string_example_name_init()
{
register_widget('string_example_name');
}
class string_example_name extends WP_Widget
{
public function __construct()
{
$widget_details = array(
'classname' => 'string_example_name',
'description' => 'String Example Name'
);
parent::__construct('string_example_name', 'String Example Name', $widget_details);
}
public function form($instance)
{
$textcontent = '';
if( !empty( $instance['textcontent'] ) ) {
$textcontent = $instance['textcontent'];
}
?>
<div class="string-arena-gods" id="texxxt">
<?php
$rand = rand( 0, 999 );
$ed_id = $this->get_field_id( 'wp_editor_' . $rand );
$ed_name = $this->get_field_name( 'wp_editor_' . $rand );
printf(
'<input type="hidden" id="%s" name="%s" value="%d" />',
$this->get_field_id( 'the_random_number' ),
$this->get_field_name( 'the_random_number' ),
$rand
);
$content = 'Hello World!';
$editor_id = $ed_id;
$settings = array(
'media_buttons' => false,
'textarea_rows' => 3,
'textarea_name' => $ed_name,
'teeny' => true,
);
wp_editor( $content, $editor_id, $settings );
?>
</div>
<div class='mfc-text'>
</div>
<?php
echo $args['after_widget'];
}
public function update( $new_instance, $old_instance ) {
$rand = (int) $new_instance['the_random_number'];
$editor_content = $new_instance[ 'wp_editor_' . $rand ];
$new_instance['wp_editor_' . $rand] = $editor_content;
return $new_instance;
}
public function widget( $args, $instance ) {
extract( $args );
$textcontent = apply_filters( 'textcontent', $instance['textcontent'] );
?>
<div class="string widget flex">
<?php
?>
</div>
<?php
}
}
```
|
Well it seems you are using ACF. The you need not echo `the_field()` only echo `get_field('')`
|
227,205 |
<p>I'm attempting to integrate the <code>custom-logo</code> functionality introduced in 4.5 and I'm running into some issues with the Customizer interface.</p>
<p>I'm checking <code>has_custom_logo</code> and, if it's false, I'm providing a text version of the site name and description as a fallback. It works perfectly fine when you add a custom logo. However, when you "Remove" it, it appears <code>has_custom_logo</code> still returns <code>true</code>.</p>
<p>Example:</p>
<pre><code>if ( function_exists( 'the_custom_logo' ) && has_custom_logo() ) {
the_custom_logo();
} else {
echo 'Fallback';
}
</code></pre>
<p>Anyone else had any luck with something similar?</p>
|
[
{
"answer_id": 230516,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 2,
"selected": true,
"text": "<p>You have it around the wrong way <code>has_custom_logo()</code> will return false if there is no logo.\n<code>function_exists( 'the_custom_logo' )</code> however will return true if you are using a version of Wordpress that support this function.</p>\n\n<p>So if you seperate your if statement like below it will work.</p>\n\n<pre><code>if( function_exists( 'the_custom_logo' ) ) {\n if(has_custom_logo()) {\n the_custom_logo();\n } else {\n echo \"No logo\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 246411,
"author": "Troy Templeman",
"author_id": 40536,
"author_profile": "https://wordpress.stackexchange.com/users/40536",
"pm_score": 2,
"selected": false,
"text": "<p>I used similar code to that in the question, using an image as a fallback, and works fine. Below 4.5 displays the fallback image and above 4.5 displays the custom logo, if one is set. If there is no custom logo set or it is removed, it displays the fallback image.</p>\n\n<pre><code><?php if ( function_exists( 'the_custom_logo' ) && has_custom_logo() ) : ?>\n <?php the_custom_logo(); ?>\n<?php else : ?> \n <h1 class=\"site-title\"><a href=\"<?php echo esc_url( home_url( '/' ) ); ?>\" rel=\"home\" title=\"<?php bloginfo( 'name' ); ?>\"><img src=\"<?php echo get_stylesheet_directory_uri(); ?>/images/logo.png\" alt=\"<?php bloginfo( 'name' ); ?>\" width=\"100\" height=\"50\" /></a></h1>\n<?php endif; ?>\n</code></pre>\n"
}
] |
2016/05/19
|
[
"https://wordpress.stackexchange.com/questions/227205",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/26817/"
] |
I'm attempting to integrate the `custom-logo` functionality introduced in 4.5 and I'm running into some issues with the Customizer interface.
I'm checking `has_custom_logo` and, if it's false, I'm providing a text version of the site name and description as a fallback. It works perfectly fine when you add a custom logo. However, when you "Remove" it, it appears `has_custom_logo` still returns `true`.
Example:
```
if ( function_exists( 'the_custom_logo' ) && has_custom_logo() ) {
the_custom_logo();
} else {
echo 'Fallback';
}
```
Anyone else had any luck with something similar?
|
You have it around the wrong way `has_custom_logo()` will return false if there is no logo.
`function_exists( 'the_custom_logo' )` however will return true if you are using a version of Wordpress that support this function.
So if you seperate your if statement like below it will work.
```
if( function_exists( 'the_custom_logo' ) ) {
if(has_custom_logo()) {
the_custom_logo();
} else {
echo "No logo";
}
}
```
|
227,229 |
<p>I have registered custom commands that scaffording some files. These commands don't rely on any wordpress funcionality, basically outputs some files with content (what commands do is irrelevant in this problem, so I won't paste here any code).</p>
<p>Example command: <code>wp make:some file</code></p>
<p>When I run these command <strong>when Wordpress is installed everything works perfectly</strong>, but <strong>if there is no Wordpress wp-cli alerts</strong> with:</p>
<pre><code>Error: This does not seem to be a WordPress install.
Pass --path=`path/to/wordpress` or run `wp core download`.
</code></pre>
<p>There is any way to run that commands without active Wordpress installation present?</p>
|
[
{
"answer_id": 230516,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 2,
"selected": true,
"text": "<p>You have it around the wrong way <code>has_custom_logo()</code> will return false if there is no logo.\n<code>function_exists( 'the_custom_logo' )</code> however will return true if you are using a version of Wordpress that support this function.</p>\n\n<p>So if you seperate your if statement like below it will work.</p>\n\n<pre><code>if( function_exists( 'the_custom_logo' ) ) {\n if(has_custom_logo()) {\n the_custom_logo();\n } else {\n echo \"No logo\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 246411,
"author": "Troy Templeman",
"author_id": 40536,
"author_profile": "https://wordpress.stackexchange.com/users/40536",
"pm_score": 2,
"selected": false,
"text": "<p>I used similar code to that in the question, using an image as a fallback, and works fine. Below 4.5 displays the fallback image and above 4.5 displays the custom logo, if one is set. If there is no custom logo set or it is removed, it displays the fallback image.</p>\n\n<pre><code><?php if ( function_exists( 'the_custom_logo' ) && has_custom_logo() ) : ?>\n <?php the_custom_logo(); ?>\n<?php else : ?> \n <h1 class=\"site-title\"><a href=\"<?php echo esc_url( home_url( '/' ) ); ?>\" rel=\"home\" title=\"<?php bloginfo( 'name' ); ?>\"><img src=\"<?php echo get_stylesheet_directory_uri(); ?>/images/logo.png\" alt=\"<?php bloginfo( 'name' ); ?>\" width=\"100\" height=\"50\" /></a></h1>\n<?php endif; ?>\n</code></pre>\n"
}
] |
2016/05/19
|
[
"https://wordpress.stackexchange.com/questions/227229",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93299/"
] |
I have registered custom commands that scaffording some files. These commands don't rely on any wordpress funcionality, basically outputs some files with content (what commands do is irrelevant in this problem, so I won't paste here any code).
Example command: `wp make:some file`
When I run these command **when Wordpress is installed everything works perfectly**, but **if there is no Wordpress wp-cli alerts** with:
```
Error: This does not seem to be a WordPress install.
Pass --path=`path/to/wordpress` or run `wp core download`.
```
There is any way to run that commands without active Wordpress installation present?
|
You have it around the wrong way `has_custom_logo()` will return false if there is no logo.
`function_exists( 'the_custom_logo' )` however will return true if you are using a version of Wordpress that support this function.
So if you seperate your if statement like below it will work.
```
if( function_exists( 'the_custom_logo' ) ) {
if(has_custom_logo()) {
the_custom_logo();
} else {
echo "No logo";
}
}
```
|
227,241 |
<p>I would like to load a css file in my Wordpress plugin by php. First I tried file_get_contents:</p>
<pre><code>$stylesheet = file_get_contents(plugins_url('assets/css/fonts.css', __FILE__ ));
</code></pre>
<p>But than I get this error:</p>
<blockquote>
<p>failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized</p>
</blockquote>
<p>I noticed that one has to enable Allow_url_fopen in php.ini (but I also read about this being a security risk).</p>
<p>Is there a WordPress function to load e.g. a txt file and store its content in a variable?</p>
<p><strong>EDIT:</strong>
I would like to parse a CSS file and get all its font-families.</p>
<pre><code><?php
function my_fonts() {
$stylesheet = file_get_contents('../assets/css/fonts.css');
$rows = explode("\n", $stylesheet);
array_shift($rows);
$fonts = array();
foreach($rows as $row => $data)
{
// Find all available font-families
$regex = '#font\-family:(.*)#';
preg_match($regex, $data, $output);
if($output){
$font = str_replace(array('font-family:', '\'', ';'), '', $output[0]);
$fonts[] = $font;
}
}
// Remove dublicates
$fonts = array_unique($fonts);
print_r($fonts);
}
?>
</code></pre>
|
[
{
"answer_id": 227242,
"author": "tehlivi",
"author_id": 54442,
"author_profile": "https://wordpress.stackexchange.com/users/54442",
"pm_score": 1,
"selected": false,
"text": "<p>You should use WordPress's built in function <code>wp_enqueue_style</code> for loading styles. </p>\n\n<pre><code>/**\n * Proper way to enqueue scripts and styles\n */\nfunction wpdocs_theme_name_scripts() {\n wp_enqueue_style( 'style-name', get_stylesheet_uri() );\n wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );\n}\nadd_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/wp_enqueue_style/</a></p>\n"
},
{
"answer_id": 227246,
"author": "user90798",
"author_id": 90798,
"author_profile": "https://wordpress.stackexchange.com/users/90798",
"pm_score": 1,
"selected": true,
"text": "<p>Looks like I blocked my self out…\nI had an .htaccess with password protection running that prevented the script from accessing the file.</p>\n"
}
] |
2016/05/19
|
[
"https://wordpress.stackexchange.com/questions/227241",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90798/"
] |
I would like to load a css file in my Wordpress plugin by php. First I tried file\_get\_contents:
```
$stylesheet = file_get_contents(plugins_url('assets/css/fonts.css', __FILE__ ));
```
But than I get this error:
>
> failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized
>
>
>
I noticed that one has to enable Allow\_url\_fopen in php.ini (but I also read about this being a security risk).
Is there a WordPress function to load e.g. a txt file and store its content in a variable?
**EDIT:**
I would like to parse a CSS file and get all its font-families.
```
<?php
function my_fonts() {
$stylesheet = file_get_contents('../assets/css/fonts.css');
$rows = explode("\n", $stylesheet);
array_shift($rows);
$fonts = array();
foreach($rows as $row => $data)
{
// Find all available font-families
$regex = '#font\-family:(.*)#';
preg_match($regex, $data, $output);
if($output){
$font = str_replace(array('font-family:', '\'', ';'), '', $output[0]);
$fonts[] = $font;
}
}
// Remove dublicates
$fonts = array_unique($fonts);
print_r($fonts);
}
?>
```
|
Looks like I blocked my self out…
I had an .htaccess with password protection running that prevented the script from accessing the file.
|
227,244 |
<p>I know the main query is fast, since it gets data after parsing the URL and after <code>WP_Query</code> has been instantiated. We are in OO PHP. </p>
<p>But is <code>query_posts</code> really slower than some secondary query that happens in a template for instance with <code>get_posts</code>, or native that you call with </p>
<pre><code>// WP_Query arguments
$args = array (
);
// The Query
$query = new WP_Query( $args );
</code></pre>
|
[
{
"answer_id": 227249,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 3,
"selected": false,
"text": "<p>You ask:</p>\n\n<blockquote>\n <p>is query_posts really slower than some secondary query...</p>\n</blockquote>\n\n<p>The fact is that if you're calling <code>query_posts()</code> from a theme then <strong>it already is a secondary query</strong>. WordPress has already queried the database once to get a certain page then it hits your <code>query_posts()</code> function and queries the database <em>again</em> creating a <em>second query</em> and overwriting the original request / data.</p>\n\n<p>From a speed perspective you're not going to notice any difference. The <code>query_posts()</code> functions uses <code>WP_Query()</code> and takes microseconds to overwrite some global variables. The biggest overhead will come from you having to normalize your data and make up for any niche issues with pagination.</p>\n\n<p>Simply put, it's all around inefficient. <strike>So, while there may not be a \"big red button\" that says \"Don't press here!\" it's pretty much implied that it shouldn't be pressed.</strike> It's not big and red but <a href=\"https://codex.wordpress.org/Function_Reference/query_posts\" rel=\"nofollow noreferrer\">The Codex specifically states</a>:</p>\n\n<blockquote>\n <p><strong>Note:</strong> This function isn't meant to be used by plugins or themes.</p>\n</blockquote>\n\n<p>If you want to be efficient and need to override the main query - use <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code></a> which will modify the query parameters before it calls it from the database which saves an entire database call ( in that we don't need a secondary query ).</p>\n"
},
{
"answer_id": 227267,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>In general, </p>\n\n<ul>\n<li><p>the query performed on the homepage, </p></li>\n<li><p><code>query_posts( 'posts_per_page=get_option( 'posts_per_page' )</code> and </p></li>\n<li><p><code>$q = new WP_Query( 'posts_per_page=get_option( 'posts_per_page' )</code></p></li>\n</ul>\n\n<p>should have the same exact performance with very very little to no difference between them as all of the above are exactly the same by default (<em>that is, have the same query arguments by default</em>). This is because all of these queries uses the <code>WP_Query</code> class to run build and run db queries to return the queried posts. <code>get_posts()</code> is a bit faster although it also uses <code>WP_Query</code>. The big difference is that <code>get_posts</code> passes <code>no_found_rows=true</code> to <code>WP_Query</code> which legally breaks pagination. </p>\n\n<p>What is true, the main query (<em>primary query</em>) runs on each and every page load according to the exact page being loaded. Removing the main loop and replacing it with a secondary query (<em>either <code>query_posts()</code>, <code>WP_Query</code> or <code>get_posts()</code></em>) is what is referred to as making the page slow. This is because you are doing the same work twice. As I said, the main query runs regardless, so you have already queried the db for posts, and replacing the main loop with a secondary query queries the db again. </p>\n\n<p>Apart from issues created with pagination and other crappy issues, this is why one should <strong>never</strong> replace the main loop from the main query with a secondary one. I have done an extensive post on this which you can read <a href=\"https://wordpress.stackexchange.com/a/155976/31545\">here</a>. To alter the main query, always use <code>pre_get_posts</code> as it alters the query vars before the <code>WP_Query</code> class builds and runs the SQL query. There are also other filters (<em>post clause filters</em>) available in <code>WP_Query</code> which you can use to directly alter the SQL query</p>\n\n<p>What makes <code>query_posts</code> bad is that it alters the main query object on which many functions rely as <code>query_posts</code> does the following</p>\n\n<pre><code>$wp_query = new WP_Query()\n</code></pre>\n\n<p>and it also alters the conditional tags. For a full explanation, you can read my answer <a href=\"https://wordpress.stackexchange.com/a/191934/31545\">here</a>. A normal <code>WP_Query</code> does not do that</p>\n"
}
] |
2016/05/19
|
[
"https://wordpress.stackexchange.com/questions/227244",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88606/"
] |
I know the main query is fast, since it gets data after parsing the URL and after `WP_Query` has been instantiated. We are in OO PHP.
But is `query_posts` really slower than some secondary query that happens in a template for instance with `get_posts`, or native that you call with
```
// WP_Query arguments
$args = array (
);
// The Query
$query = new WP_Query( $args );
```
|
You ask:
>
> is query\_posts really slower than some secondary query...
>
>
>
The fact is that if you're calling `query_posts()` from a theme then **it already is a secondary query**. WordPress has already queried the database once to get a certain page then it hits your `query_posts()` function and queries the database *again* creating a *second query* and overwriting the original request / data.
From a speed perspective you're not going to notice any difference. The `query_posts()` functions uses `WP_Query()` and takes microseconds to overwrite some global variables. The biggest overhead will come from you having to normalize your data and make up for any niche issues with pagination.
Simply put, it's all around inefficient. So, while there may not be a "big red button" that says "Don't press here!" it's pretty much implied that it shouldn't be pressed. It's not big and red but [The Codex specifically states](https://codex.wordpress.org/Function_Reference/query_posts):
>
> **Note:** This function isn't meant to be used by plugins or themes.
>
>
>
If you want to be efficient and need to override the main query - use [`pre_get_posts`](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) which will modify the query parameters before it calls it from the database which saves an entire database call ( in that we don't need a secondary query ).
|
227,247 |
<p>I have a custom loop to display a custom post type '<code>properties</code>' . The idea is to search properties based on different search parameters selected by users. Now the weird problem I am facing is that if the number of the search parameters increases to 7 the WP_Query doesn't return any results at all. </p>
<p>The properties with these search parameters exsit in the WP Backend . If I remove any of the one search parameter to make it less than 7 it displays the results. But as soon the number of parameters goes up it wont display any result.</p>
<p>What I am doing wrong ?</p>
<p>Here is the meta query array: </p>
<pre><code>(
[0] => Array
(
[key] => payment_status
[value] => yes
)
[1] => Array
(
[key] => expired
[value] => no
)
[2] => Array
(
[key] => listing_type
[meta_value_num] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
[3] => Array
(
[key] => available_for
[value] => sale
)
[4] => Array
(
[key] => country
[value] => Saudi Arabia
)
[5] => Array
(
[key] => city
[value] => Riyadh
)
[6] => Array
(
[key] => property_type
[value] => land
)
[7] => Array
(
[key] => by
[value] => owner
)
</code></pre>
<p>)</p>
<p>As I said if I remove any of the parameters the results will display. Here is my <code>WP_Query</code> function</p>
<pre><code>$loop = new WP_Query(
array(
'post_type' => 'properties',
'posts_per_page' => (int)get_field(ICL_LANGUAGE_CODE.'_search_results_per_page',get_active_lang_id()),
'meta_query' => $meta_query,
'orderby' => 'date',
'order' => 'DESC' ,
'paged' =>$paged
));
</code></pre>
<p>Is it a known problem with <code>WP_Query</code> that it doesn't display posts with large <code>meta_query</code> set?</p>
<p>Any help would be appreciated</p>
<p>Ahmar</p>
|
[
{
"answer_id": 227249,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 3,
"selected": false,
"text": "<p>You ask:</p>\n\n<blockquote>\n <p>is query_posts really slower than some secondary query...</p>\n</blockquote>\n\n<p>The fact is that if you're calling <code>query_posts()</code> from a theme then <strong>it already is a secondary query</strong>. WordPress has already queried the database once to get a certain page then it hits your <code>query_posts()</code> function and queries the database <em>again</em> creating a <em>second query</em> and overwriting the original request / data.</p>\n\n<p>From a speed perspective you're not going to notice any difference. The <code>query_posts()</code> functions uses <code>WP_Query()</code> and takes microseconds to overwrite some global variables. The biggest overhead will come from you having to normalize your data and make up for any niche issues with pagination.</p>\n\n<p>Simply put, it's all around inefficient. <strike>So, while there may not be a \"big red button\" that says \"Don't press here!\" it's pretty much implied that it shouldn't be pressed.</strike> It's not big and red but <a href=\"https://codex.wordpress.org/Function_Reference/query_posts\" rel=\"nofollow noreferrer\">The Codex specifically states</a>:</p>\n\n<blockquote>\n <p><strong>Note:</strong> This function isn't meant to be used by plugins or themes.</p>\n</blockquote>\n\n<p>If you want to be efficient and need to override the main query - use <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code></a> which will modify the query parameters before it calls it from the database which saves an entire database call ( in that we don't need a secondary query ).</p>\n"
},
{
"answer_id": 227267,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>In general, </p>\n\n<ul>\n<li><p>the query performed on the homepage, </p></li>\n<li><p><code>query_posts( 'posts_per_page=get_option( 'posts_per_page' )</code> and </p></li>\n<li><p><code>$q = new WP_Query( 'posts_per_page=get_option( 'posts_per_page' )</code></p></li>\n</ul>\n\n<p>should have the same exact performance with very very little to no difference between them as all of the above are exactly the same by default (<em>that is, have the same query arguments by default</em>). This is because all of these queries uses the <code>WP_Query</code> class to run build and run db queries to return the queried posts. <code>get_posts()</code> is a bit faster although it also uses <code>WP_Query</code>. The big difference is that <code>get_posts</code> passes <code>no_found_rows=true</code> to <code>WP_Query</code> which legally breaks pagination. </p>\n\n<p>What is true, the main query (<em>primary query</em>) runs on each and every page load according to the exact page being loaded. Removing the main loop and replacing it with a secondary query (<em>either <code>query_posts()</code>, <code>WP_Query</code> or <code>get_posts()</code></em>) is what is referred to as making the page slow. This is because you are doing the same work twice. As I said, the main query runs regardless, so you have already queried the db for posts, and replacing the main loop with a secondary query queries the db again. </p>\n\n<p>Apart from issues created with pagination and other crappy issues, this is why one should <strong>never</strong> replace the main loop from the main query with a secondary one. I have done an extensive post on this which you can read <a href=\"https://wordpress.stackexchange.com/a/155976/31545\">here</a>. To alter the main query, always use <code>pre_get_posts</code> as it alters the query vars before the <code>WP_Query</code> class builds and runs the SQL query. There are also other filters (<em>post clause filters</em>) available in <code>WP_Query</code> which you can use to directly alter the SQL query</p>\n\n<p>What makes <code>query_posts</code> bad is that it alters the main query object on which many functions rely as <code>query_posts</code> does the following</p>\n\n<pre><code>$wp_query = new WP_Query()\n</code></pre>\n\n<p>and it also alters the conditional tags. For a full explanation, you can read my answer <a href=\"https://wordpress.stackexchange.com/a/191934/31545\">here</a>. A normal <code>WP_Query</code> does not do that</p>\n"
}
] |
2016/05/19
|
[
"https://wordpress.stackexchange.com/questions/227247",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45901/"
] |
I have a custom loop to display a custom post type '`properties`' . The idea is to search properties based on different search parameters selected by users. Now the weird problem I am facing is that if the number of the search parameters increases to 7 the WP\_Query doesn't return any results at all.
The properties with these search parameters exsit in the WP Backend . If I remove any of the one search parameter to make it less than 7 it displays the results. But as soon the number of parameters goes up it wont display any result.
What I am doing wrong ?
Here is the meta query array:
```
(
[0] => Array
(
[key] => payment_status
[value] => yes
)
[1] => Array
(
[key] => expired
[value] => no
)
[2] => Array
(
[key] => listing_type
[meta_value_num] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
[3] => Array
(
[key] => available_for
[value] => sale
)
[4] => Array
(
[key] => country
[value] => Saudi Arabia
)
[5] => Array
(
[key] => city
[value] => Riyadh
)
[6] => Array
(
[key] => property_type
[value] => land
)
[7] => Array
(
[key] => by
[value] => owner
)
```
)
As I said if I remove any of the parameters the results will display. Here is my `WP_Query` function
```
$loop = new WP_Query(
array(
'post_type' => 'properties',
'posts_per_page' => (int)get_field(ICL_LANGUAGE_CODE.'_search_results_per_page',get_active_lang_id()),
'meta_query' => $meta_query,
'orderby' => 'date',
'order' => 'DESC' ,
'paged' =>$paged
));
```
Is it a known problem with `WP_Query` that it doesn't display posts with large `meta_query` set?
Any help would be appreciated
Ahmar
|
You ask:
>
> is query\_posts really slower than some secondary query...
>
>
>
The fact is that if you're calling `query_posts()` from a theme then **it already is a secondary query**. WordPress has already queried the database once to get a certain page then it hits your `query_posts()` function and queries the database *again* creating a *second query* and overwriting the original request / data.
From a speed perspective you're not going to notice any difference. The `query_posts()` functions uses `WP_Query()` and takes microseconds to overwrite some global variables. The biggest overhead will come from you having to normalize your data and make up for any niche issues with pagination.
Simply put, it's all around inefficient. So, while there may not be a "big red button" that says "Don't press here!" it's pretty much implied that it shouldn't be pressed. It's not big and red but [The Codex specifically states](https://codex.wordpress.org/Function_Reference/query_posts):
>
> **Note:** This function isn't meant to be used by plugins or themes.
>
>
>
If you want to be efficient and need to override the main query - use [`pre_get_posts`](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) which will modify the query parameters before it calls it from the database which saves an entire database call ( in that we don't need a secondary query ).
|
227,259 |
<p>I use a <code><span></code> inside the loop and I would like to get each post format the post is containing as a class in separate <code>spans</code>.</p>
<p>Example: </p>
<p><strong>If</strong> the post format <strong>is video and private</strong>: I would like to render:</p>
<pre><code><span class="format-video"></span>
<span class="status-private"></span>
</code></pre>
<p>So far I have tried <code><span <?php get_post_format_string($class); ?>></span></code> which did not work for me because this will render all the post formats and status in one <code>span</code>, not in different <code>spans</code>...</p>
|
[
{
"answer_id": 227249,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 3,
"selected": false,
"text": "<p>You ask:</p>\n\n<blockquote>\n <p>is query_posts really slower than some secondary query...</p>\n</blockquote>\n\n<p>The fact is that if you're calling <code>query_posts()</code> from a theme then <strong>it already is a secondary query</strong>. WordPress has already queried the database once to get a certain page then it hits your <code>query_posts()</code> function and queries the database <em>again</em> creating a <em>second query</em> and overwriting the original request / data.</p>\n\n<p>From a speed perspective you're not going to notice any difference. The <code>query_posts()</code> functions uses <code>WP_Query()</code> and takes microseconds to overwrite some global variables. The biggest overhead will come from you having to normalize your data and make up for any niche issues with pagination.</p>\n\n<p>Simply put, it's all around inefficient. <strike>So, while there may not be a \"big red button\" that says \"Don't press here!\" it's pretty much implied that it shouldn't be pressed.</strike> It's not big and red but <a href=\"https://codex.wordpress.org/Function_Reference/query_posts\" rel=\"nofollow noreferrer\">The Codex specifically states</a>:</p>\n\n<blockquote>\n <p><strong>Note:</strong> This function isn't meant to be used by plugins or themes.</p>\n</blockquote>\n\n<p>If you want to be efficient and need to override the main query - use <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\"><code>pre_get_posts</code></a> which will modify the query parameters before it calls it from the database which saves an entire database call ( in that we don't need a secondary query ).</p>\n"
},
{
"answer_id": 227267,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>In general, </p>\n\n<ul>\n<li><p>the query performed on the homepage, </p></li>\n<li><p><code>query_posts( 'posts_per_page=get_option( 'posts_per_page' )</code> and </p></li>\n<li><p><code>$q = new WP_Query( 'posts_per_page=get_option( 'posts_per_page' )</code></p></li>\n</ul>\n\n<p>should have the same exact performance with very very little to no difference between them as all of the above are exactly the same by default (<em>that is, have the same query arguments by default</em>). This is because all of these queries uses the <code>WP_Query</code> class to run build and run db queries to return the queried posts. <code>get_posts()</code> is a bit faster although it also uses <code>WP_Query</code>. The big difference is that <code>get_posts</code> passes <code>no_found_rows=true</code> to <code>WP_Query</code> which legally breaks pagination. </p>\n\n<p>What is true, the main query (<em>primary query</em>) runs on each and every page load according to the exact page being loaded. Removing the main loop and replacing it with a secondary query (<em>either <code>query_posts()</code>, <code>WP_Query</code> or <code>get_posts()</code></em>) is what is referred to as making the page slow. This is because you are doing the same work twice. As I said, the main query runs regardless, so you have already queried the db for posts, and replacing the main loop with a secondary query queries the db again. </p>\n\n<p>Apart from issues created with pagination and other crappy issues, this is why one should <strong>never</strong> replace the main loop from the main query with a secondary one. I have done an extensive post on this which you can read <a href=\"https://wordpress.stackexchange.com/a/155976/31545\">here</a>. To alter the main query, always use <code>pre_get_posts</code> as it alters the query vars before the <code>WP_Query</code> class builds and runs the SQL query. There are also other filters (<em>post clause filters</em>) available in <code>WP_Query</code> which you can use to directly alter the SQL query</p>\n\n<p>What makes <code>query_posts</code> bad is that it alters the main query object on which many functions rely as <code>query_posts</code> does the following</p>\n\n<pre><code>$wp_query = new WP_Query()\n</code></pre>\n\n<p>and it also alters the conditional tags. For a full explanation, you can read my answer <a href=\"https://wordpress.stackexchange.com/a/191934/31545\">here</a>. A normal <code>WP_Query</code> does not do that</p>\n"
}
] |
2016/05/20
|
[
"https://wordpress.stackexchange.com/questions/227259",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82313/"
] |
I use a `<span>` inside the loop and I would like to get each post format the post is containing as a class in separate `spans`.
Example:
**If** the post format **is video and private**: I would like to render:
```
<span class="format-video"></span>
<span class="status-private"></span>
```
So far I have tried `<span <?php get_post_format_string($class); ?>></span>` which did not work for me because this will render all the post formats and status in one `span`, not in different `spans`...
|
You ask:
>
> is query\_posts really slower than some secondary query...
>
>
>
The fact is that if you're calling `query_posts()` from a theme then **it already is a secondary query**. WordPress has already queried the database once to get a certain page then it hits your `query_posts()` function and queries the database *again* creating a *second query* and overwriting the original request / data.
From a speed perspective you're not going to notice any difference. The `query_posts()` functions uses `WP_Query()` and takes microseconds to overwrite some global variables. The biggest overhead will come from you having to normalize your data and make up for any niche issues with pagination.
Simply put, it's all around inefficient. So, while there may not be a "big red button" that says "Don't press here!" it's pretty much implied that it shouldn't be pressed. It's not big and red but [The Codex specifically states](https://codex.wordpress.org/Function_Reference/query_posts):
>
> **Note:** This function isn't meant to be used by plugins or themes.
>
>
>
If you want to be efficient and need to override the main query - use [`pre_get_posts`](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) which will modify the query parameters before it calls it from the database which saves an entire database call ( in that we don't need a secondary query ).
|
227,301 |
<p>I have updated my site manually, now I get below mentioned notice in the front and backend:</p>
<blockquote>
<p>Notice: register_sidebar was called incorrectly. No id was set in the
arguments array for the "Main Sidebar" sidebar. Defaulting to
"sidebar-1". Manually set the id to "sidebar-1" to silence this notice
and keep existing sidebar content. Please see Debugging in WordPress
for more information. (This message was added in version 4.2.0.)</p>
</blockquote>
<p>How to fix this?</p>
|
[
{
"answer_id": 227303,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>Looks like you have a very old theme. You'll have to search the <code>functions.php</code> file for <code>register_sidebar</code> and make sure the <code>$args</code> follow the format <a href=\"https://codex.wordpress.org/Function_Reference/register_sidebar\" rel=\"nofollow\">mentioned in the codex</a>.</p>\n"
},
{
"answer_id": 227304,
"author": "Nefro",
"author_id": 86801,
"author_profile": "https://wordpress.stackexchange.com/users/86801",
"pm_score": 4,
"selected": false,
"text": "<ol>\n<li><p>Find file where is <code>register_sidebar</code> ( must be on theme folder or plugins )</p></li>\n<li><p>add ID to sidebar</p>\n\n<pre><code>register_sidebar( array(\n 'name' => __( 'Main Sidebar', 'theme-slug' ),\n\n 'id' => 'change_me', // Add only this line\n\n 'description' => __( 'Widgets in this area will be shown on all posts and pages.', 'theme-slug' ),\n 'before_widget' => '<li id=\"%1$s\" class=\"widget %2$s\">',\n 'after_widget' => '</li>',\n 'before_title' => '<h2 class=\"widgettitle\">',\n 'after_title' => '</h2>',\n ) );\n</code></pre></li>\n</ol>\n\n<p>Or you can just disable notification in <code>wp-config.php</code> </p>\n\n<p>edit <code>WP_DEBUG</code> to false</p>\n\n<pre><code>define('WP_DEBUG', false);\n</code></pre>\n"
}
] |
2016/05/20
|
[
"https://wordpress.stackexchange.com/questions/227301",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94426/"
] |
I have updated my site manually, now I get below mentioned notice in the front and backend:
>
> Notice: register\_sidebar was called incorrectly. No id was set in the
> arguments array for the "Main Sidebar" sidebar. Defaulting to
> "sidebar-1". Manually set the id to "sidebar-1" to silence this notice
> and keep existing sidebar content. Please see Debugging in WordPress
> for more information. (This message was added in version 4.2.0.)
>
>
>
How to fix this?
|
1. Find file where is `register_sidebar` ( must be on theme folder or plugins )
2. add ID to sidebar
```
register_sidebar( array(
'name' => __( 'Main Sidebar', 'theme-slug' ),
'id' => 'change_me', // Add only this line
'description' => __( 'Widgets in this area will be shown on all posts and pages.', 'theme-slug' ),
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2 class="widgettitle">',
'after_title' => '</h2>',
) );
```
Or you can just disable notification in `wp-config.php`
edit `WP_DEBUG` to false
```
define('WP_DEBUG', false);
```
|
227,307 |
<p>I have a custom post type with the fields <code>Exercise</code> and <code>Tempo</code>. Here is an example of how that might look:</p>
<p>Exercise 1 - 100<br>
Exercise 2 - 104<br>
Exercise 3 - 96<br>
Exercise 1 - 104<br>
Exercise 2 - 110<br>
Exercise 3 - 100 </p>
<p>How might I use WP_Query to return only the highest <code>Tempo</code> of each <code>Exercise</code>?</p>
<p>The desired result would be:</p>
<p>Exercise 1 - 104<br>
Exercise 2 - 110<br>
Exericse 3 - 100</p>
<p>EDIT:</p>
<p>I finally got it working (see below) with the way that Rarst suggested. Thanks for the help!</p>
<pre><code> function opl_user_practice_sheet_test($atts, $content = null){
if ( is_user_logged_in()) {
global $current_user;
wp_get_current_user();
echo 'User: ' . $current_user->user_login . "\n";
global $post;
$atts = shortcode_atts( array(
'title' => 'User Practice Sheet',
'count' => -1
), $atts);
// query arguments
$args = array(
'post_type' => 'opl_exercise',
'post_status' => 'publish',
'orderby' => 'created',
'order' => 'DESC',
'posts_per_page' => $atts['count']
);
// fetch practice sheet tempos
$practice_sheet_exercises = new WP_Query($args);
// check if tempos come back
if($practice_sheet_exercises->have_posts()){
// init output
$output = '';
// build output
$output .= '<div class="user-practice-sheet">
<table>
<thead>
<tr>
<td>Exercise</td>
<td>Submitted Tempo</td>
<td>Next Target Tempo</td>
</tr>
</thead>
<tbody>';
while($practice_sheet_exercises->have_posts()){
$practice_sheet_exercises->the_post();
$exercise_type = get_post_meta($post->ID, 'opl_exercise_type', true);
$exercise_number = get_post_meta($post->ID, 'opl_exercise_number', true);
$tempo_query = new WP_Query(
array(
'post_type' => 'opl_tempo_submission',
'order_by' => 'meta_value_num',
'meta_key' => 'opl_submission_tempo',
'order' => 'DESC',
'posts_per_page' => 1,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'opl_submission_exercise_type',
'value' => $exercise_type,
'compare' => '='
),
array(
'key' => 'opl_submission_exercise_number',
'value' => $exercise_number,
'compare' => '='
)
)
)
);
if ( $tempo_query->have_posts() ) {
while ( $tempo_query->have_posts() ) {
$tempo_query->the_post();
$submission_tempo = get_post_meta($post->ID, 'opl_submission_tempo', true);
$output .= '<tr>';
$output .= '<td>'.$exercise_type .' '. $exercise_number.'</td>';
$output .= '<td>'.$submission_tempo.'</td>';
$output .= '<td></td>';
$output .= '</tr>';
}
}
}
$output .= '</tbody>
</table>
</div>';
// reset post data
wp_reset_postdata();
return $output;
} else {
return '<p>No Practice Sheet Found</p>';
}
}
}
</code></pre>
|
[
{
"answer_id": 227303,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>Looks like you have a very old theme. You'll have to search the <code>functions.php</code> file for <code>register_sidebar</code> and make sure the <code>$args</code> follow the format <a href=\"https://codex.wordpress.org/Function_Reference/register_sidebar\" rel=\"nofollow\">mentioned in the codex</a>.</p>\n"
},
{
"answer_id": 227304,
"author": "Nefro",
"author_id": 86801,
"author_profile": "https://wordpress.stackexchange.com/users/86801",
"pm_score": 4,
"selected": false,
"text": "<ol>\n<li><p>Find file where is <code>register_sidebar</code> ( must be on theme folder or plugins )</p></li>\n<li><p>add ID to sidebar</p>\n\n<pre><code>register_sidebar( array(\n 'name' => __( 'Main Sidebar', 'theme-slug' ),\n\n 'id' => 'change_me', // Add only this line\n\n 'description' => __( 'Widgets in this area will be shown on all posts and pages.', 'theme-slug' ),\n 'before_widget' => '<li id=\"%1$s\" class=\"widget %2$s\">',\n 'after_widget' => '</li>',\n 'before_title' => '<h2 class=\"widgettitle\">',\n 'after_title' => '</h2>',\n ) );\n</code></pre></li>\n</ol>\n\n<p>Or you can just disable notification in <code>wp-config.php</code> </p>\n\n<p>edit <code>WP_DEBUG</code> to false</p>\n\n<pre><code>define('WP_DEBUG', false);\n</code></pre>\n"
}
] |
2016/05/20
|
[
"https://wordpress.stackexchange.com/questions/227307",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93811/"
] |
I have a custom post type with the fields `Exercise` and `Tempo`. Here is an example of how that might look:
Exercise 1 - 100
Exercise 2 - 104
Exercise 3 - 96
Exercise 1 - 104
Exercise 2 - 110
Exercise 3 - 100
How might I use WP\_Query to return only the highest `Tempo` of each `Exercise`?
The desired result would be:
Exercise 1 - 104
Exercise 2 - 110
Exericse 3 - 100
EDIT:
I finally got it working (see below) with the way that Rarst suggested. Thanks for the help!
```
function opl_user_practice_sheet_test($atts, $content = null){
if ( is_user_logged_in()) {
global $current_user;
wp_get_current_user();
echo 'User: ' . $current_user->user_login . "\n";
global $post;
$atts = shortcode_atts( array(
'title' => 'User Practice Sheet',
'count' => -1
), $atts);
// query arguments
$args = array(
'post_type' => 'opl_exercise',
'post_status' => 'publish',
'orderby' => 'created',
'order' => 'DESC',
'posts_per_page' => $atts['count']
);
// fetch practice sheet tempos
$practice_sheet_exercises = new WP_Query($args);
// check if tempos come back
if($practice_sheet_exercises->have_posts()){
// init output
$output = '';
// build output
$output .= '<div class="user-practice-sheet">
<table>
<thead>
<tr>
<td>Exercise</td>
<td>Submitted Tempo</td>
<td>Next Target Tempo</td>
</tr>
</thead>
<tbody>';
while($practice_sheet_exercises->have_posts()){
$practice_sheet_exercises->the_post();
$exercise_type = get_post_meta($post->ID, 'opl_exercise_type', true);
$exercise_number = get_post_meta($post->ID, 'opl_exercise_number', true);
$tempo_query = new WP_Query(
array(
'post_type' => 'opl_tempo_submission',
'order_by' => 'meta_value_num',
'meta_key' => 'opl_submission_tempo',
'order' => 'DESC',
'posts_per_page' => 1,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'opl_submission_exercise_type',
'value' => $exercise_type,
'compare' => '='
),
array(
'key' => 'opl_submission_exercise_number',
'value' => $exercise_number,
'compare' => '='
)
)
)
);
if ( $tempo_query->have_posts() ) {
while ( $tempo_query->have_posts() ) {
$tempo_query->the_post();
$submission_tempo = get_post_meta($post->ID, 'opl_submission_tempo', true);
$output .= '<tr>';
$output .= '<td>'.$exercise_type .' '. $exercise_number.'</td>';
$output .= '<td>'.$submission_tempo.'</td>';
$output .= '<td></td>';
$output .= '</tr>';
}
}
}
$output .= '</tbody>
</table>
</div>';
// reset post data
wp_reset_postdata();
return $output;
} else {
return '<p>No Practice Sheet Found</p>';
}
}
}
```
|
1. Find file where is `register_sidebar` ( must be on theme folder or plugins )
2. add ID to sidebar
```
register_sidebar( array(
'name' => __( 'Main Sidebar', 'theme-slug' ),
'id' => 'change_me', // Add only this line
'description' => __( 'Widgets in this area will be shown on all posts and pages.', 'theme-slug' ),
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2 class="widgettitle">',
'after_title' => '</h2>',
) );
```
Or you can just disable notification in `wp-config.php`
edit `WP_DEBUG` to false
```
define('WP_DEBUG', false);
```
|
227,315 |
<p>Facebook's Instant Articles rejects articles that contain hyperlinks to the current page (e.g. <code><a href="#_ftn1">[1]</a></code>). How can I filter the post content to remove these links before publishing to Facebook Instant Articles?</p>
<p>I'm aware of a similar question on StackOverflow: <a href="https://stackoverflow.com/questions/11282580/how-to-remove-hyperlink-of-images-in-wordpress-post">How to remove hyperlink of images in wordpress post?</a>, but my RegEx skills aren't good enough to convert that to what I need.</p>
<p>PS - I'm using the semi-official <a href="https://en-gb.wordpress.org/plugins/fb-instant-articles/" rel="nofollow noreferrer">Instant Articles for WP</a>, which means I can filter <code>instant_articles_content</code>.</p>
<p>PPS - It would be nice to know both how to remove the link but leave the link text, and how to remove both the link and the link text.</p>
|
[
{
"answer_id": 227303,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>Looks like you have a very old theme. You'll have to search the <code>functions.php</code> file for <code>register_sidebar</code> and make sure the <code>$args</code> follow the format <a href=\"https://codex.wordpress.org/Function_Reference/register_sidebar\" rel=\"nofollow\">mentioned in the codex</a>.</p>\n"
},
{
"answer_id": 227304,
"author": "Nefro",
"author_id": 86801,
"author_profile": "https://wordpress.stackexchange.com/users/86801",
"pm_score": 4,
"selected": false,
"text": "<ol>\n<li><p>Find file where is <code>register_sidebar</code> ( must be on theme folder or plugins )</p></li>\n<li><p>add ID to sidebar</p>\n\n<pre><code>register_sidebar( array(\n 'name' => __( 'Main Sidebar', 'theme-slug' ),\n\n 'id' => 'change_me', // Add only this line\n\n 'description' => __( 'Widgets in this area will be shown on all posts and pages.', 'theme-slug' ),\n 'before_widget' => '<li id=\"%1$s\" class=\"widget %2$s\">',\n 'after_widget' => '</li>',\n 'before_title' => '<h2 class=\"widgettitle\">',\n 'after_title' => '</h2>',\n ) );\n</code></pre></li>\n</ol>\n\n<p>Or you can just disable notification in <code>wp-config.php</code> </p>\n\n<p>edit <code>WP_DEBUG</code> to false</p>\n\n<pre><code>define('WP_DEBUG', false);\n</code></pre>\n"
}
] |
2016/05/20
|
[
"https://wordpress.stackexchange.com/questions/227315",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/19528/"
] |
Facebook's Instant Articles rejects articles that contain hyperlinks to the current page (e.g. `<a href="#_ftn1">[1]</a>`). How can I filter the post content to remove these links before publishing to Facebook Instant Articles?
I'm aware of a similar question on StackOverflow: [How to remove hyperlink of images in wordpress post?](https://stackoverflow.com/questions/11282580/how-to-remove-hyperlink-of-images-in-wordpress-post), but my RegEx skills aren't good enough to convert that to what I need.
PS - I'm using the semi-official [Instant Articles for WP](https://en-gb.wordpress.org/plugins/fb-instant-articles/), which means I can filter `instant_articles_content`.
PPS - It would be nice to know both how to remove the link but leave the link text, and how to remove both the link and the link text.
|
1. Find file where is `register_sidebar` ( must be on theme folder or plugins )
2. add ID to sidebar
```
register_sidebar( array(
'name' => __( 'Main Sidebar', 'theme-slug' ),
'id' => 'change_me', // Add only this line
'description' => __( 'Widgets in this area will be shown on all posts and pages.', 'theme-slug' ),
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2 class="widgettitle">',
'after_title' => '</h2>',
) );
```
Or you can just disable notification in `wp-config.php`
edit `WP_DEBUG` to false
```
define('WP_DEBUG', false);
```
|
227,360 |
<p>I feel there is a red button saying "Do not press" below <code>query_posts()</code>. For some time I am trying to demystify this phenomena with very low success to be honest. </p>
<p>For example, probable the main reason not to use this function is a broken pagination. Second, was it may be slow (read: calling twice), or there are better ways (<code>pre_get_posts</code>). There may be more reasons. </p>
<p>For those who may downwote this question from instinct, I would appeal, to hold at least for a week or so. There is always a second chance to do that. I am hardly waiting to see at least some answers, before a team pressure.</p>
<p>For those not read <a href="https://wordpress.stackexchange.com/questions/226960/why-query-posts-isnt-marked-as-deprecated">this</a> post, I would say that this function is nor deprecated, nor it is marked as <code>_doing_it_wrong</code>, nor there are plans.
Even the ticket to make it deprecated has been closed recently.</p>
<p>Some may say they read this function must not be used within the WordPress. I am providing in here the full function.</p>
<pre><code>File: /wp-includes/query.php
79: /**
80: * Set up The Loop with query parameters.
81: *
82: * This will override the current WordPress Loop and shouldn't be used more than
83: * once. This must not be used within the WordPress Loop.
84: *
85: * @since 1.5.0
86: *
87: * @global WP_Query $wp_query Global WP_Query instance.
88: *
89: * @param string $query
90: * @return array List of posts
91: */
92: function query_posts($query) {
93: $GLOBALS['wp_query'] = new WP_Query();
94: return $GLOBALS['wp_query']->query($query);
95: }
</code></pre>
<p>You can see <code>This must not be used within the WordPress Loop.</code>, meaning not within the WordPress loop, implying that before the WordPress loop may be not prohibited.</p>
<p>I noted <a href="https://wordpress.stackexchange.com/questions/227244/is-query-posts-really-slower-than-secondary-query">from this post</a> that this function is not slower than any secondary query (having the same arguments). </p>
<p>Bottomline, speaking of the pagination <code>query_posts</code> is much better solution for the pagination than the <code>get_posts</code> since <code>get_posts</code> actually disables <code>SQL_CALC_FOUND_ROWS</code>.</p>
<p>Some good thoughts on the <code>query_posts</code> may be:</p>
<ul>
<li>the query arguments are not limited, you can set anything you like.</li>
<li>you can even set the arguments to use pagination, if you don't plan to use core pagination functions; super easy you can create your own pagination</li>
<li>in a typical blog only small portion of the pages, may use pagination. The most of the pages, in a majority of regular simple cases, don't even use pagination so to do something quick and to reuse the main query templates (read loop) <code>query_posts</code> may be handy.</li>
</ul>
<p>These are just a the few thoughts, I am sure there are more, but certainly If you know what you are downing you cannot be wrong.</p>
<hr>
<p><a href="https://i.stack.imgur.com/RTGaH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RTGaH.png" alt="Do no"></a></p>
|
[
{
"answer_id": 227362,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 3,
"selected": false,
"text": "<p><code>query_posts()</code> is useful in cases when there is <strong>no main query</strong>: calls to <code>wp-admin/admin-ajax.php</code>, <code>wp-admin/admin-post.php</code> or <code>wp-login.php</code> for example. </p>\n\n<p>Yes, you can achieve the same results there without <code>query_posts()</code> and slightly less compact code instead. But if you don't have to care about side effects, using <code>query_posts()</code> is acceptable.</p>\n"
},
{
"answer_id": 227379,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>Whenever the main query is available, which is for every front end page load regardless of which page/archive is loaded, you should use <code>pre_get_posts</code> to alter the main query's query vars before the SQL query is build and executed. This goes for each and every page where you need to alter the main query. This is the <strong>RECOMMENDED</strong> way to alter the main query. Doing it this way will not result in any extra db queries being made, period. For true pages and static front pages, you can always use my <a href=\"https://wordpress.stackexchange.com/a/215027/31545\"><code>PreGetPostsForPages</code> class</a> or even <a href=\"https://stackoverflow.com/a/22142984/1908141\">the <code>pre_get_posts</code> method described by @birgire here</a>.</p>\n\n<p>You should never ever replace the main query with a custom one, neither using <code>query_posts</code>, a new instance of <code>WP_Query</code> or <code>get_posts</code>. This adds extra db calls per page load because the main query runs regardless. If you replace the main query with a custom one, you are running twice as many db calls which also increases page load times. Not just that, pagination becomes a nightmare. You should take your time and read <a href=\"https://wordpress.stackexchange.com/a/176412/31545\">this answer I have done on pagination</a>.</p>\n\n<p>You should only ever run custom queries for things like sliders, widgets, related posts and navigation menus, never ever to replace or alter the main query. </p>\n\n<p><code>query_posts</code> still stays a very problematic way to run custom queries as it alter the main query object stored in <code>$wp_query</code> (<em>$GLOBALS['wp_query']</em>) because so many functions and plugins relies on the main query object to run things like pagination and related posts and breadcrumbs</p>\n\n<p>As @toscho already mentioned, only use <code>query_posts</code> when there is no main query, which is for ajax calls, and some pages on the admin side. Apart from that, you really really should avoid using it, accepts when you really need to break something on the front end. </p>\n\n<p>As I said, there is absolutely no need at all to run any type of custom query in place of the main query just to alter or modify the output from the page. If you really need better performance and faster loading times, use <code>pre_get_posts</code> to alter the main query and never replace it for whatever reason at all. Custom queries are meant to do additional stuff like widgets, related posts and sliders</p>\n\n<h2>EDIT</h2>\n\n<p>As final note, and proof, download and install the Query Monitor plugin. This way you can see the drastic increase in page load time and db calls when you replace the main query with any custom query and how there is no difference when using <code>pre_get_posts</code></p>\n"
},
{
"answer_id": 250295,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 1,
"selected": true,
"text": "<p>Opposite from the common believes <code>query_posts</code> is harmless if you know how to use it. I tried <a href=\"https://wordpress.stackexchange.com/questions/226960/why-query-posts-isnt-marked-as-deprecated/248955#248955\">here</a> to provide more arguments.</p>\n<p>In here I will add a simple outline that you never should rely on:\n<code>$GLOBALS['wp_query']</code>.</p>\n<p>You should rely on <code>$GLOBALS['wp_the_query']</code> that should be frozen.\nIf you like to reset the <code>$GLOBALS['wp_query']</code> just use <code>wp_reset_query</code>.</p>\n<h3>Use case</h3>\n<p><a href=\"https://i.stack.imgur.com/vJvv9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vJvv9.png\" alt=\"enter image description here\" /></a></p>\n<p>For example, if you need this on a homepage, after the main loop, you may call <code>query_posts</code> for the cpt1 and later <code>query_posts</code> again for the cpt2.</p>\n"
}
] |
2016/05/20
|
[
"https://wordpress.stackexchange.com/questions/227360",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88606/"
] |
I feel there is a red button saying "Do not press" below `query_posts()`. For some time I am trying to demystify this phenomena with very low success to be honest.
For example, probable the main reason not to use this function is a broken pagination. Second, was it may be slow (read: calling twice), or there are better ways (`pre_get_posts`). There may be more reasons.
For those who may downwote this question from instinct, I would appeal, to hold at least for a week or so. There is always a second chance to do that. I am hardly waiting to see at least some answers, before a team pressure.
For those not read [this](https://wordpress.stackexchange.com/questions/226960/why-query-posts-isnt-marked-as-deprecated) post, I would say that this function is nor deprecated, nor it is marked as `_doing_it_wrong`, nor there are plans.
Even the ticket to make it deprecated has been closed recently.
Some may say they read this function must not be used within the WordPress. I am providing in here the full function.
```
File: /wp-includes/query.php
79: /**
80: * Set up The Loop with query parameters.
81: *
82: * This will override the current WordPress Loop and shouldn't be used more than
83: * once. This must not be used within the WordPress Loop.
84: *
85: * @since 1.5.0
86: *
87: * @global WP_Query $wp_query Global WP_Query instance.
88: *
89: * @param string $query
90: * @return array List of posts
91: */
92: function query_posts($query) {
93: $GLOBALS['wp_query'] = new WP_Query();
94: return $GLOBALS['wp_query']->query($query);
95: }
```
You can see `This must not be used within the WordPress Loop.`, meaning not within the WordPress loop, implying that before the WordPress loop may be not prohibited.
I noted [from this post](https://wordpress.stackexchange.com/questions/227244/is-query-posts-really-slower-than-secondary-query) that this function is not slower than any secondary query (having the same arguments).
Bottomline, speaking of the pagination `query_posts` is much better solution for the pagination than the `get_posts` since `get_posts` actually disables `SQL_CALC_FOUND_ROWS`.
Some good thoughts on the `query_posts` may be:
* the query arguments are not limited, you can set anything you like.
* you can even set the arguments to use pagination, if you don't plan to use core pagination functions; super easy you can create your own pagination
* in a typical blog only small portion of the pages, may use pagination. The most of the pages, in a majority of regular simple cases, don't even use pagination so to do something quick and to reuse the main query templates (read loop) `query_posts` may be handy.
These are just a the few thoughts, I am sure there are more, but certainly If you know what you are downing you cannot be wrong.
---
[](https://i.stack.imgur.com/RTGaH.png)
|
Opposite from the common believes `query_posts` is harmless if you know how to use it. I tried [here](https://wordpress.stackexchange.com/questions/226960/why-query-posts-isnt-marked-as-deprecated/248955#248955) to provide more arguments.
In here I will add a simple outline that you never should rely on:
`$GLOBALS['wp_query']`.
You should rely on `$GLOBALS['wp_the_query']` that should be frozen.
If you like to reset the `$GLOBALS['wp_query']` just use `wp_reset_query`.
### Use case
[](https://i.stack.imgur.com/vJvv9.png)
For example, if you need this on a homepage, after the main loop, you may call `query_posts` for the cpt1 and later `query_posts` again for the cpt2.
|
227,404 |
<p>I have a custom post type in my plugin "Luckydraw" as 'voucher'. </p>
<p>By clicking on post link, wordpress generates its URL as :</p>
<pre><code>http://localhost:81/luckydraw/index.php/voucher/testing-2/
</code></pre>
<p>But I want to change it to:</p>
<pre><code>http://localhost:81/luckydraw/voucher/testing-2/
</code></pre>
<p>How would I do this?</p>
|
[
{
"answer_id": 227405,
"author": "Mukesh Ram",
"author_id": 93667,
"author_profile": "https://wordpress.stackexchange.com/users/93667",
"pm_score": -1,
"selected": false,
"text": "<p>Change or add the \n<code>'rewrite' => array( 'slug' => 'luckydraw', 'with_front' => false ),</code>\ninto the <strong>register_post_type</strong> arguments, This will change the slug of your custom post type. </p>\n"
},
{
"answer_id": 227407,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 1,
"selected": false,
"text": "<p>I am not sure I follow your question, title seems different from question itself.</p>\n\n<p>You seem to want to get rid of <code>index.php</code> in URL?</p>\n\n<p>It's hard to say confidently from outside, but it looks like <a href=\"https://codex.wordpress.org/Using_Permalinks#PATHINFO:_.22Almost_Pretty.22\" rel=\"nofollow\">PATHINFO permalink</a>.</p>\n\n<p>If that's the case you would need to change your WP permalink configuration to more common \"pretty\" one. Doesn't have anything to do with CPT's config.</p>\n"
},
{
"answer_id": 227419,
"author": "Owais Alam",
"author_id": 91939,
"author_profile": "https://wordpress.stackexchange.com/users/91939",
"pm_score": 0,
"selected": false,
"text": "<p>You can achieve your task in both ways through plugin as well as coding</p>\n\n<p><strong>Manually</strong></p>\n\n<p>Please see the documentation on <a href=\"http://codex.wordpress.org/Post_Types#URLs_of_Namespaced_Custom_Post_Types_Identifiers\" rel=\"nofollow\">URLs of Namespaced Custom Post Types Identifiers</a>. One of the options available to you is to add a <code>'rewrite'</code> argument to <a href=\"http://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow\">register_post_type()</a>. From the docs:</p>\n\n<p><strong>Plugin</strong></p>\n\n<p>Custom Post Type Permalinks allow you edit the permalink structure of custom post type.</p>\n\n<p>Download Link: <a href=\"https://wordpress.org/plugins/custom-post-type-permalinks/\" rel=\"nofollow\">Custom Post Type Permalinks</a></p>\n"
}
] |
2016/05/21
|
[
"https://wordpress.stackexchange.com/questions/227404",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91044/"
] |
I have a custom post type in my plugin "Luckydraw" as 'voucher'.
By clicking on post link, wordpress generates its URL as :
```
http://localhost:81/luckydraw/index.php/voucher/testing-2/
```
But I want to change it to:
```
http://localhost:81/luckydraw/voucher/testing-2/
```
How would I do this?
|
I am not sure I follow your question, title seems different from question itself.
You seem to want to get rid of `index.php` in URL?
It's hard to say confidently from outside, but it looks like [PATHINFO permalink](https://codex.wordpress.org/Using_Permalinks#PATHINFO:_.22Almost_Pretty.22).
If that's the case you would need to change your WP permalink configuration to more common "pretty" one. Doesn't have anything to do with CPT's config.
|
227,417 |
<p>So, I'm building a theme for a client with one page layout functionality. Currently, I'm allowing the user to create a parent page, and the modules within that page are separate pages that will be set as children of the main page. </p>
<p>Clarifying. I have a home page. Within the home page, I need to have a section to display a product tour and also a map. The client will create the parent page Home and then create a page called <code>Product Tour</code> & <code>Map</code>. These pages will be set as children of <code>Home</code> and I have set up a loop that will pull all children of the page and display them.</p>
<p>Here's where I'm getting stuck. I need to allow my client to create a child page and set a custom page template that will then display on the main page. Does anyone know how I can make the <code>loop</code> work this way, looking for the page template and displaying the content through that page template, based on user choice? I've Googled everything imaginable, searched every forum and I can't find anything helpful, so I figured some of you WordPress mega ninjas could be amazing and give me a little bit of much needed help.</p>
<p>I've found another answer similar to this question <a href="https://wordpress.stackexchange.com/questions/159724/getting-the-chosen-template-when-iterating-through-pages">here</a>, but I need someone to clarify exactly how I can implement this.</p>
<p>I will be eternally grateful.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 227446,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 0,
"selected": false,
"text": "<p>The question you linked to doesn't <em>quite</em> do what you're wanting - it allows you to get the template assigned to a page you're querying, but what you're actually wanting is to <em>get a page</em> assigned to a particular template.</p>\n\n<p>You can do this using the <code>get_pages()</code> function by querying a meta key of the page.</p>\n\n<p>Pages/posts can have a range of fields assigned to them, both built-in fields and custom fields. Anything outside of the standard (such as date, post type, author, etc.) is called 'post meta'. For pages, the 'page template' setting is one such meta item that you can individually query.</p>\n\n<p>Here's how you do it in your case:</p>\n\n<pre><code>$templated_pages = get_pages(\n array(\n \"meta_key\" => \"_wp_page_template\",\n \"meta_value\" => \"file-name-of-your-template.php\",\n )\n);\n\nforeach($templated_pages as $page){\n print_r($page); // print everything so you can see what you've got\n echo get_the_title($page); // print the title\n echo apply_filters(\"the_content\", $page->post_content); // print the content of the page\n}\n</code></pre>\n\n<p>For more details on the get_pages() function you can see the <a href=\"https://developer.wordpress.org/reference/functions/get_pages/\" rel=\"nofollow\">Wordpress function reference</a>. Depending on what information you want to get out, there are other functions you can look up as well - eg. you can get the title and content as described above, or anything else you need, by using the information present in the <code>$page</code> variable within that foreach loop.</p>\n"
},
{
"answer_id": 227458,
"author": "Jesse Winton",
"author_id": 83015,
"author_profile": "https://wordpress.stackexchange.com/users/83015",
"pm_score": 2,
"selected": true,
"text": "<p>I was able to figure this out and make it dynamic.</p>\n\n<p>I created a variable <code>$template</code> that I put inside the loop, in which I stored the page template.</p>\n\n<p><code>$template = get_post_meta( $post->ID, '_wp_page_template', true );</code></p>\n\n<p>Then, I utilize this where I need the child pages to show up.</p>\n\n<p><code><?php include(locate_template($template)); ?></code></p>\n\n<p>This is working for me and is pulling each child page into the parent page according to their chosen page template. Here, for your enjoyment is the entirety of the code.</p>\n\n<pre><code><?php \n $this_page=get_query_var('page_id');\n $loop = new WP_Query( array('post_type'=>'page', 'posts_per_page' => -1, 'post_parent' => $this_page, 'orderby' => 'menu_order', 'order' => 'ASC') ); \n while ( $loop->have_posts() ) : $loop->the_post();\n\n <?php include(locate_template($template)); ?>\n\n<?php endwhile; endif; ?>\n</code></pre>\n"
}
] |
2016/05/21
|
[
"https://wordpress.stackexchange.com/questions/227417",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83015/"
] |
So, I'm building a theme for a client with one page layout functionality. Currently, I'm allowing the user to create a parent page, and the modules within that page are separate pages that will be set as children of the main page.
Clarifying. I have a home page. Within the home page, I need to have a section to display a product tour and also a map. The client will create the parent page Home and then create a page called `Product Tour` & `Map`. These pages will be set as children of `Home` and I have set up a loop that will pull all children of the page and display them.
Here's where I'm getting stuck. I need to allow my client to create a child page and set a custom page template that will then display on the main page. Does anyone know how I can make the `loop` work this way, looking for the page template and displaying the content through that page template, based on user choice? I've Googled everything imaginable, searched every forum and I can't find anything helpful, so I figured some of you WordPress mega ninjas could be amazing and give me a little bit of much needed help.
I've found another answer similar to this question [here](https://wordpress.stackexchange.com/questions/159724/getting-the-chosen-template-when-iterating-through-pages), but I need someone to clarify exactly how I can implement this.
I will be eternally grateful.
Thanks!
|
I was able to figure this out and make it dynamic.
I created a variable `$template` that I put inside the loop, in which I stored the page template.
`$template = get_post_meta( $post->ID, '_wp_page_template', true );`
Then, I utilize this where I need the child pages to show up.
`<?php include(locate_template($template)); ?>`
This is working for me and is pulling each child page into the parent page according to their chosen page template. Here, for your enjoyment is the entirety of the code.
```
<?php
$this_page=get_query_var('page_id');
$loop = new WP_Query( array('post_type'=>'page', 'posts_per_page' => -1, 'post_parent' => $this_page, 'orderby' => 'menu_order', 'order' => 'ASC') );
while ( $loop->have_posts() ) : $loop->the_post();
<?php include(locate_template($template)); ?>
<?php endwhile; endif; ?>
```
|
227,430 |
<p>I want to make a menu with hover animations. My HTML syntax looks like this:</p>
<pre><code><ul class="menus">
<li class="current"><a href="#" data-hover="Home">Home</a></li>
<li><a href="#" data-hover="About Us">About Us</a></li>
<li><a href="#" data-hover="Blog">Blog</a></li>
<li><a href="#" data-hover="Services">Services</a></li>
<li><a href="#" data-hover="Products">Products</a></li>
<li><a href="#" data-hover="Contact">Contact</a></li>
</ul>
</code></pre>
<p>How can I add a data attribute like <code>data-hover="About Us"</code> for each menu dynamically?</p>
|
[
{
"answer_id": 227434,
"author": "Alex",
"author_id": 94487,
"author_profile": "https://wordpress.stackexchange.com/users/94487",
"pm_score": 2,
"selected": false,
"text": "<p>If you want WordPress to add these items dynamically you would need to add a custom walker class to your menu declaration.</p>\n\n<ol>\n<li><p>Find where your menu is declared in the theme and add a custom walker class name in their <code>wp_nav_menu</code> function:</p>\n\n<pre><code>wp_nav_menu( array ( 'menu'=> 'main-menu', 'container'=> '', 'walker' => new Description_Walker));\n</code></pre></li>\n<li><p>The menu may have a bunch of values but just add the line:</p>\n\n<pre><code>'walker' => new Description_Walker\n</code></pre></li>\n</ol>\n\n<p>Then you will want to create the custom walker class to extend the menu class. Here is a giant example of this:</p>\n\n<pre><code>wp_nav_menu( array(\n 'menu' => 'Something custom walker',\n 'walker' => new WPDocs_Walker_Nav_Menu()\n) );\n\n/**\n * Custom walker class.\n */\nclass WPDocs_Walker_Nav_Menu extends Walker_Nav_Menu {\n\n /**\n * Starts the list before the elements are added.\n *\n * Adds classes to the unordered list sub-menus.\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @param int $depth Depth of menu item. Used for padding.\n * @param array $args An array of arguments. @see wp_nav_menu()\n */\n function start_lvl( &$output, $depth = 0, $args = array() ) {\n // Depth-dependent classes.\n $indent = ( $depth > 0 ? str_repeat( \"\\t\", $depth ) : '' ); // code indent\n $display_depth = ( $depth + 1); // because it counts the first submenu as 0\n $classes = array(\n 'sub-menu',\n ( $display_depth % 2 ? 'menu-odd' : 'menu-even' ),\n ( $display_depth >=2 ? 'sub-sub-menu' : '' ),\n 'menu-depth-' . $display_depth\n );\n $class_names = implode( ' ', $classes );\n\n // Build HTML for output.\n $output .= \"\\n\" . $indent . '<ul class=\"' . $class_names . '\">' . \"\\n\";\n }\n\n /**\n * Start the element output.\n *\n * Adds main/sub-classes to the list items and links.\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @param object $item Menu item data object.\n * @param int $depth Depth of menu item. Used for padding.\n * @param array $args An array of arguments. @see wp_nav_menu()\n * @param int $id Current item ID.\n */\n function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n global $wp_query;\n $indent = ( $depth > 0 ? str_repeat( \"\\t\", $depth ) : '' ); // code indent\n\n // Depth-dependent classes.\n $depth_classes = array(\n ( $depth == 0 ? 'main-menu-item' : 'sub-menu-item' ),\n ( $depth >=2 ? 'sub-sub-menu-item' : '' ),\n ( $depth % 2 ? 'menu-item-odd' : 'menu-item-even' ),\n 'menu-item-depth-' . $depth\n );\n $depth_class_names = esc_attr( implode( ' ', $depth_classes ) );\n\n // Passed classes.\n $classes = empty( $item->classes ) ? array() : (array) $item->classes;\n $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) );\n\n // Build HTML.\n $output .= $indent . '<li id=\"nav-menu-item-'. $item->ID . '\" class=\"' . $depth_class_names . ' ' . $class_names . '\">';\n\n // Link attributes.\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 $attributes .= ' class=\"menu-link ' . ( $depth > 0 ? 'sub-menu-link' : 'main-menu-link' ) . '\"';\n\n // Build HTML output and pass through the proper filter.\n $item_output = sprintf( '%1$s<a%2$s>%3$s%4$s%5$s</a>%6$s',\n $args->before,\n $attributes,\n $args->link_before,\n apply_filters( 'the_title', $item->title, $item->ID ),\n $args->link_after,\n $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>You see the part that says:</p>\n\n<pre><code>// Build HTML.\n$output .= $indent . '<li id=\"nav-menu-item-'. $item->ID . '\" class=\"' . $depth_class_names . ' ' . $class_names . '\">';\n</code></pre>\n\n<p>Just add the <code>data-hover=\"' .$item->title. '\"</code> or something like that to it and it will automatically add what you want.</p>\n\n<p>I took that code from: </p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/#Using_a_Custom_Walker_Function\" rel=\"nofollow\">Using a Custom Walker Function</a></li>\n</ul>\n\n<p>Also here is a tutorial about making the walker class if needed:</p>\n\n<ul>\n<li><a href=\"http://www.kriesi.at/archives/improve-your-wordpress-navigation-menu-output\" rel=\"nofollow\">Improve your WordPress Navigation Menu Output</a></li>\n</ul>\n"
},
{
"answer_id": 255416,
"author": "pagol",
"author_id": 16755,
"author_profile": "https://wordpress.stackexchange.com/users/16755",
"pm_score": 3,
"selected": true,
"text": "<p>I found one small and nice solution.</p>\n\n<pre><code>add_filter( 'nav_menu_link_attributes', 'cfw_add_data_atts_to_nav', 10, 4 );\nfunction cfw_add_data_atts_to_nav( $atts, $item, $args )\n{\n $atts['data-hover'] = $item->title;\n return $atts;\n}\n</code></pre>\n\n<p>I tested it and it works.</p>\n"
}
] |
2016/05/22
|
[
"https://wordpress.stackexchange.com/questions/227430",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16755/"
] |
I want to make a menu with hover animations. My HTML syntax looks like this:
```
<ul class="menus">
<li class="current"><a href="#" data-hover="Home">Home</a></li>
<li><a href="#" data-hover="About Us">About Us</a></li>
<li><a href="#" data-hover="Blog">Blog</a></li>
<li><a href="#" data-hover="Services">Services</a></li>
<li><a href="#" data-hover="Products">Products</a></li>
<li><a href="#" data-hover="Contact">Contact</a></li>
</ul>
```
How can I add a data attribute like `data-hover="About Us"` for each menu dynamically?
|
I found one small and nice solution.
```
add_filter( 'nav_menu_link_attributes', 'cfw_add_data_atts_to_nav', 10, 4 );
function cfw_add_data_atts_to_nav( $atts, $item, $args )
{
$atts['data-hover'] = $item->title;
return $atts;
}
```
I tested it and it works.
|
227,435 |
<p>I'm wondering if it is at all possible to set display a page template chosen by the user within the context of a <code>query_posts</code> using <code>get_template_part</code>. In other words, I have set up a page template to pull all of it's child pages and display them, but I need each child page to display according to the page template that is chosen in the page editor. Is there any way to make that happen? Here is the code I have for the parent page template so far.</p>
<pre><code><?php
$this_page=get_query_var('page_id');
query_posts( array('post_type'=>'page', 'posts_per_page' => -1, 'post_parent' => $this_page, 'orderby' => 'menu_order', 'order' => 'ASC') );
if(have_posts()): while(have_posts()): the_post();
?>
<?php get_template_part('_wp_page_template'); ?>
<?php endwhile; endif; ?>
</code></pre>
<p>So, as you can see, I've got the query pulling all of the child pages. I'd like to know how I can make each of these child pages display according to their chosen page template.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 227434,
"author": "Alex",
"author_id": 94487,
"author_profile": "https://wordpress.stackexchange.com/users/94487",
"pm_score": 2,
"selected": false,
"text": "<p>If you want WordPress to add these items dynamically you would need to add a custom walker class to your menu declaration.</p>\n\n<ol>\n<li><p>Find where your menu is declared in the theme and add a custom walker class name in their <code>wp_nav_menu</code> function:</p>\n\n<pre><code>wp_nav_menu( array ( 'menu'=> 'main-menu', 'container'=> '', 'walker' => new Description_Walker));\n</code></pre></li>\n<li><p>The menu may have a bunch of values but just add the line:</p>\n\n<pre><code>'walker' => new Description_Walker\n</code></pre></li>\n</ol>\n\n<p>Then you will want to create the custom walker class to extend the menu class. Here is a giant example of this:</p>\n\n<pre><code>wp_nav_menu( array(\n 'menu' => 'Something custom walker',\n 'walker' => new WPDocs_Walker_Nav_Menu()\n) );\n\n/**\n * Custom walker class.\n */\nclass WPDocs_Walker_Nav_Menu extends Walker_Nav_Menu {\n\n /**\n * Starts the list before the elements are added.\n *\n * Adds classes to the unordered list sub-menus.\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @param int $depth Depth of menu item. Used for padding.\n * @param array $args An array of arguments. @see wp_nav_menu()\n */\n function start_lvl( &$output, $depth = 0, $args = array() ) {\n // Depth-dependent classes.\n $indent = ( $depth > 0 ? str_repeat( \"\\t\", $depth ) : '' ); // code indent\n $display_depth = ( $depth + 1); // because it counts the first submenu as 0\n $classes = array(\n 'sub-menu',\n ( $display_depth % 2 ? 'menu-odd' : 'menu-even' ),\n ( $display_depth >=2 ? 'sub-sub-menu' : '' ),\n 'menu-depth-' . $display_depth\n );\n $class_names = implode( ' ', $classes );\n\n // Build HTML for output.\n $output .= \"\\n\" . $indent . '<ul class=\"' . $class_names . '\">' . \"\\n\";\n }\n\n /**\n * Start the element output.\n *\n * Adds main/sub-classes to the list items and links.\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @param object $item Menu item data object.\n * @param int $depth Depth of menu item. Used for padding.\n * @param array $args An array of arguments. @see wp_nav_menu()\n * @param int $id Current item ID.\n */\n function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {\n global $wp_query;\n $indent = ( $depth > 0 ? str_repeat( \"\\t\", $depth ) : '' ); // code indent\n\n // Depth-dependent classes.\n $depth_classes = array(\n ( $depth == 0 ? 'main-menu-item' : 'sub-menu-item' ),\n ( $depth >=2 ? 'sub-sub-menu-item' : '' ),\n ( $depth % 2 ? 'menu-item-odd' : 'menu-item-even' ),\n 'menu-item-depth-' . $depth\n );\n $depth_class_names = esc_attr( implode( ' ', $depth_classes ) );\n\n // Passed classes.\n $classes = empty( $item->classes ) ? array() : (array) $item->classes;\n $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) );\n\n // Build HTML.\n $output .= $indent . '<li id=\"nav-menu-item-'. $item->ID . '\" class=\"' . $depth_class_names . ' ' . $class_names . '\">';\n\n // Link attributes.\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 $attributes .= ' class=\"menu-link ' . ( $depth > 0 ? 'sub-menu-link' : 'main-menu-link' ) . '\"';\n\n // Build HTML output and pass through the proper filter.\n $item_output = sprintf( '%1$s<a%2$s>%3$s%4$s%5$s</a>%6$s',\n $args->before,\n $attributes,\n $args->link_before,\n apply_filters( 'the_title', $item->title, $item->ID ),\n $args->link_after,\n $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>You see the part that says:</p>\n\n<pre><code>// Build HTML.\n$output .= $indent . '<li id=\"nav-menu-item-'. $item->ID . '\" class=\"' . $depth_class_names . ' ' . $class_names . '\">';\n</code></pre>\n\n<p>Just add the <code>data-hover=\"' .$item->title. '\"</code> or something like that to it and it will automatically add what you want.</p>\n\n<p>I took that code from: </p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/#Using_a_Custom_Walker_Function\" rel=\"nofollow\">Using a Custom Walker Function</a></li>\n</ul>\n\n<p>Also here is a tutorial about making the walker class if needed:</p>\n\n<ul>\n<li><a href=\"http://www.kriesi.at/archives/improve-your-wordpress-navigation-menu-output\" rel=\"nofollow\">Improve your WordPress Navigation Menu Output</a></li>\n</ul>\n"
},
{
"answer_id": 255416,
"author": "pagol",
"author_id": 16755,
"author_profile": "https://wordpress.stackexchange.com/users/16755",
"pm_score": 3,
"selected": true,
"text": "<p>I found one small and nice solution.</p>\n\n<pre><code>add_filter( 'nav_menu_link_attributes', 'cfw_add_data_atts_to_nav', 10, 4 );\nfunction cfw_add_data_atts_to_nav( $atts, $item, $args )\n{\n $atts['data-hover'] = $item->title;\n return $atts;\n}\n</code></pre>\n\n<p>I tested it and it works.</p>\n"
}
] |
2016/05/22
|
[
"https://wordpress.stackexchange.com/questions/227435",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83015/"
] |
I'm wondering if it is at all possible to set display a page template chosen by the user within the context of a `query_posts` using `get_template_part`. In other words, I have set up a page template to pull all of it's child pages and display them, but I need each child page to display according to the page template that is chosen in the page editor. Is there any way to make that happen? Here is the code I have for the parent page template so far.
```
<?php
$this_page=get_query_var('page_id');
query_posts( array('post_type'=>'page', 'posts_per_page' => -1, 'post_parent' => $this_page, 'orderby' => 'menu_order', 'order' => 'ASC') );
if(have_posts()): while(have_posts()): the_post();
?>
<?php get_template_part('_wp_page_template'); ?>
<?php endwhile; endif; ?>
```
So, as you can see, I've got the query pulling all of the child pages. I'd like to know how I can make each of these child pages display according to their chosen page template.
Thanks.
|
I found one small and nice solution.
```
add_filter( 'nav_menu_link_attributes', 'cfw_add_data_atts_to_nav', 10, 4 );
function cfw_add_data_atts_to_nav( $atts, $item, $args )
{
$atts['data-hover'] = $item->title;
return $atts;
}
```
I tested it and it works.
|
227,444 |
<p>I have added a new field (time_last_seen) in my plugin (v1.1) table then uploaded my plugin as version 1.2 to wordpress svn repository.
When I update my plugin from admin panel, it is not creating the field (time_last_seen) in the table.</p>
<p>Here is what I have tried:</p>
<pre><code>function ulh_add_user_logins_table() {
global $wpdb;
$oldVersion = get_option( 'fa_userloginhostory_version', '1.0' );
$newVersion = '1.2';
$charset_collate = $wpdb->get_charset_collate();
$fa_user_logins_table = $wpdb->prefix . "fa_user_logins";
$sql = "CREATE TABLE $fa_user_logins_table (
id int(11) NOT NULL AUTO_INCREMENT,
user_id int(11) ,
`time_login` datetime NOT NULL,
`time_logout` datetime NOT NULL,
`time_last_seen` datetime NOT NULL,
`ip_address` varchar(20) NOT NULL,
`browser` varchar(100) NOT NULL,
`operating_system` varchar(100) NOT NULL,
`country_name` varchar(100) NOT NULL,
`country_code` varchar(20) NOT NULL ,
PRIMARY KEY (`id`)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
update_option( 'fa_userloginhostory_version', $newVersion );
}
register_activation_hook(__FILE__, 'ulh_add_user_logins_table');
</code></pre>
|
[
{
"answer_id": 227449,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 3,
"selected": true,
"text": "<p><code>register_activation_hook()</code> only attaches a function to run on <em>activation</em> of your plugin, not on updating. See <a href=\"https://codex.wordpress.org/Function_Reference/register_activation_hook\" rel=\"nofollow noreferrer\">the docs</a> for full details, particularly this part:</p>\n\n<blockquote>\n <p>3.1 : This hook is now fired only when the user activates the plugin and not when an automatic plugin update occurs (#14915).</p>\n</blockquote>\n\n<p>Of course, you could force your hook to run by deactivating and re-activating your plugin, but you certainly don't want your users to have to do this :)</p>\n\n<p>A better way would be to manage the 'database version' of your plugin - so perhaps, store the 'current version' number of your plugin in the database. When your plugin runs, check this version number against the real version of your plugin. If it is ever different... <em>that's</em> when you want to add this field to the database.</p>\n\n<p>Of course, for brand new installs of v1.1 of your plugin, you still want to run this as you are currently. You just need to also consider the upgrade path that existing users - such as yourself in this instance - will take.</p>\n\n<p>Further reading which I would definitely recommend for this topic:</p>\n\n<ul>\n<li><a href=\"https://make.wordpress.org/core/2010/10/27/plugin-activation-hooks-no-longer-fire-for-updates/\" rel=\"nofollow noreferrer\">Plugin activation hooks no longer fire for updates</a></li>\n<li><a href=\"https://wordpress.stackexchange.com/questions/144870/wordpress-update-plugin-hook-action-since-3-9\">Wordpress Update Plugin Hook/Action? Since 3.9</a></li>\n<li><a href=\"https://wordpress.stackexchange.com/questions/25910/uninstall-activate-deactivate-a-plugin-typical-features-how-to/\">Uninstall, Activate, Deactivate a plugin: typical features & how-to</a></li>\n</ul>\n"
},
{
"answer_id": 227476,
"author": "Faiyaz Alam",
"author_id": 85769,
"author_profile": "https://wordpress.stackexchange.com/users/85769",
"pm_score": 0,
"selected": false,
"text": "<p>as per the answer given by Tim Malone, I have this working code:</p>\n\n<pre><code> /* Activate Hook Plugin */\n register_activation_hook(__FILE__, 'ulh_add_user_logins_table');\n\n /* call when plugin is activated */\n function ulh_add_user_logins_table() {\n global $wpdb;\n $charset_collate = $wpdb->get_charset_collate();\n $fa_user_logins_table = $wpdb->prefix . \"fa_user_logins\";\n\n $sql = \"CREATE TABLE $fa_user_logins_table (\n id int(11) NOT NULL AUTO_INCREMENT,\n user_id int(11) ,\n `time_login` datetime NOT NULL,\n `time_logout` datetime NOT NULL,\n `ip_address` varchar(20) NOT NULL,\n `browser` varchar(100) NOT NULL,\n `operating_system` varchar(100) NOT NULL,\n `country_name` varchar(100) NOT NULL,\n `country_code` varchar(20) NOT NULL , \n PRIMARY KEY (`id`)\n ) $charset_collate;\";\n\n require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );\n dbDelta( $sql );\n update_option( 'fa_userloginhostory_version', '1.0' );\n ulh_update_tables_when_plugin_updating();\n }\n\n\n //call when plugin is updated. \n//Actually it gets called every time \n//but the sql query execute only when there is plugin version difference\n function ulh_update_tables_when_plugin_updating() {\n global $wpdb;\n $oldVersion = get_option( 'fa_userloginhostory_version', '1.0' );\n $newVersion = '1.2';\n\n if ( !(version_compare( $oldVersion, $newVersion ) < 0) ) {\n return FALSE;\n }\n\n $charset_collate = $wpdb->get_charset_collate();\n $fa_user_logins_table = $wpdb->prefix . \"fa_user_logins\";\n\n $sql = \"CREATE TABLE $fa_user_logins_table (\n id int(11) NOT NULL AUTO_INCREMENT,\n user_id int(11) ,\n `time_login` datetime NOT NULL,\n `time_logout` datetime NOT NULL,\n `time_last_seen` datetime NOT NULL,\n `ip_address` varchar(20) NOT NULL,\n `browser` varchar(100) NOT NULL,\n `operating_system` varchar(100) NOT NULL,\n `country_name` varchar(100) NOT NULL,\n `country_code` varchar(20) NOT NULL , \n PRIMARY KEY (`id`)\n ) $charset_collate;\";\n\n require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );\n dbDelta( $sql );\n update_option( 'fa_userloginhostory_version', $newVersion );\n }\n\n add_action('init', 'ulh_update_tables_when_plugin_updating');\n</code></pre>\n\n<p>Hope this helps to other user.</p>\n"
}
] |
2016/05/22
|
[
"https://wordpress.stackexchange.com/questions/227444",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85769/"
] |
I have added a new field (time\_last\_seen) in my plugin (v1.1) table then uploaded my plugin as version 1.2 to wordpress svn repository.
When I update my plugin from admin panel, it is not creating the field (time\_last\_seen) in the table.
Here is what I have tried:
```
function ulh_add_user_logins_table() {
global $wpdb;
$oldVersion = get_option( 'fa_userloginhostory_version', '1.0' );
$newVersion = '1.2';
$charset_collate = $wpdb->get_charset_collate();
$fa_user_logins_table = $wpdb->prefix . "fa_user_logins";
$sql = "CREATE TABLE $fa_user_logins_table (
id int(11) NOT NULL AUTO_INCREMENT,
user_id int(11) ,
`time_login` datetime NOT NULL,
`time_logout` datetime NOT NULL,
`time_last_seen` datetime NOT NULL,
`ip_address` varchar(20) NOT NULL,
`browser` varchar(100) NOT NULL,
`operating_system` varchar(100) NOT NULL,
`country_name` varchar(100) NOT NULL,
`country_code` varchar(20) NOT NULL ,
PRIMARY KEY (`id`)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
update_option( 'fa_userloginhostory_version', $newVersion );
}
register_activation_hook(__FILE__, 'ulh_add_user_logins_table');
```
|
`register_activation_hook()` only attaches a function to run on *activation* of your plugin, not on updating. See [the docs](https://codex.wordpress.org/Function_Reference/register_activation_hook) for full details, particularly this part:
>
> 3.1 : This hook is now fired only when the user activates the plugin and not when an automatic plugin update occurs (#14915).
>
>
>
Of course, you could force your hook to run by deactivating and re-activating your plugin, but you certainly don't want your users to have to do this :)
A better way would be to manage the 'database version' of your plugin - so perhaps, store the 'current version' number of your plugin in the database. When your plugin runs, check this version number against the real version of your plugin. If it is ever different... *that's* when you want to add this field to the database.
Of course, for brand new installs of v1.1 of your plugin, you still want to run this as you are currently. You just need to also consider the upgrade path that existing users - such as yourself in this instance - will take.
Further reading which I would definitely recommend for this topic:
* [Plugin activation hooks no longer fire for updates](https://make.wordpress.org/core/2010/10/27/plugin-activation-hooks-no-longer-fire-for-updates/)
* [Wordpress Update Plugin Hook/Action? Since 3.9](https://wordpress.stackexchange.com/questions/144870/wordpress-update-plugin-hook-action-since-3-9)
* [Uninstall, Activate, Deactivate a plugin: typical features & how-to](https://wordpress.stackexchange.com/questions/25910/uninstall-activate-deactivate-a-plugin-typical-features-how-to/)
|
227,464 |
<p>Since Wordpress <a href="https://codex.wordpress.org/Sticky_Posts" rel="nofollow">sticky posts</a> feature allow the post checked as <em>sticky</em> in post publish panel to be placed at the top of the front page of posts. I was also intended to style the sticky post differently than normal ones within the loop by customizing <a href="https://codex.wordpress.org/The_Loop" rel="nofollow">The Loop</a> default coding as following:</p>
<pre><code> <?php if (have_posts()) : ?>
<?php $post = $posts[0]; $c=0;?>
<?php while (have_posts()) : the_post(); $do_not_duplicate = $post->ID; ?>
<?php $c++;
if( is_home() && !$paged && $c == 1) :?>
<?php get_template_part( 'includes/sticky-post', 'page' ); ?>
<?php else :?>
<?php get_template_part( 'includes/loop-post', 'page' ); ?>
<?php endif;?>
<?php endwhile; ?>
<?php endif; ?>
</code></pre>
<p>Where template parts <code>includes/sticky-post</code> and <code>includes/loop-post</code> have post content layout for sticky and normal ones respectively, I still having sticky post twice. Once at the top as required with assigned layout and the other at its normal order of publish date within normal posts which I seeking help to get rid of this issue of duplication.</p>
<p>Any help is much appreciated.</p>
|
[
{
"answer_id": 227466,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>You'll have to move the part that says <code>$do_not_duplicate = $post->ID;</code> to the conditional statement that leads to the first <code>get_template_part()</code>. Now you have stored the ID of that sticky post.</p>\n\n<pre><code>if( is_home() && !$paged && $c == 1) {\n $do_not_duplicate = $post->ID;\n get_template_part( 'includes/sticky-post', 'page' ); \n }\n</code></pre>\n\n<p>Next, in the else part you have to add another condition to make sure you do nothing if the sticky post appears again (which you know if the ID of the current post is the same as the value you stored earlier):</p>\n\n<pre><code>if ($do_not_duplicate != $post->ID) get_template_part( 'includes/loop-post', 'page' );\n</code></pre>\n"
},
{
"answer_id": 227471,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>You simply need the <a href=\"https://developer.wordpress.org/reference/functions/is_sticky/\" rel=\"nofollow\"><code>is_sticky()</code></a> conditional check and then act on that. You would probably still need the <code>is_home()</code> and <code>!is_paged()</code> conditional check to only target stikies on the first page of the home page</p>\n\n<pre><code>if ( have_posts() ) :\n while ( have_posts() ) :\n the_post();\n\n if ( is_sticky()\n && is_home()\n && !is_paged()\n ) {\n // Do what you need to do for stickies\n } elseif ( !is_sticky() ) {\n // Do something else for non-stickies \n }\n endwhile;\nendif;\n</code></pre>\n"
}
] |
2016/05/22
|
[
"https://wordpress.stackexchange.com/questions/227464",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
Since Wordpress [sticky posts](https://codex.wordpress.org/Sticky_Posts) feature allow the post checked as *sticky* in post publish panel to be placed at the top of the front page of posts. I was also intended to style the sticky post differently than normal ones within the loop by customizing [The Loop](https://codex.wordpress.org/The_Loop) default coding as following:
```
<?php if (have_posts()) : ?>
<?php $post = $posts[0]; $c=0;?>
<?php while (have_posts()) : the_post(); $do_not_duplicate = $post->ID; ?>
<?php $c++;
if( is_home() && !$paged && $c == 1) :?>
<?php get_template_part( 'includes/sticky-post', 'page' ); ?>
<?php else :?>
<?php get_template_part( 'includes/loop-post', 'page' ); ?>
<?php endif;?>
<?php endwhile; ?>
<?php endif; ?>
```
Where template parts `includes/sticky-post` and `includes/loop-post` have post content layout for sticky and normal ones respectively, I still having sticky post twice. Once at the top as required with assigned layout and the other at its normal order of publish date within normal posts which I seeking help to get rid of this issue of duplication.
Any help is much appreciated.
|
You simply need the [`is_sticky()`](https://developer.wordpress.org/reference/functions/is_sticky/) conditional check and then act on that. You would probably still need the `is_home()` and `!is_paged()` conditional check to only target stikies on the first page of the home page
```
if ( have_posts() ) :
while ( have_posts() ) :
the_post();
if ( is_sticky()
&& is_home()
&& !is_paged()
) {
// Do what you need to do for stickies
} elseif ( !is_sticky() ) {
// Do something else for non-stickies
}
endwhile;
endif;
```
|
227,482 |
<p>In a lot of how to create a custom meta box tutorials, when saving data, i.e., update_post_meta the data is escaped:</p>
<pre><code>update_post_meta( $post_id, 'city', esc_attr( ucwords( $_POST['city'] ) ) );
</code></pre>
<p>Some tutorials do not esc when saving and do it on screen output.</p>
<p>However, escaping protects the output to the screen, i.e., echo:</p>
<pre><code>echo esc_attr( $city );
</code></pre>
<p>So does it matter if you esc before you output to the screen or before it's saved?</p>
<p>If you esc on save does the order of esc-ing, sanitizing and validating matter?</p>
<p>Do you esc then sanitize and validate or sanitize, esc and sanitize . . . etc.?</p>
|
[
{
"answer_id": 227483,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 3,
"selected": true,
"text": "<p>Yes it does. Escaping depends on context and in worst case like using <code>esc_html</code> when writing directly to the DB are just a security hole.</p>\n\n<p>Even if there is no security issue, there is theoretical one. The user asked you to store A, and you are storing B. In a simple cases B is exactly how A should be displayed in the HTML, but life is rarely simple and while at one point you want to display A in an input for which you want to do <code>esc_attr</code> and at another in a textarea for which you will want to use <code>esc_html</code>. If you already transformed A into B in the DB, it is a PITA to reconstruct for B what was the original A to apply the correct escape function on it.</p>\n\n<p>Rule of thumb: In the DB you should store the raw values the user submitted (probably sanitized, but not escaped), escaping should be done only on output.</p>\n"
},
{
"answer_id": 227496,
"author": "Daniel Mulder",
"author_id": 86859,
"author_profile": "https://wordpress.stackexchange.com/users/86859",
"pm_score": 2,
"selected": false,
"text": "<p>Input from the user or other functions etc you validate and sanitize. For sanitizing sql strings before execution (important one!) look at this page <a href=\"http://codex.wordpress.org/Data_Validation\" rel=\"nofollow\">http://codex.wordpress.org/Data_Validation</a> under Database. When you want to sanitize input from a not trusted source then sanitize look under text input or use <a href=\"http://codex.wordpress.org/Function_Reference/sanitize_text_field\" rel=\"nofollow\">http://codex.wordpress.org/Function_Reference/sanitize_text_field</a> which is also on the first page under text nodes. Now you can more safely use sql strings crafted dynamically in your scripts and store them safely in a database. The thing about esc_html is only for the browser and to display symbols like & which also can be seen as code and displayed incorrectly, nothing more. </p>\n\n<p>If you want to be sure that you always use the same data then json_encode it UNICODE, convert it to a base64 string and than store it or send it. </p>\n"
}
] |
2016/05/22
|
[
"https://wordpress.stackexchange.com/questions/227482",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16641/"
] |
In a lot of how to create a custom meta box tutorials, when saving data, i.e., update\_post\_meta the data is escaped:
```
update_post_meta( $post_id, 'city', esc_attr( ucwords( $_POST['city'] ) ) );
```
Some tutorials do not esc when saving and do it on screen output.
However, escaping protects the output to the screen, i.e., echo:
```
echo esc_attr( $city );
```
So does it matter if you esc before you output to the screen or before it's saved?
If you esc on save does the order of esc-ing, sanitizing and validating matter?
Do you esc then sanitize and validate or sanitize, esc and sanitize . . . etc.?
|
Yes it does. Escaping depends on context and in worst case like using `esc_html` when writing directly to the DB are just a security hole.
Even if there is no security issue, there is theoretical one. The user asked you to store A, and you are storing B. In a simple cases B is exactly how A should be displayed in the HTML, but life is rarely simple and while at one point you want to display A in an input for which you want to do `esc_attr` and at another in a textarea for which you will want to use `esc_html`. If you already transformed A into B in the DB, it is a PITA to reconstruct for B what was the original A to apply the correct escape function on it.
Rule of thumb: In the DB you should store the raw values the user submitted (probably sanitized, but not escaped), escaping should be done only on output.
|
227,506 |
<p>I am trying to create a REST APIs for my wordpress website which is used for facility listing using wordpress job manager plugin. </p>
<p>I have registered my custom post , taxonomies in \plugins\rest-api\plugin.php.</p>
<p>below API gives me all the listings with default response. </p>
<p><a href="http://localhost/sports/wp-json/wp/v2/joblisting/" rel="noreferrer">http://localhost/sports/wp-json/wp/v2/joblisting/</a></p>
<p>I wanted to add post meta in the JSON response using the below code.</p>
<pre><code>function slug_register_phone_number() {
register_rest_field( 'job_listing',
'phone',
array(
'get_callback' => 'slug_get_phone_number',
'update_callback' => null,
'schema' => null,
)
);
}
function slug_get_phone_number($post, $field_name, $request) {
return get_post_meta($post->id, '_phone' );
}
}
</code></pre>
<p>Using above code i am able to add "phone" as a REST response but i am always getting phone = false in response. It is not showing the correct data from wp_postmeta table. </p>
<p>I have followed below mentioned links for reference. </p>
<p><a href="http://v2.wp-api.org/extending/modifying/" rel="noreferrer">http://v2.wp-api.org/extending/modifying/</a></p>
<p>Plug in details.
1. WP Job manager
2. rest-api</p>
<p>Any help will be really helpful.</p>
|
[
{
"answer_id": 227515,
"author": "wpclevel",
"author_id": 92212,
"author_profile": "https://wordpress.stackexchange.com/users/92212",
"pm_score": 4,
"selected": true,
"text": "<p><code>$post</code> in the <a href=\"http://v2.wp-api.org/extending/modifying/#examples\" rel=\"noreferrer\">callback function</a> is an array, not an object. So you cannot use <code>$post->id</code>. Change it to <code>$post['id']</code> and it should work:</p>\n\n\n\n<pre><code>function slug_get_phone_number($post, $field_name, $request)\n{\n return get_post_meta($post['id'], '_phone', true);\n}\n</code></pre>\n\n<p>I recommend to change <code>_phone</code> to <code>phone_number</code> or something else without underscore prefix. Because <code>_</code> is often used with private meta keys. Try to add a custom field which has meta key with <code>_</code> prefix directly to your post, you will see what I meant.</p>\n"
},
{
"answer_id": 227517,
"author": "Boris Kuzmanov",
"author_id": 68965,
"author_profile": "https://wordpress.stackexchange.com/users/68965",
"pm_score": 4,
"selected": false,
"text": "<p>WP API has a <code>rest_prepare_post</code> filter (or <code>rest_prepare_CPT</code> if you are working with custom posts) which you can use to modify the JSON response.\nIn your case it will be <code>rest_prepare_joblisting</code>.</p>\n\n<pre><code>function filter_joblisting_json( $data, $post, $context ) {\n$phone = get_post_meta( $post->ID, '_phone', true );\n\nif( $phone ) {\n $data->data['phone'] = $phone;\n}\n\nreturn $data;\n}\nadd_filter( 'rest_prepare_joblisting', 'filter_joblisting_json', 10, 3 );\n</code></pre>\n\n<p>Using the same filter you can also remove fields/data from the response and do any manipulation of the data.</p>\n"
},
{
"answer_id": 285819,
"author": "Nuwan",
"author_id": 131454,
"author_profile": "https://wordpress.stackexchange.com/users/131454",
"pm_score": 2,
"selected": false,
"text": "<p>Just Add this methods to function.php</p>\n\n<pre><code>add_action( 'rest_api_init', 'create_api_posts_meta_field' );\n\nfunction create_api_posts_meta_field() {\n\n // register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )\n register_rest_field( 'tour', 'metaval', array(\n 'get_callback' => 'get_post_meta_for_api',\n 'schema' => null,\n )\n );\n}\n\nfunction get_post_meta_for_api( $object ) {\n //get the id of the post object array\n $post_id = $object['id'];\n\n //return the post meta\n return get_post_meta( $post_id );\n}\n</code></pre>\n"
},
{
"answer_id": 353860,
"author": "John Dee",
"author_id": 131224,
"author_profile": "https://wordpress.stackexchange.com/users/131224",
"pm_score": 0,
"selected": false,
"text": "<p>Here is an OOP example:</p>\n\n<pre><code>class MetaDataFetcher{\n\n public function enableAPIroute(){\n add_action ('rest_api_init', array($this, 'doRegisterRoutes'));\n }\n\n public function doRegisterRoutes(){\n register_rest_route(\n 'yournamespace/vXX',\n 'fetch-post-meta',\n array(\n 'methods' => array('GET','POST'),\n 'callback' => array($this, 'returnMetaData'),\n\n //You should have a better auth, or this endpoint will be exposed\n permission_callback' => function(){return TRUE;}\n );\n }\n\n public function returnMetaData(){\n if (!(isset($_REQUEST['post-id']))){\n return \"ERROR: No post ID\";\n }\n $postID = $_REQUEST['post-id'];\n $meta = get_post_meta($postID);\n $meta = json_encode($meta);\n return $meta;\n }\n}\n\n$MetaDetaFetcher = New MetaDataFetcher;\n$MetaDetaFetcher->enableAPIroute();\n</code></pre>\n"
},
{
"answer_id": 367843,
"author": "Lyle Bennett",
"author_id": 155008,
"author_profile": "https://wordpress.stackexchange.com/users/155008",
"pm_score": 0,
"selected": false,
"text": "<p>I tested and used what seems to be an easier way to me,\nafter you register the custom post type you can also register the custom meta and make it available in the rest API.</p>\n\n<p>See <a href=\"https://developer.wordpress.org/reference/functions/register_meta/\" rel=\"nofollow noreferrer\">register_meta()</a></p>\n\n<pre><code>register_post_type( 'job_listing', $args ); // in $args you can make the post type available in rest api\nregister_meta(\n 'post', '_phone', [\n 'object_subtype' => 'job_listing',\n 'show_in_rest' => true\n ]\n );\n</code></pre>\n"
}
] |
2016/05/23
|
[
"https://wordpress.stackexchange.com/questions/227506",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94106/"
] |
I am trying to create a REST APIs for my wordpress website which is used for facility listing using wordpress job manager plugin.
I have registered my custom post , taxonomies in \plugins\rest-api\plugin.php.
below API gives me all the listings with default response.
<http://localhost/sports/wp-json/wp/v2/joblisting/>
I wanted to add post meta in the JSON response using the below code.
```
function slug_register_phone_number() {
register_rest_field( 'job_listing',
'phone',
array(
'get_callback' => 'slug_get_phone_number',
'update_callback' => null,
'schema' => null,
)
);
}
function slug_get_phone_number($post, $field_name, $request) {
return get_post_meta($post->id, '_phone' );
}
}
```
Using above code i am able to add "phone" as a REST response but i am always getting phone = false in response. It is not showing the correct data from wp\_postmeta table.
I have followed below mentioned links for reference.
<http://v2.wp-api.org/extending/modifying/>
Plug in details.
1. WP Job manager
2. rest-api
Any help will be really helpful.
|
`$post` in the [callback function](http://v2.wp-api.org/extending/modifying/#examples) is an array, not an object. So you cannot use `$post->id`. Change it to `$post['id']` and it should work:
```
function slug_get_phone_number($post, $field_name, $request)
{
return get_post_meta($post['id'], '_phone', true);
}
```
I recommend to change `_phone` to `phone_number` or something else without underscore prefix. Because `_` is often used with private meta keys. Try to add a custom field which has meta key with `_` prefix directly to your post, you will see what I meant.
|
227,532 |
<p>I got stuck with some modifications and maybe someone could give me some help. </p>
<p><strong>What am I doing</strong></p>
<p>I use the multiple theme plugin to switch themes for my WordPress project. To switch between the themes a URL Parameter is added <strong><code>www.mydomain/?parameter=XYZ</code></strong>. So far everything works great. </p>
<p><strong>Where is the issue</strong></p>
<p>The problem is when I click on internal links within the page I am sent back to the basic theme as the links and URLS within the website do not have the URL parameter appended.</p>
<p>Please note that I am aware that the plugin has a sticky function that adds the parameter to most URLs but it does not work for all URLS and especially not those which are loaded with AJAX. Also I still need to be able to access the basic theme via the normal URL without parameters.</p>
<p><strong>What I am trying to do</strong></p>
<p>Within the <code>functions.php</code> of the specific theme I try to add a function that adds the needed parameter to all URLs that WordPress is generating.</p>
<p>Based on <a href="https://developer.wordpress.org/reference/functions/add_query_arg/" rel="nofollow noreferrer">this info</a>:<br>
I am in the position to at least echo the right URL</p>
<pre><code>//Add partner parameter
echo add_query_arg( 'partner', 'XYZ', get_permalink());
</code></pre>
<p>Unfortunately I have no clue how I may turn that into a function that all URLS within the loaded webpage get the parameter appended? Does anyone have an idea?</p>
<p><strong>What I already checked</strong></p>
<p><a href="https://wordpress.stackexchange.com/questions/188749/i-am-looking-to-append-url-parameter-to-all-urls">I am Looking to append URL Parameter to all URLs</a></p>
<p>As it is a redirection and not a rewrite of the URL I can't then access the normal URL without the parameter anymore.</p>
|
[
{
"answer_id": 227561,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 1,
"selected": false,
"text": "<p>You can set the <code>$_GET</code> global internally. By saving the parameter passed as user meta and/or a cookie and retrieving it later. This would probably have to be put in your <code>/wp-content/mu-plugins/</code> folder to work properly (so it is loaded early):</p>\n\n<pre><code><?php \n\n $parameter = 'theme'; // default for theme test drive\n $savemethod = 'both'; // 'usermeta' (only), 'cookie' (only) or 'both'\n $expires = 7*24*60*60; // cookie length (a week in seconds)\n\n if (!function_exists('is_user_logged_in')) {require(ABSPATH.WPINC.'/pluggable.php');}\n if (is_user_logged_in()) {global $current_user; wp_get_current_user();}\n\n if (isset($_GET[$parameter])) {\n // sanitize querystring input (like a theme slug)\n $originalvalue = $_GET[$parameter];\n $value = sanitize_title($_GET[$originalvalue]);\n if (!$value) {$value = '';}\n\n // save parameter as usermeta\n if ( ($savemethod != 'cookie') && (is_user_logged_in()) ) {\n if ($value == '') {delete_user_meta($current_user->ID,$parameter);}\n else {update_user_meta($current_user->ID,$parameter,$value);}\n } \n // save parameter value as cookie\n if ($savemethod != 'usermeta') {\n if ($value == '') {setCookie($parameter,'',-300);}\n else {setCookie($parameter,$value,time()+$expires);}\n }\n }\n elseif ( ($savemethod != 'cookie') && (is_user_logged_in()) ) {\n // maybe set parameter from usermeta\n $uservalue = get_user_meta($current_user->ID,$parameter,true);\n if ($uservalue != '') {$_GET[$parameter] = $uservalue;}\n }\n elseif ($savemethod != 'usermeta') {\n // maybe set parameter from cookie\n if ( (isset($_COOKIE[$parameter])) && ($_COOKIE[$parameter] != '') ) {\n $_GET[$parameter] = $_COOKIE[$parameter];\n }\n }\n\n // parameter override debugging\n if ( (isset($_GET[$parameter.'debug'])) && ($_GET[$parameter.'debug'] == '1') ) {\n $debugfile = get_stylesheet_directory().'/'.$parameter.'-debug.txt';\n $fh = fopen($debugfile,'a'); \n $debugline = $_SERVER['REQUEST_URI'].'::original:'.$originalvalue;\n $debugline .= '::cookie:'.$_COOKIE[$parameter'].'::usermeta.'.$uservalue;\n $debugline .= '::current:'.$_GET[$parameter].PHP_EOL;\n fwrite ($debugfile,$debugline); fclose($fh);\n }\n\n?>\n</code></pre>\n\n<p>Usage: This could be used for making Theme Test Drive persistent on a per-user level, currently it only works on a user-role level and/or via non-persistent querystring. However, Theme Test Drive does not allow for site area selection - either the whole theme is switched for the user everywhere or nowhere.</p>\n"
},
{
"answer_id": 227789,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 0,
"selected": false,
"text": "<p>Okay this is one insanely long answer, but fortunately I was working on testing Theme Test Drive plugin with my theme I figured I may as well make it better compatible with Multiple Themes also by having the admin issue fixed...</p>\n\n<p>So here is the code I came up with that handles both. Again, put it in your <code>/wp-content/mu-plugins/</code> folder (though it probably be fine as a plugin too.) I am putting it in my theme to support Child Theme switching anyway, but it needs to load earlier than that to support Parent Theme switching. </p>\n\n<p>I will add some other notes later, for the now it is worth mentioning that you want to <strong>not</strong> use the \"sticky\" option of Multiple Themes as this will cause conflicts - because if you have two themes on the same site open in different windows the persistant cookie will override the matching admin calls, and this is exactly why I have coded this solution - to overcome that problem. </p>\n\n<p>Basically it let's Multiple Themes do the work of determining which stylesheet/template to use as it normally would, and stores a list of URLs with different theme to the default when they are loaded, then matches to these using the referrer string of the admin AJAX request (both admin-ajax.php and admin-post.php supported.)</p>\n\n<p>As for Theme Test Drive I found that it already loads in admin if you have the persistent theme drive enabled, fine. But for the querystring test drive I have used an entirely different approach with matching cookies and transients.</p>\n\n<p>Anyway, that's enough of that, read the code comments for more (if you dare.) Otherwise, I have tested it rather thoroughly already so you can just give it a go... :-)</p>\n\n<pre><code>add_action('init','muscle_theme_switch_admin_fix');\n\nif (!function_exists('muscle_theme_switch_admin_fix')) {\n function muscle_theme_switch_admin_fix() {\n\n $multiplethemes = false; $themetestdrive = false; $debug = false;\n $expires = 24*60*60; // transient time for temporary theme test drive (querystring)\n\n // maybe reset cookie and URL data by user request\n if ( (isset($_GET['resetthemes'])) && ($_GET['resetthemes'] == '1') ) {\n if ($debug) {echo \"<!-- THEME SWITCH DATA RESET -->\";}\n if ($themetestdrive) {setCookie('theme_test_drive','',-300);}\n delete_option('theme_switch_request_urls'); return;\n }\n\n // maybe set debug switch\n if ( (isset($_GET['debug'])) && ($_GET['debug'] == '1') ) {$debug = true;}\n elseif (defined('THEMEDEBUG')) {$debug = THEMEDEBUG;}\n\n // check for a valid active plugin\n $activeplugins = maybe_unserialize(get_option('active_plugins'));\n if (!is_array($activeplugins)) {return;}\n if (in_array('jonradio-multiple-themes/jonradio-multiple-themes.php',$activeplugins)) {$multiplethemes = true;}\n if (in_array('theme-test-drive/themedrive.php',$activeplugins)) {$themetestdrive = true;}\n if ( (!$multiplethemes) && (!$themetestdrive) ) {return;} // nothing to do\n\n // theme test drive by default only filters via get_stylesheet and get_template\n // improve theme test drive to use options filters like multiple themes instead\n if ($themetestdrive) {\n remove_filter('template', 'themedrive_get_template'); remove_filter('stylesheet', 'themedrive_get_stylesheet');\n add_filter('pre_option_stylesheet', 'themedrive_get_stylesheet'); add_filter('pre_option_template', 'themedrive_get_template');\n }\n\n // maybe load stored alternative theme for AJAX/admin calls\n if (is_admin()) {\n\n // get pagenow to check for admin-post.php as well\n global $pagenow;\n\n if ( ( (defined('DOING_AJAX')) && (DOING_AJAX) ) || ($pagenow == 'admin-post.php') ) {\n\n // set the referer path for URL matching\n $referer = parse_url($_SERVER['HTTP_REFERER'],PHP_URL_PATH);\n\n // set some globals for the AJAX theme options\n global $ajax_stylesheet, $ajax_template;\n\n // check for temporary Theme Test Drive cookie data\n if ( ($themetestdrive) && (isset($_COOKIE['theme_test_drive'])) && ($_COOKIE['theme_test_drive'] != '') ) {\n $i = 0; $cookiedata = explode(',',$_COOKIE['theme_test_drive']);\n // attempt to match referer data with stored transient request\n foreach ($cookiedata as $transientkey) {\n $transientdata = get_transient($transientkey);\n if ($transientdata) {\n $data = explode(':',$transientdata);\n if ($data[0] == $referer) {\n $ajax_stylesheet = $data[1]; $ajax_template = $data[2];\n $transientdebug = $transientdata; $matchedurlpath = true;\n }\n }\n $i++;\n }\n }\n elseif ($multiplethemes) {\n // check the request URL list to handle all other cases\n $requesturls = get_option('theme_switch_request_urls');\n if (!is_array($requesturls)) {return;}\n\n if ( (is_array($requesturls)) && (array_key_exists($referer,$requesturls)) ) {\n $matchedurlpath = true;\n $ajax_stylesheet = $requesturls[$referer]['stylesheet'];\n $ajax_template = $requesturls[$referer]['template'];\n }\n }\n\n if ($matchedurlpath) {\n // add new theme option filters for admin AJAX (and admin post)\n // so any admin actions defined by the theme are finally loaded!\n add_filter('pre_option_stylesheet','admin_ajax_stylesheet');\n add_filter('pre_option_template','admin_ajax_template');\n\n function admin_ajax_stylesheet() {global $ajax_stylesheet; return $ajax_stylesheet;}\n function admin_ajax_template() {global $ajax_template; return $ajax_template;}\n }\n\n // maybe output debug info for AJAX/admin test frame\n if ($debug) {\n echo \"<!-- COOKIE DATA: \".$_COOKIE['theme_test_drive'].\" -->\";\n echo \"<!-- TRANSIENT DATA: \".$transientdebug.\" -->\";\n echo \"<!-- REFERER: \".$referer.\" -->\";\n echo \"<!-- STORED URLS: \"; print_r($requesturls); echo \" -->\";\n if ($matchedurlpath) {echo \"<!-- URL MATCH FOUND -->\";} else {echo \"<!-- NO URL MATCH FOUND -->\";}\n echo \"<!-- AJAX Stylesheet: \".get_option('stylesheet').\" -->\";\n echo \"<!-- AJAX Template: \".get_option('template').\" -->\";\n }\n\n return; // we are done so bug out here\n }\n }\n\n // store public request URLs where an alternate theme is active\n // (multiple themes does not load in admin, but theme test drive does)\n if ( ($themetestdrive) || ( (!is_admin()) && ($multiplethemes) ) ) {\n\n // get current theme (possibly overriden) setting\n $themestylesheet = get_option('stylesheet'); $themetemplate = get_option('template');\n\n // remove filters, get default theme setting, re-add filters\n if ($multiplethemes) {\n remove_filter('pre_option_stylesheet', 'jr_mt_stylesheet'); remove_filter('pre_option_template', 'jr_mt_template');\n $stylesheet = get_option('stylesheet'); $template = get_option('template');\n add_filter('pre_option_stylesheet', 'jr_mt_stylesheet'); add_filter('pre_option_template', 'jr_mt_template');\n }\n if ($themetestdrive) {\n // note: default theme test drive filters are changed earlier on\n remove_filter('pre_option_stylesheet', 'themedrive_get_stylesheet'); remove_filter('pre_option_template', 'themedrive_get_template');\n $stylesheet = get_stylesheet(); $template = get_template();\n add_filter('pre_option_stylesheet', 'themedrive_get_stylesheet'); add_filter('pre_option_template', 'themedrive_get_template');\n }\n\n // set/get request URL values (URL path only)\n $requesturl = parse_url($_SERVER['REQUEST_URI'],PHP_URL_PATH);\n $requesturls = get_option('theme_switch_request_urls');\n\n // check for a temporary Theme Test Drive (querystring)\n if ( ($themetestdrive) && (isset($_REQUEST['theme'])) && ($_REQUEST['theme'] != '') ) {\n // add a transient style user page cookie for matching later\n $cookiedata = array();\n if ( (isset($_COOKIE['theme_test_drive'])) && ($_COOKIE['theme_test_drive'] != '') ) {\n $existingmatch = false;\n $i = 0; $cookiedata = explode(',',$_COOKIE['theme_test_drive']);\n // remove transient IDs for expired transients\n foreach ($cookiedata as $transientkey) {\n $transientdata = get_transient($transientkey);\n if ($transientdata) {\n $data = explode(':',$transientdata);\n if ($data[0] == $requesturl) {\n // update the existing transient data\n $transientdata = $transientdebug = $requesturl.':'.$themestylesheet.':'.$themetemplate;\n set_transient($transientkey,$transientdata,$expires);\n $existingmatch = true; // no duplicates\n }\n } else {unset($cookiedata[$i]);}\n $i++;\n }\n }\n // set the matching transient and cookie data\n if (!$existingmatch) {\n $transientkey = 'theme_test_drive_session_'.uniqid();\n $transientdata = $transientdebug = $requesturl.':'.$themestylesheet.':'.$themetemplate;\n set_transient($transientkey, $transientdata, $expires);\n $cookiedata[] = $transientkey; $cookiedatastring = implode(',',$cookiedata);\n setCookie('theme_test_drive', $cookiedatastring, time()+$expires);\n }\n // maybe output debug info\n if ($debug) {\n echo \"<!-- COOKIE DATA: \"; print_r($cookiedata); echo \" -->\";\n echo \"<!-- TRANSIENT DATA: \".$transientdebug.\" -->\";\n }\n }\n elseif ($multiplesthemes) {\n // save/remove the requested URL path in the list\n if ( ($stylesheet == $themestylesheet) && ($template == $themetemplate) ) {\n // maybe remove this request from the stored URL list\n if ( (is_array($requesturls)) && (array_key_exists($requesturl,$requesturls)) ) {\n unset($requesturls[$requesturl]);\n if (count($requesturls) === 0) {delete_option('theme_switch_request_urls');}\n else {update_option('theme_switch_request_urls',$requesturls);}\n }\n }\n else {\n // add this request URL to the stored list\n $requesturls[$requesturl]['stylesheet'] = $themestylesheet;\n $requesturls[$requesturl]['template'] = $themetemplate;\n update_option('theme_switch_request_urls',$requesturls);\n }\n // maybe output debug info\n if ( (!is_admin()) && ($debug) ) {\n echo \"<!-- REQUEST URL: \".$requesturl.\" -->\";\n echo \"<!-- STORED URLS: \"; print_r($requesturls); echo \" -->\";\n }\n }\n\n // maybe output hidden ajax debugging frames\n if ( (!is_admin()) && ($debug) ) {\n echo \"<iframe src='\".admin_url('admin-ajax.php').\"?debug=1' style='display:none;'></iframe>\";\n echo \"<iframe src='\".admin_url('admin-post.php').\"?debug=1' style='display:none;'></iframe>\";\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 227970,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 0,
"selected": false,
"text": "<p>For your particular use case (as far as I understand it now) you just want to use the sticky queries if the access source is different, thus running on a user level not a site level (eg. such as all posts and/or pages option)... </p>\n\n<p>Since Multiple Themes is actually fine to run \"as is\" in admin from the sticky query via cookie (it just doesn't do that by default because that would conflict for it's sitewide options)... you can just force it to load for AJAX calls by including <code>select-theme.php</code>...</p>\n\n<p>But since it would be still be good to not have them affect any AJAX calls from the home page where the default theme is used, you can add a list of those paths manually to filter them out (via adding to <code>$defaultthemepaths</code>) This is much easier, but just does not <em>automatically</em> mesh with Multiple Theme's sitewide options, you need to add the default theme URLs manually in this code...</p>\n\n<pre><code>add_action('plugins_loaded','switched_theme_admin_fix');\nfunction switched_theme_admin_fix() {\n\n if (!is_admin()) {return;} // switch-themes.php already loads for non-admin\n\n // default theme URL paths (add to this list?)\n $defaultthemepaths = array('','/'); // 'home' paths\n\n // get pagenow to check for admin-post.php as well\n global $pagenow;\n\n if ( ( (defined('DOING_AJAX')) && (DOING_AJAX) ) || ($pagenow == 'admin-post.php') ) {\n\n // set the referer path for URL matching\n $referer = parse_url($_SERVER['HTTP_REFERER'],PHP_URL_PATH);\n\n // do not switch themes if called from a default theme URL path\n if (!in_array($referer,$defaultthemepaths)) {\n\n // full path to select-theme.php\n $selecttheme = WP_PLUGIN_DIR.'/jonradio-multiple-themes';\n $selecttheme .= '/includes/select-theme.php';\n\n // just in case multiple themes does update to load for admin\n $included = get_included_files();\n if (!in_array($selecttheme,$included)) {\n // adds the multiple themes stylesheet filters\n if (file_exists($selecttheme) {include($selecttheme);}\n } \n }\n }\n }\n</code></pre>\n"
}
] |
2016/05/23
|
[
"https://wordpress.stackexchange.com/questions/227532",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94531/"
] |
I got stuck with some modifications and maybe someone could give me some help.
**What am I doing**
I use the multiple theme plugin to switch themes for my WordPress project. To switch between the themes a URL Parameter is added **`www.mydomain/?parameter=XYZ`**. So far everything works great.
**Where is the issue**
The problem is when I click on internal links within the page I am sent back to the basic theme as the links and URLS within the website do not have the URL parameter appended.
Please note that I am aware that the plugin has a sticky function that adds the parameter to most URLs but it does not work for all URLS and especially not those which are loaded with AJAX. Also I still need to be able to access the basic theme via the normal URL without parameters.
**What I am trying to do**
Within the `functions.php` of the specific theme I try to add a function that adds the needed parameter to all URLs that WordPress is generating.
Based on [this info](https://developer.wordpress.org/reference/functions/add_query_arg/):
I am in the position to at least echo the right URL
```
//Add partner parameter
echo add_query_arg( 'partner', 'XYZ', get_permalink());
```
Unfortunately I have no clue how I may turn that into a function that all URLS within the loaded webpage get the parameter appended? Does anyone have an idea?
**What I already checked**
[I am Looking to append URL Parameter to all URLs](https://wordpress.stackexchange.com/questions/188749/i-am-looking-to-append-url-parameter-to-all-urls)
As it is a redirection and not a rewrite of the URL I can't then access the normal URL without the parameter anymore.
|
You can set the `$_GET` global internally. By saving the parameter passed as user meta and/or a cookie and retrieving it later. This would probably have to be put in your `/wp-content/mu-plugins/` folder to work properly (so it is loaded early):
```
<?php
$parameter = 'theme'; // default for theme test drive
$savemethod = 'both'; // 'usermeta' (only), 'cookie' (only) or 'both'
$expires = 7*24*60*60; // cookie length (a week in seconds)
if (!function_exists('is_user_logged_in')) {require(ABSPATH.WPINC.'/pluggable.php');}
if (is_user_logged_in()) {global $current_user; wp_get_current_user();}
if (isset($_GET[$parameter])) {
// sanitize querystring input (like a theme slug)
$originalvalue = $_GET[$parameter];
$value = sanitize_title($_GET[$originalvalue]);
if (!$value) {$value = '';}
// save parameter as usermeta
if ( ($savemethod != 'cookie') && (is_user_logged_in()) ) {
if ($value == '') {delete_user_meta($current_user->ID,$parameter);}
else {update_user_meta($current_user->ID,$parameter,$value);}
}
// save parameter value as cookie
if ($savemethod != 'usermeta') {
if ($value == '') {setCookie($parameter,'',-300);}
else {setCookie($parameter,$value,time()+$expires);}
}
}
elseif ( ($savemethod != 'cookie') && (is_user_logged_in()) ) {
// maybe set parameter from usermeta
$uservalue = get_user_meta($current_user->ID,$parameter,true);
if ($uservalue != '') {$_GET[$parameter] = $uservalue;}
}
elseif ($savemethod != 'usermeta') {
// maybe set parameter from cookie
if ( (isset($_COOKIE[$parameter])) && ($_COOKIE[$parameter] != '') ) {
$_GET[$parameter] = $_COOKIE[$parameter];
}
}
// parameter override debugging
if ( (isset($_GET[$parameter.'debug'])) && ($_GET[$parameter.'debug'] == '1') ) {
$debugfile = get_stylesheet_directory().'/'.$parameter.'-debug.txt';
$fh = fopen($debugfile,'a');
$debugline = $_SERVER['REQUEST_URI'].'::original:'.$originalvalue;
$debugline .= '::cookie:'.$_COOKIE[$parameter'].'::usermeta.'.$uservalue;
$debugline .= '::current:'.$_GET[$parameter].PHP_EOL;
fwrite ($debugfile,$debugline); fclose($fh);
}
?>
```
Usage: This could be used for making Theme Test Drive persistent on a per-user level, currently it only works on a user-role level and/or via non-persistent querystring. However, Theme Test Drive does not allow for site area selection - either the whole theme is switched for the user everywhere or nowhere.
|
227,542 |
<p>I am using the following code to show next/previous posts in my wordpress theme.</p>
<pre><code><?php
previous_post_link('<span class="left">&larr; %link</span>');
next_post_link('<span class="right">%link &rarr;</span>'); ?>
</code></pre>
<p>It's working but I want to limit the post title which is displayed in the link to a specific length because too big links don't work because of the space I have.
And I want to have the arrow within the link so that it shows link and arrow with the same style. Is that possible aswell?</p>
<p>Thank you!</p>
|
[
{
"answer_id": 227565,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>Both of these should trickle down to <code>get_adjacent_post_link()</code> function, which passes result through dynamic <a href=\"https://developer.wordpress.org/reference/hooks/adjacent_post_link/\" rel=\"nofollow\"><code>{$adjacent}_post_link</code></a> filter (where <code>$adjacent</code> is <code>previous</code> or <code>next</code>).</p>\n\n<p>You should be able to use this filter to make any changes to final output.</p>\n"
},
{
"answer_id": 227566,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 4,
"selected": true,
"text": "<p>Here's a little coding that should implement this for you:</p>\n\n<pre><code><?php $max_length = 5; // set max character length here\n\n$next = get_next_post()->ID;\n$prev = get_previous_post()->ID;\n\nif( $prev ) {\n $title = get_the_title( $prev );\n $link = get_the_permalink( $prev );\n $post_name = mb_strlen( $title ) > $max_length ? mb_substr( $title, 0, $max_length ) . ' ..' : $title;\n ?>\n <span class=\"left\">\n <a href=\"<?php echo $link; ?>\" rel=\"prev\" title=\"<?php echo $title; ?>\">&larr; <?php echo $post_name; ?></a>\n </span>\n <?php\n}\nif( $next ) {\n $title = get_the_title( $next );\n $link = get_the_permalink( $next );\n $post_name = mb_strlen( $title ) > $max_length ? mb_substr( $title, 0, $max_length ) . ' ..' : $title;\n ?>\n <span class=\"right\">\n <a href=\"<?php echo $link; ?>\" rel=\"next\" title=\"<?php echo $title; ?>\"><?php echo $post_name; ?> &rarr;</a>\n </span>\n <?php\n} ?>\n</code></pre>\n\n<p>Hope that helps in your template.</p>\n\n<p>Edit: small fix so this could work with multibyte characters. (mb_strlen - mb_substr)</p>\n"
},
{
"answer_id": 227574,
"author": "Antony Gibbs",
"author_id": 93359,
"author_profile": "https://wordpress.stackexchange.com/users/93359",
"pm_score": 2,
"selected": false,
"text": "<p>This can be done just using simple css based on max-width and text-overflow properties.</p>\n<pre class=\"lang-html prettyprint-override\"><code><style>\n /**\n * note that your theme might not use class nav_posts\n * so you might have to adjust to your need\n */\n\n .nav_posts .title {\n /**\n * This is what is minimum required for the magic\n * First it has to be a block... inline blocks are cool and simple to use,\n * but if your theme used blocks (includes flex) don't upset him and take that line out\n */\n display: inline-block;\n\n text-overflow: ellipsis;\n\n /* Required for text-overflow to do anything */\n overflow: hidden;\n white-space: nowrap; /* forces text to fit on one line */\n\n max-width: 30ex; /* Fit to your needs... */\n\n /* Then what ever you need to fit in your theme */\n vertical-align: bottom;\n }\n</style>\n\n<!--\n// Check out your theme (could be in single.php)\n// the below php is only to illustrate the case.\n// Make your life simple, don't edit the theme or any php, adjust the css\n// adding it using wordpress custom css, nothing more, as simple as that :)\n-->\n\n<?php\n\nprevious_post_link('<span class="nav_posts left">&larr; <span class="title">%link</span></span>');\n\nnext_post_link('<span class="nav_posts right"><span class="title">%link</span> &rarr;</span>');\n\n?>\n</code></pre>\n"
}
] |
2016/05/23
|
[
"https://wordpress.stackexchange.com/questions/227542",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94072/"
] |
I am using the following code to show next/previous posts in my wordpress theme.
```
<?php
previous_post_link('<span class="left">← %link</span>');
next_post_link('<span class="right">%link →</span>'); ?>
```
It's working but I want to limit the post title which is displayed in the link to a specific length because too big links don't work because of the space I have.
And I want to have the arrow within the link so that it shows link and arrow with the same style. Is that possible aswell?
Thank you!
|
Here's a little coding that should implement this for you:
```
<?php $max_length = 5; // set max character length here
$next = get_next_post()->ID;
$prev = get_previous_post()->ID;
if( $prev ) {
$title = get_the_title( $prev );
$link = get_the_permalink( $prev );
$post_name = mb_strlen( $title ) > $max_length ? mb_substr( $title, 0, $max_length ) . ' ..' : $title;
?>
<span class="left">
<a href="<?php echo $link; ?>" rel="prev" title="<?php echo $title; ?>">← <?php echo $post_name; ?></a>
</span>
<?php
}
if( $next ) {
$title = get_the_title( $next );
$link = get_the_permalink( $next );
$post_name = mb_strlen( $title ) > $max_length ? mb_substr( $title, 0, $max_length ) . ' ..' : $title;
?>
<span class="right">
<a href="<?php echo $link; ?>" rel="next" title="<?php echo $title; ?>"><?php echo $post_name; ?> →</a>
</span>
<?php
} ?>
```
Hope that helps in your template.
Edit: small fix so this could work with multibyte characters. (mb\_strlen - mb\_substr)
|
227,545 |
<p>This one should be easy, but I can't figure it out.
I want to send an email that is HTML formatted, but also has an attachment. The attachment is being sent correctly, but the message is delivered as plaintext, like this: </p>
<pre><code><p>Hello!</p>
<p>&nbsp;</p>
<p>Some text.</p>
<p>&nbsp;</p>
<p>Best wishes,</p>
<p>Team</p>
</code></pre>
<p>If it was an email without attachment, I would force it to send html by changing the header as described <a href="https://developer.wordpress.org/reference/functions/wp_mail/" rel="nofollow">here</a>. But now I need the content type to be multipart / mixed (right?). So my question is: how do I convince <code>wp_mail()</code> to send my messages as html, and include the attachment? </p>
|
[
{
"answer_id": 227552,
"author": "flero",
"author_id": 13970,
"author_profile": "https://wordpress.stackexchange.com/users/13970",
"pm_score": 0,
"selected": false,
"text": "<p>as stated in the <a href=\"https://developer.wordpress.org/reference/functions/wp_mail/\" rel=\"nofollow\">link you posted</a>:</p>\n\n<blockquote>\n <p>The default content type is ‘text/plain’ which does not allow using HTML. However, you can set the content type of the email by using the 'wp_mail_content_type’ filter.</p>\n</blockquote>\n\n<p>Adding this to functions.php, as stated in <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_mail_content_type\" rel=\"nofollow\">wp_mail_content_type</a>:</p>\n\n<pre><code>add_filter( 'wp_mail_content_type', 'set_content_type' );\nfunction set_content_type( $content_type ) {\n return 'text/html';\n}\n</code></pre>\n\n<p>Should do the trick.</p>\n"
},
{
"answer_id": 227572,
"author": "Naveen Kumar",
"author_id": 94546,
"author_profile": "https://wordpress.stackexchange.com/users/94546",
"pm_score": 2,
"selected": false,
"text": "<p>Reference link <a href=\"https://developer.wordpress.org/reference/functions/wp_mail/\" rel=\"nofollow\">click here</a>.</p>\n\n<p>Using below code you can send the mail with html format.</p>\n\n<pre><code>$to = '[email protected]';\n$subject = 'The subject';\n$body = 'The email body content';\n$headers = array('Content-Type: text/html; charset=UTF-8');\n\nwp_mail( $to, $subject, $body, $headers );\n\n// For attachment \n\n$attachments = array( WP_CONTENT_DIR . '/uploads/file_to_attach.zip' );\n$headers = 'From: My Name <[email protected]>' . \"\\r\\n\";\n\nwp_mail( '[email protected]', 'subject', 'message', $headers, $attachments );\n</code></pre>\n"
},
{
"answer_id": 227695,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 2,
"selected": false,
"text": "<p>I believe the answer in your particular case does not involve the bug that is mentioned in the linked thread. There is no need to set <em>custom headers</em> to achieve what you state you want to do. </p>\n\n<p>Instead you simply set the alternative body as text using <code>$phpmailer->AltBody</code>. This automatically sets the to content type <code>multipart/alternative</code> (not multipart/mixed) and you allow the <code>phpmailer</code> class to take care of the rest <em>without</em> needing to set custom headers manually.</p>\n\n<pre><code>add_action('phpmailer_init','wp_mail_set_text_body');\nfunction wp_mail_set_text_body($phpmailer) {\n $phpmailer->AltBody = strip_tags($phpmailer->Body);\n}\n\n$to = '[email protected]';\n$headers = array();\n$attachments = array(dirname(__FILE__).'/test.txt');\nwp_mail($to,$subject,$message,$headers,$attachments);\n</code></pre>\n\n<p>If you add attachments, the overall content type will automatically become <code>multipart/mixed</code> with <code>multipart/alternative</code> inside of that wchi contains <code>text/plain</code> and <code>text/html</code> parts, then followed by the attachments.</p>\n\n<p>You can also add <code>multipart/related</code> (inline) attachments such as images by passing them to <code>wp_mail</code> via <code>$attachements</code> (with the 5th parameter as 'inline') - or even declaring them within the HTML body itself. These will not be accessible to the text version as far as I know.</p>\n"
}
] |
2016/05/23
|
[
"https://wordpress.stackexchange.com/questions/227545",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/41165/"
] |
This one should be easy, but I can't figure it out.
I want to send an email that is HTML formatted, but also has an attachment. The attachment is being sent correctly, but the message is delivered as plaintext, like this:
```
<p>Hello!</p>
<p> </p>
<p>Some text.</p>
<p> </p>
<p>Best wishes,</p>
<p>Team</p>
```
If it was an email without attachment, I would force it to send html by changing the header as described [here](https://developer.wordpress.org/reference/functions/wp_mail/). But now I need the content type to be multipart / mixed (right?). So my question is: how do I convince `wp_mail()` to send my messages as html, and include the attachment?
|
Reference link [click here](https://developer.wordpress.org/reference/functions/wp_mail/).
Using below code you can send the mail with html format.
```
$to = '[email protected]';
$subject = 'The subject';
$body = 'The email body content';
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail( $to, $subject, $body, $headers );
// For attachment
$attachments = array( WP_CONTENT_DIR . '/uploads/file_to_attach.zip' );
$headers = 'From: My Name <[email protected]>' . "\r\n";
wp_mail( '[email protected]', 'subject', 'message', $headers, $attachments );
```
|
227,591 |
<p>I have a Custom Post Type like</p>
<pre><code>function cpt_Projects() {
$labels = array(
'name' => 'Projects',
'singular_name' => 'Project',
'menu_name' => 'Projects',
'name_admin_bar' => 'Projects',
'parent_item_colon' => 'Parent Projects:',
'all_items' => 'All Projects',
'view_item' => 'View Project',
'add_new_item' => 'Add New Project',
'add_new' => 'Add New Project',
'new_item' => 'New Projects',
'edit_item' => 'Edit Project Item',
'update_item' => 'Update Project Item',
'search_items' => 'Search Project Item',
'not_found' => 'Project Not found',
'not_found_in_trash' => 'Project Not found in Trash',
);
$args = array(
'label' => 'ProjectsCPT',
'description' => 'This Post Type Adds Eyeglasses to Website',
'labels' => $labels,
'supports' => array( 'title', 'thumbnail', 'editor'),
'taxonomies' => array( 'ProjectsTax' ),
'register_meta_box_cb' => 'add_details_metabox',
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 5,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'post',
);
register_post_type( 'ProjectsCPT', $args );
}
add_action( 'init', 'cpt_Projects', 0 );
</code></pre>
<p>and a Metabox like</p>
<pre><code> function add_details_metabox($post_type) {
$types = array('post', 'page', 'ProjectsCPT');
if (in_array($post_type, $types)) {
add_meta_box(
'details-metabox',
'Project Details',
'detail_meta_callback',
$post_type,
'normal',
'high'
);
}
}
</code></pre>
<p>after running the code the Metabox is showing on all <code>Page</code>s and <code>Post</code>s but not on Custom Post Type <code>ProjectsCPT</code> Can you please let me know what I am doing wrong? (It works fine if I remove the if statement </p>
<pre><code> if (in_array($post_type, $types)) {}
</code></pre>
<p>but this add metabox to all Posts and Pages which is not what I need to do</p>
|
[
{
"answer_id": 227606,
"author": "vancoder",
"author_id": 26778,
"author_profile": "https://wordpress.stackexchange.com/users/26778",
"pm_score": 2,
"selected": false,
"text": "<p>Post type names cannot contain capital letters. So behind the scenes, your CPT is probably called projectscpt rather than ProjectsCPT - hence it not matching the value in your array.</p>\n"
},
{
"answer_id": 227607,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 0,
"selected": false,
"text": "<p>NOTE the difference between <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes\" rel=\"nofollow\"><code>add_meta_boxes</code></a> and <code>register_meta_box_cb</code>.</p>\n\n<p>When you register the meta boxes using <code>add_meta_boxes</code>, here is how WordPress calls <code>do_action()</code></p>\n\n<pre><code>/**\n * Fires after all built-in meta boxes have been added.\n *\n * @since 3.0.0\n *\n * @param string $post_type Post type.\n * @param WP_Post $post Post object.\n */\ndo_action( 'add_meta_boxes', $post_type, $post );\n</code></pre>\n\n<p>The first argument is post type and the second one is post object.</p>\n\n<p>And when callback is registered using <code>register_meta_box_cb</code> then in <code>register_post_type()</code> function WordPress add an action.</p>\n\n<pre><code>if ( $args->register_meta_box_cb )\n add_action( 'add_meta_boxes_' . $post_type, $args->register_meta_box_cb, 10, 1 );\n</code></pre>\n\n<p>Then </p>\n\n<pre><code>/**\n * Fires after all built-in meta boxes have been added, contextually for the given post type.\n *\n * The dynamic portion of the hook, `$post_type`, refers to the post type of the post.\n *\n * @since 3.0.0\n *\n * @param WP_Post $post Post object.\n */\ndo_action( 'add_meta_boxes_' . $post_type, $post );\n</code></pre>\n\n<p>So the first and only argument is <code>$post</code> the post object and you are using it as post type.</p>\n\n<p>You have to get the post type before comparing.</p>\n\n<p>Example:-</p>\n\n<pre><code>function add_details_metabox($post) {\n $types = array('post', 'page', 'projectscpt');\n $post_type = get_post_type($post);\n\n if (in_array($post_type, $types)) {\n add_meta_box(\n 'details-metabox',\n 'Project Details',\n 'detail_meta_callback',\n $post_type,\n 'normal',\n 'high'\n );\n }\n}\n</code></pre>\n\n<p><strong>NOTE #1</strong> As @vancoder answered, no matter what case you pass in post type. It is converted to lowercase. What WordPress recommends to register post type without spaces and capital letters. You must use <code>projectscpt</code> instead of capital letters.</p>\n\n<p><strong>NOTE #2</strong> When using <code>register_meta_box_cb</code> it hook the callback function on <code>add_meta_boxes_{post_type}</code> action. This meta box will not appear on any other post type. Therefore, you do not need to check the post type in callback function. If you are getting meta box on other post types too then check the code, perhaps you made some mistake.</p>\n"
},
{
"answer_id": 290995,
"author": "Prince Ahmed",
"author_id": 127311,
"author_profile": "https://wordpress.stackexchange.com/users/127311",
"pm_score": 0,
"selected": false,
"text": "<p>Make sure you add your custom post type in the add_meta_box function arguments for $screen.</p>\n\n<p>add_meta_box( string $id, string $title, callable $callback, <strong><code>string|array|WP_Screen $screen = null,</code></strong> string $context = 'advanced', string $priority = 'default', array $callback_args = null )</p>\n\n<p><strong>Example:</strong> </p>\n\n<pre><code>add_meta_box( \n 'my_id', My Title, 'my_callback_function', '**my_post_type**', 'normal', 'default' \n);\n</code></pre>\n"
}
] |
2016/05/23
|
[
"https://wordpress.stackexchange.com/questions/227591",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31793/"
] |
I have a Custom Post Type like
```
function cpt_Projects() {
$labels = array(
'name' => 'Projects',
'singular_name' => 'Project',
'menu_name' => 'Projects',
'name_admin_bar' => 'Projects',
'parent_item_colon' => 'Parent Projects:',
'all_items' => 'All Projects',
'view_item' => 'View Project',
'add_new_item' => 'Add New Project',
'add_new' => 'Add New Project',
'new_item' => 'New Projects',
'edit_item' => 'Edit Project Item',
'update_item' => 'Update Project Item',
'search_items' => 'Search Project Item',
'not_found' => 'Project Not found',
'not_found_in_trash' => 'Project Not found in Trash',
);
$args = array(
'label' => 'ProjectsCPT',
'description' => 'This Post Type Adds Eyeglasses to Website',
'labels' => $labels,
'supports' => array( 'title', 'thumbnail', 'editor'),
'taxonomies' => array( 'ProjectsTax' ),
'register_meta_box_cb' => 'add_details_metabox',
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 5,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'post',
);
register_post_type( 'ProjectsCPT', $args );
}
add_action( 'init', 'cpt_Projects', 0 );
```
and a Metabox like
```
function add_details_metabox($post_type) {
$types = array('post', 'page', 'ProjectsCPT');
if (in_array($post_type, $types)) {
add_meta_box(
'details-metabox',
'Project Details',
'detail_meta_callback',
$post_type,
'normal',
'high'
);
}
}
```
after running the code the Metabox is showing on all `Page`s and `Post`s but not on Custom Post Type `ProjectsCPT` Can you please let me know what I am doing wrong? (It works fine if I remove the if statement
```
if (in_array($post_type, $types)) {}
```
but this add metabox to all Posts and Pages which is not what I need to do
|
Post type names cannot contain capital letters. So behind the scenes, your CPT is probably called projectscpt rather than ProjectsCPT - hence it not matching the value in your array.
|
227,593 |
<p>I have installed Visual Composer for a client and am now trying to remove the tab from the Dashboard menu. How can I do this?</p>
<p><a href="https://i.stack.imgur.com/FN3by.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/FN3by.jpg" alt="Remove Visual Composer tab from Dashboard menu"></a></p>
<pre><code>function remove_menus(){
remove_menu_page( ‘js_composer.php’ );
}
add_action( ‘admin_menu’, ‘remove_menus’ );
</code></pre>
<p>The code used above isn't working for me. It seems the path "js_composer.php" is not correct.</p>
|
[
{
"answer_id": 227601,
"author": "cpcdev",
"author_id": 93195,
"author_profile": "https://wordpress.stackexchange.com/users/93195",
"pm_score": 1,
"selected": false,
"text": "<p>I solved this by installing the <a href=\"https://wordpress.org/plugins/admin-menu-editor/\" rel=\"nofollow\">Admin Menu Editor</a> plugin which gave me the ability to manually remove the Visual Composer dashboard tab. Good plugin!</p>\n"
},
{
"answer_id": 228234,
"author": "marvinpoo",
"author_id": 94786,
"author_profile": "https://wordpress.stackexchange.com/users/94786",
"pm_score": 4,
"selected": true,
"text": "<p>It is not easy to find it out, but it is pretty easy if you know how.</p>\n<p>Add this following code to your themes <code>functions.php</code>.</p>\n<pre><code>function custom_menu_page_removing() {\n remove_menu_page('vc-welcome'); //vc\n}\nadd_action( 'admin_init', 'custom_menu_page_removing' );\n</code></pre>\n<p>(Previously been <code>admin_menu</code>, now is <code>admin_init</code>)</p>\n<p>This is how to find out for the next time:</p>\n<p>If you want to hide a link from any plugin in the admin backend, simply use everything behind the <code>?page=</code> in this example case it's <code>vc-welcome</code></p>\n<p>No need for an additional plugin to remove/hide the link.</p>\n"
},
{
"answer_id": 242792,
"author": "user2511140",
"author_id": 51752,
"author_profile": "https://wordpress.stackexchange.com/users/51752",
"pm_score": 2,
"selected": false,
"text": "<p>I use version 4.12.1 and this code works for me. Hide from user menu but not for admin menu.</p>\n\n<pre><code>function custom_menu_page_removing() {\n remove_menu_page('vc-welcome'); //vc\n}\nadd_action( 'admin_menu', 'custom_menu_page_removing' );\n</code></pre>\n"
},
{
"answer_id": 260653,
"author": "Isolin",
"author_id": 115768,
"author_profile": "https://wordpress.stackexchange.com/users/115768",
"pm_score": 2,
"selected": false,
"text": "<p>The previous answers did not work for me. I realized that I had to change the hook to <strong>admin_init</strong>.</p>\n\n<pre><code>function custom_menu_page_removing() {\n remove_menu_page('vc-welcome');\n}\nadd_action( 'admin_init', 'custom_menu_page_removing' );\n</code></pre>\n"
},
{
"answer_id": 278665,
"author": "Arsalan Chishti",
"author_id": 126912,
"author_profile": "https://wordpress.stackexchange.com/users/126912",
"pm_score": 0,
"selected": false,
"text": "<p>This code worked out for me on the latest Wordpress</p>\n\n<pre><code>function custom_menu_page_removing() {\n remove_menu_page('vc-welcome');\n}\nadd_action( 'admin_init', 'custom_menu_page_removing' );\n</code></pre>\n"
}
] |
2016/05/23
|
[
"https://wordpress.stackexchange.com/questions/227593",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93195/"
] |
I have installed Visual Composer for a client and am now trying to remove the tab from the Dashboard menu. How can I do this?
[](https://i.stack.imgur.com/FN3by.jpg)
```
function remove_menus(){
remove_menu_page( ‘js_composer.php’ );
}
add_action( ‘admin_menu’, ‘remove_menus’ );
```
The code used above isn't working for me. It seems the path "js\_composer.php" is not correct.
|
It is not easy to find it out, but it is pretty easy if you know how.
Add this following code to your themes `functions.php`.
```
function custom_menu_page_removing() {
remove_menu_page('vc-welcome'); //vc
}
add_action( 'admin_init', 'custom_menu_page_removing' );
```
(Previously been `admin_menu`, now is `admin_init`)
This is how to find out for the next time:
If you want to hide a link from any plugin in the admin backend, simply use everything behind the `?page=` in this example case it's `vc-welcome`
No need for an additional plugin to remove/hide the link.
|
227,604 |
<p>I'm running a VPS with <code>Ubuntu 14.04.4 x64</code> and Apache <code>2.4.7</code>, and would like to set-up a WordPress site on it. Which apache-modules <em>must</em> I have enabled - and which <em>should</em> I enable (eg. for cool WP-features)? Are there any modules I absolutely should <em>not</em> enable?</p>
|
[
{
"answer_id": 227605,
"author": "Nefro",
"author_id": 86801,
"author_profile": "https://wordpress.stackexchange.com/users/86801",
"pm_score": 4,
"selected": true,
"text": "<p>Here is the list of minimum Apache modules which is required to run WordPress websites.</p>\n\n<pre><code>mod_alias\nmod_authz_host\nmod_deflate\nmod_dir\nmod_expires\nmod_headers\nmod_mime\nmod_rewrite\nmod_log_config\nmod_autoindex\nmod_negotiation\nmod_setenvif\n</code></pre>\n"
},
{
"answer_id": 238838,
"author": "Michael",
"author_id": 102569,
"author_profile": "https://wordpress.stackexchange.com/users/102569",
"pm_score": 1,
"selected": false,
"text": "<p>Of the list above, these are definitely not required (although they could be useful).</p>\n\n<p>mod_deflate\nmod_expires\nmod_mime </p>\n\n<p>Others might also be able to be omitted, depending on what you're doing and what you want to give up. </p>\n"
},
{
"answer_id": 398846,
"author": "thowden",
"author_id": 163402,
"author_profile": "https://wordpress.stackexchange.com/users/163402",
"pm_score": 0,
"selected": false,
"text": "<p>The question asked is older but still relevant and this thread still comes up today in search results. Researching for my own understanding, I hope the following info updates & helps.</p>\n<p>Referencing CloudLinux 8.4 & 7.8 with Cpanel v100.x servers and EasyApache4.</p>\n<p>Checked Apache loaded modules with #apachectl -M and compared the enabled modules with the list and presented options in EA4.</p>\n<p>To update the module list:\n:not offered in EA4 - appear to be installed / enabled by default in apachectl\nmod_alias; mod_authz_host; mod_dir.</p>\n<p>:offered in EA4 and were already enabled on the two reference servers.\nmod_expires; mod_headers; mod_mime; mod_rewrite; mod_log_config; mod_autoindex;\nmod_negotiation; mod_setenvif.</p>\n<p>In EA4 these could be useful:\nmod_brotli : <a href=\"https://docs.cpanel.net/ea4/apache/apache-module-brotli/\" rel=\"nofollow noreferrer\">https://docs.cpanel.net/ea4/apache/apache-module-brotli/</a></p>\n<p>mod_cgi /mod_cgid / mod_fcgid : <a href=\"https://docs.cpanel.net/ea4/apache/apache-module-fcgid/\" rel=\"nofollow noreferrer\">https://docs.cpanel.net/ea4/apache/apache-module-fcgid/</a> - lots of caveats with this one - the test servers had mod_cgi eabled on one and mod-cgid on the other - not sure how these were enabled - further review needed</p>\n<p>mod_deflate :: Enable - relates to Optimize Website tool : html / txt file compression to enhance site speed via Apache. Ref <a href=\"https://docs.cpanel.net/cpanel/software/optimize-website/\" rel=\"nofollow noreferrer\">https://docs.cpanel.net/cpanel/software/optimize-website/</a> - Also review Gzip compression options in WHM->Tweak Settings - check vCPU count defaults to 1 - increase to add CPU's (max = total CPU's)</p>\n<p>mod_expires :: Enabled by default - Ref <a href=\"https://support.cpanel.net/hc/en-us/articles/1500008232181-How-to-set-Expires-Headers-for-Your-Site-on-cPanel\" rel=\"nofollow noreferrer\">https://support.cpanel.net/hc/en-us/articles/1500008232181-How-to-set-Expires-Headers-for-Your-Site-on-cPanel</a></p>\n<p>There are more but I'll review another day.</p>\n"
}
] |
2016/05/23
|
[
"https://wordpress.stackexchange.com/questions/227604",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31032/"
] |
I'm running a VPS with `Ubuntu 14.04.4 x64` and Apache `2.4.7`, and would like to set-up a WordPress site on it. Which apache-modules *must* I have enabled - and which *should* I enable (eg. for cool WP-features)? Are there any modules I absolutely should *not* enable?
|
Here is the list of minimum Apache modules which is required to run WordPress websites.
```
mod_alias
mod_authz_host
mod_deflate
mod_dir
mod_expires
mod_headers
mod_mime
mod_rewrite
mod_log_config
mod_autoindex
mod_negotiation
mod_setenvif
```
|
227,608 |
<p>I'm running a VPS with Ubuntu. I've installed the LAMP-stack, and would now like to make a couple of blogs/sites using WordPress. I'm thinking about creating new users for each blog and making a <code>public_html</code> directory for each user. This way each blog could be reached with <code>http://mysite/~some_blog</code>. </p>
<p>Space is however at a bit of a premium, so I was wondering if it's possible to install WordPress only once (eg. under <code>/var/www/html/</code> or perhaps <code>/var/www/wordpress</code>), and let all blogs access WordPress from there? </p>
<p>Of course they'd each also have a "private" directory in the <code>public_html</code> for each user, for individual configurations, uploads, and so on. Each blog/user would have their own MySQL database.</p>
<p>Are there better ways of doing this - one WP installation, multiple blogs - that I'm missing?</p>
<p>Also, is it possible to use only one shared MySQL-database for all blogs? (Not that I intend to do so, just curious...)</p>
|
[
{
"answer_id": 227605,
"author": "Nefro",
"author_id": 86801,
"author_profile": "https://wordpress.stackexchange.com/users/86801",
"pm_score": 4,
"selected": true,
"text": "<p>Here is the list of minimum Apache modules which is required to run WordPress websites.</p>\n\n<pre><code>mod_alias\nmod_authz_host\nmod_deflate\nmod_dir\nmod_expires\nmod_headers\nmod_mime\nmod_rewrite\nmod_log_config\nmod_autoindex\nmod_negotiation\nmod_setenvif\n</code></pre>\n"
},
{
"answer_id": 238838,
"author": "Michael",
"author_id": 102569,
"author_profile": "https://wordpress.stackexchange.com/users/102569",
"pm_score": 1,
"selected": false,
"text": "<p>Of the list above, these are definitely not required (although they could be useful).</p>\n\n<p>mod_deflate\nmod_expires\nmod_mime </p>\n\n<p>Others might also be able to be omitted, depending on what you're doing and what you want to give up. </p>\n"
},
{
"answer_id": 398846,
"author": "thowden",
"author_id": 163402,
"author_profile": "https://wordpress.stackexchange.com/users/163402",
"pm_score": 0,
"selected": false,
"text": "<p>The question asked is older but still relevant and this thread still comes up today in search results. Researching for my own understanding, I hope the following info updates & helps.</p>\n<p>Referencing CloudLinux 8.4 & 7.8 with Cpanel v100.x servers and EasyApache4.</p>\n<p>Checked Apache loaded modules with #apachectl -M and compared the enabled modules with the list and presented options in EA4.</p>\n<p>To update the module list:\n:not offered in EA4 - appear to be installed / enabled by default in apachectl\nmod_alias; mod_authz_host; mod_dir.</p>\n<p>:offered in EA4 and were already enabled on the two reference servers.\nmod_expires; mod_headers; mod_mime; mod_rewrite; mod_log_config; mod_autoindex;\nmod_negotiation; mod_setenvif.</p>\n<p>In EA4 these could be useful:\nmod_brotli : <a href=\"https://docs.cpanel.net/ea4/apache/apache-module-brotli/\" rel=\"nofollow noreferrer\">https://docs.cpanel.net/ea4/apache/apache-module-brotli/</a></p>\n<p>mod_cgi /mod_cgid / mod_fcgid : <a href=\"https://docs.cpanel.net/ea4/apache/apache-module-fcgid/\" rel=\"nofollow noreferrer\">https://docs.cpanel.net/ea4/apache/apache-module-fcgid/</a> - lots of caveats with this one - the test servers had mod_cgi eabled on one and mod-cgid on the other - not sure how these were enabled - further review needed</p>\n<p>mod_deflate :: Enable - relates to Optimize Website tool : html / txt file compression to enhance site speed via Apache. Ref <a href=\"https://docs.cpanel.net/cpanel/software/optimize-website/\" rel=\"nofollow noreferrer\">https://docs.cpanel.net/cpanel/software/optimize-website/</a> - Also review Gzip compression options in WHM->Tweak Settings - check vCPU count defaults to 1 - increase to add CPU's (max = total CPU's)</p>\n<p>mod_expires :: Enabled by default - Ref <a href=\"https://support.cpanel.net/hc/en-us/articles/1500008232181-How-to-set-Expires-Headers-for-Your-Site-on-cPanel\" rel=\"nofollow noreferrer\">https://support.cpanel.net/hc/en-us/articles/1500008232181-How-to-set-Expires-Headers-for-Your-Site-on-cPanel</a></p>\n<p>There are more but I'll review another day.</p>\n"
}
] |
2016/05/23
|
[
"https://wordpress.stackexchange.com/questions/227608",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31032/"
] |
I'm running a VPS with Ubuntu. I've installed the LAMP-stack, and would now like to make a couple of blogs/sites using WordPress. I'm thinking about creating new users for each blog and making a `public_html` directory for each user. This way each blog could be reached with `http://mysite/~some_blog`.
Space is however at a bit of a premium, so I was wondering if it's possible to install WordPress only once (eg. under `/var/www/html/` or perhaps `/var/www/wordpress`), and let all blogs access WordPress from there?
Of course they'd each also have a "private" directory in the `public_html` for each user, for individual configurations, uploads, and so on. Each blog/user would have their own MySQL database.
Are there better ways of doing this - one WP installation, multiple blogs - that I'm missing?
Also, is it possible to use only one shared MySQL-database for all blogs? (Not that I intend to do so, just curious...)
|
Here is the list of minimum Apache modules which is required to run WordPress websites.
```
mod_alias
mod_authz_host
mod_deflate
mod_dir
mod_expires
mod_headers
mod_mime
mod_rewrite
mod_log_config
mod_autoindex
mod_negotiation
mod_setenvif
```
|
227,620 |
<p>Been hitting my head against the wall on this for a while. If I have a add_rewrite_rules like so:</p>
<pre><code> $aNewRules = array('my-books/?$' => 'index.php?pagename=my-books');
</code></pre>
<p>This works correctly; going to <a href="http://example.com/my-books/" rel="nofollow">http://example.com/my-books/</a> shows <a href="http://example.com/index.php?pagename=my-books" rel="nofollow">http://example.com/index.php?pagename=my-books</a>.</p>
<p>However, this is case sensitive - going to "/My-bOoKs/" does not trip the rule (and thus shows the 404 page instead).</p>
<p>Is there an easy way to just mark it as case insensitive? I only make links with the lower case, sure, but users may add a capital on their own and I'd hate to lose the traffic to a 404 page.</p>
<p>Thanks!
Alex</p>
|
[
{
"answer_id": 261357,
"author": "Joshua Ostrom",
"author_id": 116227,
"author_profile": "https://wordpress.stackexchange.com/users/116227",
"pm_score": -1,
"selected": false,
"text": "<p>Not directly. The wordpress API is using preg_match / preg_replace but is not exposing the flags parameter. That's what you'd need to pass the insensitive flag (i).</p>\n\n<p>See their implementation here:\n<a href=\"https://github.com/WordPress/WordPress/blob/a8802232ecac8184cbe6e8dbe9c6a7bd0f5b7dee/wp-includes/class-wp-rewrite.php\" rel=\"nofollow noreferrer\">https://github.com/WordPress/WordPress/blob/a8802232ecac8184cbe6e8dbe9c6a7bd0f5b7dee/wp-includes/class-wp-rewrite.php</a></p>\n\n<p>Probably the simplest solution is just to use a little helper function to do this for you:</p>\n\n<pre><code>function anyCase($rules){\n $insensitive = array();\n foreach ($rules as $regex => $mapping) {\n $regex = preg_replace_callback('([A-Za-z])', function($matches){\n return \"[\" . strtoupper($matches[1]) . strtolower($matches[1]) . \"]\";\n }, $regex);\n $insensitive[$regex] = $mapping;\n }\n return $insensitive;\n }\n</code></pre>\n\n<p>Given</p>\n\n<pre><code>$rules = array('my-books/?$' => 'index.php?pagename=my-books');\nvar_dump(anyCase($rules));\n</code></pre>\n\n<p>Will output\n array(1) { [\"[Mm][Yy]-[Bb][Oo][Oo][Kk][Ss]/?$\"]=> string(27) \"index.php?pagename=my-books\" }</p>\n\n<p>So you can keep your rules clean / simple :-)</p>\n\n<p>If you're running an older PHP that doesn't support closures you can just this instead:</p>\n\n<pre><code> function lowerOrUpper($matches){\n return \"[\" . strtoupper($matches[0]) . strtolower($matches[0]) . \"]\";\n }\n\n function anyCase($rules){\n $insensitive = array();\n foreach ($rules as $regex => $mapping) {\n $regex = preg_replace_callback('([A-Za-z])', lowerOrUpper, $regex);\n $insensitive[$regex] = $mapping;\n }\n return $insensitive;\n }\n</code></pre>\n\n<p>Cheers</p>\n"
},
{
"answer_id": 311069,
"author": "Eric Jorgensen",
"author_id": 32537,
"author_profile": "https://wordpress.stackexchange.com/users/32537",
"pm_score": 1,
"selected": false,
"text": "<p>As the answer below mentions, it is not possible to pass a flag to <code>add_rewrite_rule()</code>; however, it <em>is</em> possible to use an inline modifier. In your example, you would do this:</p>\n\n<p><code>$aNewRules = array('(?i)my-books/?$' => 'index.php?pagename=my-books');</code></p>\n\n<p>(note the <code>(?i)</code> in the regular expression).</p>\n\n<p>The advantage of this approach is that your rewrite rules are much cleaner and more performant.</p>\n\n<p>See <a href=\"https://www.regular-expressions.info/modifiers.html\" rel=\"nofollow noreferrer\">this page</a> on regular expression modifiers for more information.</p>\n"
}
] |
2016/05/23
|
[
"https://wordpress.stackexchange.com/questions/227620",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/11654/"
] |
Been hitting my head against the wall on this for a while. If I have a add\_rewrite\_rules like so:
```
$aNewRules = array('my-books/?$' => 'index.php?pagename=my-books');
```
This works correctly; going to <http://example.com/my-books/> shows <http://example.com/index.php?pagename=my-books>.
However, this is case sensitive - going to "/My-bOoKs/" does not trip the rule (and thus shows the 404 page instead).
Is there an easy way to just mark it as case insensitive? I only make links with the lower case, sure, but users may add a capital on their own and I'd hate to lose the traffic to a 404 page.
Thanks!
Alex
|
As the answer below mentions, it is not possible to pass a flag to `add_rewrite_rule()`; however, it *is* possible to use an inline modifier. In your example, you would do this:
`$aNewRules = array('(?i)my-books/?$' => 'index.php?pagename=my-books');`
(note the `(?i)` in the regular expression).
The advantage of this approach is that your rewrite rules are much cleaner and more performant.
See [this page](https://www.regular-expressions.info/modifiers.html) on regular expression modifiers for more information.
|
227,642 |
<p>I am creating an RSS feed. I have created a table in my database with 400 post id's. I have the rss feed coded I am now trying to link the two so my RSS feed runs only for the list of 400 posts from my table. </p>
<p>On my RSS feed page I can create an array by using a couple of id's (see below)</p>
<pre><code>$myarray2 = array(12345,12346);
$args = array(
'post_type' => 'posttype',
'post__in' => $myarray2
);
</code></pre>
<p>This works and creates an RSS feed for id's 12345,12346. </p>
<p>I can also print the array of my 400 database table records on the page as follows;</p>
<pre><code>$myarray = $wpdb->get_results("SELECT * FROM my_table");
print_r($myarray)
</code></pre>
<p>This produces data of this form</p>
<pre><code>(
[0] => stdClass Object (
[id] => 145
)
[1] => stdClass Object (
[id] => 4573
)
[2] => continues.....
)
</code></pre>
<p>However I can not seem to get the code right to use <code>$myarray</code> with <code>post__in</code> for example</p>
<pre><code>$myarray = $wpdb->get_results("SELECT * FROM my_table");
$args = array(
'post_type' => 'posttype',
'post__in' => $myarray
);
</code></pre>
<p>does not work. I have tried various variations but I am missing something about how to deliver a list of post id's from my array to <code>post__in</code></p>
<p>What am I missing?</p>
|
[
{
"answer_id": 227647,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 1,
"selected": false,
"text": "<p><code>post__in</code> accept array of post IDs e.g. <code>array(5, 4, 8, 9);</code></p>\n\n<p>Extending @bravokeyl comment. By default result is Object. As codex suggest you can change the output type of <a href=\"https://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results\" rel=\"nofollow\"><code>get_results()</code></a> to these values.</p>\n\n<blockquote>\n <ul>\n <li>OBJECT - result will be output as a numerically indexed array of row objects.</li>\n <li>OBJECT_K - result will be output as an associative array of row objects, using first column's values as keys (duplicates will be\n discarded).</li>\n <li>ARRAY_A - result will be output as a numerically indexed array of associative arrays, using column names as keys.</li>\n <li>ARRAY_N - result will be output as a numerically indexed array of numerically indexed arrays.</li>\n </ul>\n</blockquote>\n\n<p>Here we can change output to <code>ARRAY_A</code> then extract post IDs and pass to <code>post__in</code></p>\n\n<pre><code>global $wpdb;\n$fivesdrafts = $wpdb->get_results(\"SELECT ID FROM my_table\", ARRAY_A);\n$post_ids = array_map(function($single_array){\n return $single_array['ID'];\n}, $fivesdrafts);\n\n//Pass this to post__in\narray(\n 'post__in' => $post_ids\n);\n</code></pre>\n"
},
{
"answer_id": 227655,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p>Here's one way by using <code>wpdb::get_col()</code> and fetch the <code>id</code> column:</p>\n\n<pre><code>$pids = $wpdb->get_col( \"SELECT id FROM my_table\" );\n</code></pre>\n\n<p>We could then clean it by integer convert each id with:</p>\n\n<pre><code>$pids = wp_parse_id_list( $pids );\n</code></pre>\n\n<p><a href=\"http://php.net/manual/en/function.intval.php\" rel=\"nofollow\">Just note</a> the different max value for <code>intval()</code>, depending on 32 or 64 bits systems.</p>\n"
},
{
"answer_id": 227685,
"author": "Jolo",
"author_id": 94581,
"author_profile": "https://wordpress.stackexchange.com/users/94581",
"pm_score": -1,
"selected": false,
"text": "<p>OK I got it to work as follows.</p>\n\n<pre><code>global $wpdb;\n$jlk = $wpdb->get_results(\"SELECT * FROM my_table\");\n\nforeach($jlk as $custompost) {\n $custompost_ids[] = $custompost->ID;\n}\n\n$args = array(\n'post_type' => 'custompost',\n'numberposts' => -1,\n'post__in'=> $custompost_ids\n);\n$result = get_posts($args);\n</code></pre>\n"
}
] |
2016/05/24
|
[
"https://wordpress.stackexchange.com/questions/227642",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94581/"
] |
I am creating an RSS feed. I have created a table in my database with 400 post id's. I have the rss feed coded I am now trying to link the two so my RSS feed runs only for the list of 400 posts from my table.
On my RSS feed page I can create an array by using a couple of id's (see below)
```
$myarray2 = array(12345,12346);
$args = array(
'post_type' => 'posttype',
'post__in' => $myarray2
);
```
This works and creates an RSS feed for id's 12345,12346.
I can also print the array of my 400 database table records on the page as follows;
```
$myarray = $wpdb->get_results("SELECT * FROM my_table");
print_r($myarray)
```
This produces data of this form
```
(
[0] => stdClass Object (
[id] => 145
)
[1] => stdClass Object (
[id] => 4573
)
[2] => continues.....
)
```
However I can not seem to get the code right to use `$myarray` with `post__in` for example
```
$myarray = $wpdb->get_results("SELECT * FROM my_table");
$args = array(
'post_type' => 'posttype',
'post__in' => $myarray
);
```
does not work. I have tried various variations but I am missing something about how to deliver a list of post id's from my array to `post__in`
What am I missing?
|
`post__in` accept array of post IDs e.g. `array(5, 4, 8, 9);`
Extending @bravokeyl comment. By default result is Object. As codex suggest you can change the output type of [`get_results()`](https://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results) to these values.
>
> * OBJECT - result will be output as a numerically indexed array of row objects.
> * OBJECT\_K - result will be output as an associative array of row objects, using first column's values as keys (duplicates will be
> discarded).
> * ARRAY\_A - result will be output as a numerically indexed array of associative arrays, using column names as keys.
> * ARRAY\_N - result will be output as a numerically indexed array of numerically indexed arrays.
>
>
>
Here we can change output to `ARRAY_A` then extract post IDs and pass to `post__in`
```
global $wpdb;
$fivesdrafts = $wpdb->get_results("SELECT ID FROM my_table", ARRAY_A);
$post_ids = array_map(function($single_array){
return $single_array['ID'];
}, $fivesdrafts);
//Pass this to post__in
array(
'post__in' => $post_ids
);
```
|
227,660 |
<p>I realize that this question is being asked in a very generic fashion, without detailed specifics of the configuration in question, and thus I am not expecting answers that go beyond anything but <em>general</em> guidance.</p>
<p>With that, given a WordPress site that is:</p>
<ul>
<li><p>based on a typical "heavy" ("kitchen-sink included") theme, purchased via ThemeForest.net, and</p></li>
<li><p>hosted on typical (entry-level, Linux-based) "cheap hosting," priced at under <strong>$10</strong>/month</p></li>
</ul>
<p>... to what degree can one <em>realistically</em> expect that the use of properly-configured caching-plugins (such as W3 Total Cache) and a CDN solution (such as CloudFlare or MaxCDN) can significantly boost the sluggish performance of the current setup?</p>
<p>In other words, if we take as an upper limit the performance that might be achieved hosting that very same website on a "high-end" hosting package (say, WPEngine's "Professional" plan, at <strong>$99</strong>/month, or even their "Business" plan, at <strong>$249</strong>/month):</p>
<ul>
<li><p>Is there any realistic chance of achieving relatively-"zippy" performance <em>despite</em> the underlying "heavy" theme and relatively-weak infrastructure of the cheap hosting?</p></li>
<li><p>Specifically, what ballpark percentage of "high-end" performance might realistically be achieved?</p></li>
<li><p>And what estimated plugin- and CDN-related expenses would be required each month? Also: what ballpark percentage of peak performance might be achieved using only a "free" CDN plan?</p></li>
</ul>
<p>Primarily, I'd like to receive -- if possible -- a "sanity check" that at least a "semi-respectable" level of performance can nevertheless be achieved with cheap hosting in my situation, with the proper tuning and external support (as well as <em>general</em> guidelines on the direction to take).</p>
|
[
{
"answer_id": 227647,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 1,
"selected": false,
"text": "<p><code>post__in</code> accept array of post IDs e.g. <code>array(5, 4, 8, 9);</code></p>\n\n<p>Extending @bravokeyl comment. By default result is Object. As codex suggest you can change the output type of <a href=\"https://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results\" rel=\"nofollow\"><code>get_results()</code></a> to these values.</p>\n\n<blockquote>\n <ul>\n <li>OBJECT - result will be output as a numerically indexed array of row objects.</li>\n <li>OBJECT_K - result will be output as an associative array of row objects, using first column's values as keys (duplicates will be\n discarded).</li>\n <li>ARRAY_A - result will be output as a numerically indexed array of associative arrays, using column names as keys.</li>\n <li>ARRAY_N - result will be output as a numerically indexed array of numerically indexed arrays.</li>\n </ul>\n</blockquote>\n\n<p>Here we can change output to <code>ARRAY_A</code> then extract post IDs and pass to <code>post__in</code></p>\n\n<pre><code>global $wpdb;\n$fivesdrafts = $wpdb->get_results(\"SELECT ID FROM my_table\", ARRAY_A);\n$post_ids = array_map(function($single_array){\n return $single_array['ID'];\n}, $fivesdrafts);\n\n//Pass this to post__in\narray(\n 'post__in' => $post_ids\n);\n</code></pre>\n"
},
{
"answer_id": 227655,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p>Here's one way by using <code>wpdb::get_col()</code> and fetch the <code>id</code> column:</p>\n\n<pre><code>$pids = $wpdb->get_col( \"SELECT id FROM my_table\" );\n</code></pre>\n\n<p>We could then clean it by integer convert each id with:</p>\n\n<pre><code>$pids = wp_parse_id_list( $pids );\n</code></pre>\n\n<p><a href=\"http://php.net/manual/en/function.intval.php\" rel=\"nofollow\">Just note</a> the different max value for <code>intval()</code>, depending on 32 or 64 bits systems.</p>\n"
},
{
"answer_id": 227685,
"author": "Jolo",
"author_id": 94581,
"author_profile": "https://wordpress.stackexchange.com/users/94581",
"pm_score": -1,
"selected": false,
"text": "<p>OK I got it to work as follows.</p>\n\n<pre><code>global $wpdb;\n$jlk = $wpdb->get_results(\"SELECT * FROM my_table\");\n\nforeach($jlk as $custompost) {\n $custompost_ids[] = $custompost->ID;\n}\n\n$args = array(\n'post_type' => 'custompost',\n'numberposts' => -1,\n'post__in'=> $custompost_ids\n);\n$result = get_posts($args);\n</code></pre>\n"
}
] |
2016/05/24
|
[
"https://wordpress.stackexchange.com/questions/227660",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54948/"
] |
I realize that this question is being asked in a very generic fashion, without detailed specifics of the configuration in question, and thus I am not expecting answers that go beyond anything but *general* guidance.
With that, given a WordPress site that is:
* based on a typical "heavy" ("kitchen-sink included") theme, purchased via ThemeForest.net, and
* hosted on typical (entry-level, Linux-based) "cheap hosting," priced at under **$10**/month
... to what degree can one *realistically* expect that the use of properly-configured caching-plugins (such as W3 Total Cache) and a CDN solution (such as CloudFlare or MaxCDN) can significantly boost the sluggish performance of the current setup?
In other words, if we take as an upper limit the performance that might be achieved hosting that very same website on a "high-end" hosting package (say, WPEngine's "Professional" plan, at **$99**/month, or even their "Business" plan, at **$249**/month):
* Is there any realistic chance of achieving relatively-"zippy" performance *despite* the underlying "heavy" theme and relatively-weak infrastructure of the cheap hosting?
* Specifically, what ballpark percentage of "high-end" performance might realistically be achieved?
* And what estimated plugin- and CDN-related expenses would be required each month? Also: what ballpark percentage of peak performance might be achieved using only a "free" CDN plan?
Primarily, I'd like to receive -- if possible -- a "sanity check" that at least a "semi-respectable" level of performance can nevertheless be achieved with cheap hosting in my situation, with the proper tuning and external support (as well as *general* guidelines on the direction to take).
|
`post__in` accept array of post IDs e.g. `array(5, 4, 8, 9);`
Extending @bravokeyl comment. By default result is Object. As codex suggest you can change the output type of [`get_results()`](https://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results) to these values.
>
> * OBJECT - result will be output as a numerically indexed array of row objects.
> * OBJECT\_K - result will be output as an associative array of row objects, using first column's values as keys (duplicates will be
> discarded).
> * ARRAY\_A - result will be output as a numerically indexed array of associative arrays, using column names as keys.
> * ARRAY\_N - result will be output as a numerically indexed array of numerically indexed arrays.
>
>
>
Here we can change output to `ARRAY_A` then extract post IDs and pass to `post__in`
```
global $wpdb;
$fivesdrafts = $wpdb->get_results("SELECT ID FROM my_table", ARRAY_A);
$post_ids = array_map(function($single_array){
return $single_array['ID'];
}, $fivesdrafts);
//Pass this to post__in
array(
'post__in' => $post_ids
);
```
|
227,667 |
<p>I have a custom post type called blogs (blog URL is saved as custom field). There are nearly 250 blog custom post types. When a custom post type (blogs) load I use <code>fetch_feed()</code> to get the recent posts of that blog.</p>
<p>Now my site is on localhost. One of my My friend said I can't host this site on shared hosting because my website use lots of resources. Is it true?</p>
|
[
{
"answer_id": 227647,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 1,
"selected": false,
"text": "<p><code>post__in</code> accept array of post IDs e.g. <code>array(5, 4, 8, 9);</code></p>\n\n<p>Extending @bravokeyl comment. By default result is Object. As codex suggest you can change the output type of <a href=\"https://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results\" rel=\"nofollow\"><code>get_results()</code></a> to these values.</p>\n\n<blockquote>\n <ul>\n <li>OBJECT - result will be output as a numerically indexed array of row objects.</li>\n <li>OBJECT_K - result will be output as an associative array of row objects, using first column's values as keys (duplicates will be\n discarded).</li>\n <li>ARRAY_A - result will be output as a numerically indexed array of associative arrays, using column names as keys.</li>\n <li>ARRAY_N - result will be output as a numerically indexed array of numerically indexed arrays.</li>\n </ul>\n</blockquote>\n\n<p>Here we can change output to <code>ARRAY_A</code> then extract post IDs and pass to <code>post__in</code></p>\n\n<pre><code>global $wpdb;\n$fivesdrafts = $wpdb->get_results(\"SELECT ID FROM my_table\", ARRAY_A);\n$post_ids = array_map(function($single_array){\n return $single_array['ID'];\n}, $fivesdrafts);\n\n//Pass this to post__in\narray(\n 'post__in' => $post_ids\n);\n</code></pre>\n"
},
{
"answer_id": 227655,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p>Here's one way by using <code>wpdb::get_col()</code> and fetch the <code>id</code> column:</p>\n\n<pre><code>$pids = $wpdb->get_col( \"SELECT id FROM my_table\" );\n</code></pre>\n\n<p>We could then clean it by integer convert each id with:</p>\n\n<pre><code>$pids = wp_parse_id_list( $pids );\n</code></pre>\n\n<p><a href=\"http://php.net/manual/en/function.intval.php\" rel=\"nofollow\">Just note</a> the different max value for <code>intval()</code>, depending on 32 or 64 bits systems.</p>\n"
},
{
"answer_id": 227685,
"author": "Jolo",
"author_id": 94581,
"author_profile": "https://wordpress.stackexchange.com/users/94581",
"pm_score": -1,
"selected": false,
"text": "<p>OK I got it to work as follows.</p>\n\n<pre><code>global $wpdb;\n$jlk = $wpdb->get_results(\"SELECT * FROM my_table\");\n\nforeach($jlk as $custompost) {\n $custompost_ids[] = $custompost->ID;\n}\n\n$args = array(\n'post_type' => 'custompost',\n'numberposts' => -1,\n'post__in'=> $custompost_ids\n);\n$result = get_posts($args);\n</code></pre>\n"
}
] |
2016/05/24
|
[
"https://wordpress.stackexchange.com/questions/227667",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94595/"
] |
I have a custom post type called blogs (blog URL is saved as custom field). There are nearly 250 blog custom post types. When a custom post type (blogs) load I use `fetch_feed()` to get the recent posts of that blog.
Now my site is on localhost. One of my My friend said I can't host this site on shared hosting because my website use lots of resources. Is it true?
|
`post__in` accept array of post IDs e.g. `array(5, 4, 8, 9);`
Extending @bravokeyl comment. By default result is Object. As codex suggest you can change the output type of [`get_results()`](https://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results) to these values.
>
> * OBJECT - result will be output as a numerically indexed array of row objects.
> * OBJECT\_K - result will be output as an associative array of row objects, using first column's values as keys (duplicates will be
> discarded).
> * ARRAY\_A - result will be output as a numerically indexed array of associative arrays, using column names as keys.
> * ARRAY\_N - result will be output as a numerically indexed array of numerically indexed arrays.
>
>
>
Here we can change output to `ARRAY_A` then extract post IDs and pass to `post__in`
```
global $wpdb;
$fivesdrafts = $wpdb->get_results("SELECT ID FROM my_table", ARRAY_A);
$post_ids = array_map(function($single_array){
return $single_array['ID'];
}, $fivesdrafts);
//Pass this to post__in
array(
'post__in' => $post_ids
);
```
|
227,707 |
<p>I'm looking for some advice on how to make a gallery of images.
it is a particular bit a gallery, because I would show the last 5 post and a fixed post, for a total of 6 posts, in a specific order. ie the fixed post must be the third in the list.
The only method that I believe it is possible to create 3 loops, the first to see the last two post, the second to display the fixed post (by id), and the third to see other last three posts.
Something like this (most probably it is not correct):</p>
<pre><code> <?php $my_query = new WP_Query( 'posts_per_page=2' ); // get the latest 2 posts
while ( $my_query->have_posts() ) : $my_query->the_post();
$do_not_duplicate = $post->ID;
?>
<?php the_title(); ?>
<?php endwhile; ?>
<?php $my_query2 = new WP_Query( 'p=1' ); // get fixed post with id=1
while ( $my_query2->have_posts() ) : $my_query2->the_post();
?>
<?php the_title(); ?>
<?php endwhile; ?>
<?php $my_query3 = new WP_Query( 'posts_per_page=3' ); // get the latest 3 posts
while ( $my_query3->have_posts() ) : $my_query3>the_post();
if ( $post->ID == $do_not_duplicate ) continue; // don't show the same post of the first loop
?>
<?php the_title(); ?>
<?php endwhile; endif; ?>
</code></pre>
<p>There's a different way to do this without do many loops, considering that there's already one in the page ?</p>
<p>thank you</p>
|
[
{
"answer_id": 227708,
"author": "AntonChanning",
"author_id": 5077,
"author_profile": "https://wordpress.stackexchange.com/users/5077",
"pm_score": 0,
"selected": false,
"text": "<p>One way would be to use the built in counter to tell how many times you've been through the loop, then use <code>get_post</code> on the fixed posts id once you've been through 3 times...</p>\n\n<pre><code> <?php \n $my_query = new WP_Query( 'posts_per_page=5' ); // get the latest 5 posts\n while ( $my_query->have_posts() ) : $my_query->the_post();\n $do_not_duplicate = $post->ID; \n ?>\n <?php the_title(); ?>\n\n <?php \n if(3 == $my_query->current_post) {\n $fixed_post = get_post(1);\n // Do what you need to with $fixed_post...\n }\n endwhile; \n ?>\n</code></pre>\n\n<p>See the wordpress developer reference for <a href=\"https://developer.wordpress.org/reference/functions/get_post/\" rel=\"nofollow\">get_post</a> for more details...</p>\n\n<p>(Editted code to use built in counter as per suggestion of Milo in comments.)</p>\n"
},
{
"answer_id": 227712,
"author": "Luis Sanz",
"author_id": 81084,
"author_profile": "https://wordpress.stackexchange.com/users/81084",
"pm_score": 2,
"selected": true,
"text": "<p>I cannot think of a way of getting the latest 5 posts plus a specific one in a single query without using SQL.</p>\n\n<p>If you don't mind using two queries, I think this would be an easy way to do what you intend:</p>\n\n<pre><code>//Get the latest 5 posts (which happens to be get_posts default 'posts_per_page' value)\n$posts = get_posts();\n\n//Build up an array with the IDs\n$latests_posts_ids = wp_list_pluck( $posts, 'ID' );\n\n//Insert the desired ID in the third position\n$post_id_to_insert = 1;\n$insert_position = 2; //which equals 3 when starting from 0\narray_splice( $latests_posts_ids, $insert_position, 0, $post_id_to_insert );\n\n//Get the posts based on the IDs and do not alter their order\n$args = array(\n 'posts_per_page' => 6,\n 'post__in' => $latests_posts_ids,\n 'orderby' => 'post__in'\n);\n\n$posts = get_posts( $args );\n\n//Parse the posts\nforeach( $posts as $post ) :\n\n setup_postdata( $post );\n the_title();\n\nendforeach;\n</code></pre>\n\n<p>I'm using <a href=\"https://codex.wordpress.org/Template_Tags/get_posts\" rel=\"nofollow\"><code>get_posts()</code></a> but you can safely use <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">WP_query</a> instead.</p>\n\n<p>WordPress already handles possible duplicates in <code>post__in</code>, which would be the case if the post you want to insert is one of the latest 5.</p>\n"
}
] |
2016/05/24
|
[
"https://wordpress.stackexchange.com/questions/227707",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71371/"
] |
I'm looking for some advice on how to make a gallery of images.
it is a particular bit a gallery, because I would show the last 5 post and a fixed post, for a total of 6 posts, in a specific order. ie the fixed post must be the third in the list.
The only method that I believe it is possible to create 3 loops, the first to see the last two post, the second to display the fixed post (by id), and the third to see other last three posts.
Something like this (most probably it is not correct):
```
<?php $my_query = new WP_Query( 'posts_per_page=2' ); // get the latest 2 posts
while ( $my_query->have_posts() ) : $my_query->the_post();
$do_not_duplicate = $post->ID;
?>
<?php the_title(); ?>
<?php endwhile; ?>
<?php $my_query2 = new WP_Query( 'p=1' ); // get fixed post with id=1
while ( $my_query2->have_posts() ) : $my_query2->the_post();
?>
<?php the_title(); ?>
<?php endwhile; ?>
<?php $my_query3 = new WP_Query( 'posts_per_page=3' ); // get the latest 3 posts
while ( $my_query3->have_posts() ) : $my_query3>the_post();
if ( $post->ID == $do_not_duplicate ) continue; // don't show the same post of the first loop
?>
<?php the_title(); ?>
<?php endwhile; endif; ?>
```
There's a different way to do this without do many loops, considering that there's already one in the page ?
thank you
|
I cannot think of a way of getting the latest 5 posts plus a specific one in a single query without using SQL.
If you don't mind using two queries, I think this would be an easy way to do what you intend:
```
//Get the latest 5 posts (which happens to be get_posts default 'posts_per_page' value)
$posts = get_posts();
//Build up an array with the IDs
$latests_posts_ids = wp_list_pluck( $posts, 'ID' );
//Insert the desired ID in the third position
$post_id_to_insert = 1;
$insert_position = 2; //which equals 3 when starting from 0
array_splice( $latests_posts_ids, $insert_position, 0, $post_id_to_insert );
//Get the posts based on the IDs and do not alter their order
$args = array(
'posts_per_page' => 6,
'post__in' => $latests_posts_ids,
'orderby' => 'post__in'
);
$posts = get_posts( $args );
//Parse the posts
foreach( $posts as $post ) :
setup_postdata( $post );
the_title();
endforeach;
```
I'm using [`get_posts()`](https://codex.wordpress.org/Template_Tags/get_posts) but you can safely use [WP\_query](https://codex.wordpress.org/Class_Reference/WP_Query) instead.
WordPress already handles possible duplicates in `post__in`, which would be the case if the post you want to insert is one of the latest 5.
|
227,714 |
<p>I'm digging out on old question as no solution came out.
<a href="https://wordpress.stackexchange.com/questions/190634/how-to-limit-page-pagination">How to limit page pagination</a></p>
<p>I'm looking for a way to limit pages on homepage and categories (archive.php).
I have around 200k posts spread into about 50 categories.
If I leave the default pagination, homepage has 20k pages.
Then most categories have over 5k pages.
This will send google in some long long loops... and each time a post is added (200/day) google will start again etc... when all I want is google to look into recent posts (this is a news website)</p>
<p>All I need is to let the visitors navigate threw the 10 first pages of each categories.</p>
<p>Is there a nice way for doing this?</p>
<p>I've tried different things described here without success.
<a href="https://wordpress.stackexchange.com/questions/194363/limit-number-of-pages-in-pagination">Limit number of pages in pagination</a></p>
<pre><code>// this didn't work (beyond page 10 "next page" take us back to page 1)
function wpcodex_filter_main_search_post_limits( $limit, $query ) {
return 'LIMIT 0, 100';
}
add_filter( 'post_limits', 'wpcodex_filter_main_search_post_limits', 10, 2 );
</code></pre>
<p>Removing the page links on page 10 would work for me even if you can manually enter page 11 and see page 11 posts... all I want is google not to find a link.</p>
<p>Deleting old posts is not an option, nor running a double query.</p>
<p>Thanks for your help</p>
|
[
{
"answer_id": 227730,
"author": "Antony Gibbs",
"author_id": 93359,
"author_profile": "https://wordpress.stackexchange.com/users/93359",
"pm_score": 1,
"selected": false,
"text": "<p>I was lucky, the theme used it's own function, so it was easy to override.\nInspired by worpdress native get_the_posts_navigation (wp-includes/link-template.php) here is what I end up using:</p>\n\n<pre><code>function my_get_the_posts_navigation( $args = array() ) {\n $limit = 5;\n $navigation = '';\n\n // Don't print empty markup if there's only one page.\n if ( $GLOBALS['wp_query']->max_num_pages > 1 ) {\n $args = wp_parse_args( $args, array(\n 'prev_text' => __( 'Older posts' ),\n 'next_text' => __( 'Newer posts' ),\n 'screen_reader_text' => __( 'Posts navigation' ),\n ) );\n\n\n $next_link = get_previous_posts_link( $args['next_text'] );\n\n $p = (get_query_var('paged')) ? get_query_var('paged') : 1;\n if ($p < $limit) {\n $prev_link = get_next_posts_link( $args['prev_text'] );\n } else {\n $prev_link = false;\n }\n\n if ( $prev_link ) {\n $navigation .= '<div class=\"nav-previous\">' . $prev_link . '</div>';\n }\n\n if ( $next_link ) {\n $navigation .= '<div class=\"nav-next\">' . $next_link . '</div>';\n }\n\n $navigation = _navigation_markup( $navigation, 'posts-navigation', $args['screen_reader_text'] );\n }\n\n return $navigation;\n}\n\nfunction my_the_posts_navigation( $args = array() ) {\n echo my_get_the_posts_navigation( $args );\n}\n\n// now override the theme pagination function\nif ( ! function_exists( 'cactus_paging_nav' ) ) :\nfunction cactus_paging_nav() {\n\n my_the_posts_navigation();\n}\nendif;\n</code></pre>\n"
},
{
"answer_id": 379974,
"author": "Bunty",
"author_id": 109377,
"author_profile": "https://wordpress.stackexchange.com/users/109377",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the following function into your archive template</p>\n<pre><code>paginate_links\n</code></pre>\n<p>And set "total" to your desired number of pages.</p>\n<p>Ref: <a href=\"https://developer.wordpress.org/reference/functions/paginate_links/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/paginate_links/</a></p>\n"
}
] |
2016/05/24
|
[
"https://wordpress.stackexchange.com/questions/227714",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93359/"
] |
I'm digging out on old question as no solution came out.
[How to limit page pagination](https://wordpress.stackexchange.com/questions/190634/how-to-limit-page-pagination)
I'm looking for a way to limit pages on homepage and categories (archive.php).
I have around 200k posts spread into about 50 categories.
If I leave the default pagination, homepage has 20k pages.
Then most categories have over 5k pages.
This will send google in some long long loops... and each time a post is added (200/day) google will start again etc... when all I want is google to look into recent posts (this is a news website)
All I need is to let the visitors navigate threw the 10 first pages of each categories.
Is there a nice way for doing this?
I've tried different things described here without success.
[Limit number of pages in pagination](https://wordpress.stackexchange.com/questions/194363/limit-number-of-pages-in-pagination)
```
// this didn't work (beyond page 10 "next page" take us back to page 1)
function wpcodex_filter_main_search_post_limits( $limit, $query ) {
return 'LIMIT 0, 100';
}
add_filter( 'post_limits', 'wpcodex_filter_main_search_post_limits', 10, 2 );
```
Removing the page links on page 10 would work for me even if you can manually enter page 11 and see page 11 posts... all I want is google not to find a link.
Deleting old posts is not an option, nor running a double query.
Thanks for your help
|
I was lucky, the theme used it's own function, so it was easy to override.
Inspired by worpdress native get\_the\_posts\_navigation (wp-includes/link-template.php) here is what I end up using:
```
function my_get_the_posts_navigation( $args = array() ) {
$limit = 5;
$navigation = '';
// Don't print empty markup if there's only one page.
if ( $GLOBALS['wp_query']->max_num_pages > 1 ) {
$args = wp_parse_args( $args, array(
'prev_text' => __( 'Older posts' ),
'next_text' => __( 'Newer posts' ),
'screen_reader_text' => __( 'Posts navigation' ),
) );
$next_link = get_previous_posts_link( $args['next_text'] );
$p = (get_query_var('paged')) ? get_query_var('paged') : 1;
if ($p < $limit) {
$prev_link = get_next_posts_link( $args['prev_text'] );
} else {
$prev_link = false;
}
if ( $prev_link ) {
$navigation .= '<div class="nav-previous">' . $prev_link . '</div>';
}
if ( $next_link ) {
$navigation .= '<div class="nav-next">' . $next_link . '</div>';
}
$navigation = _navigation_markup( $navigation, 'posts-navigation', $args['screen_reader_text'] );
}
return $navigation;
}
function my_the_posts_navigation( $args = array() ) {
echo my_get_the_posts_navigation( $args );
}
// now override the theme pagination function
if ( ! function_exists( 'cactus_paging_nav' ) ) :
function cactus_paging_nav() {
my_the_posts_navigation();
}
endif;
```
|
227,724 |
<p>I am working on adding some functionality on a Wordpress plugin which after a certain click needs to call on some shortcode through ajax.</p>
<p>What I first attempted was to call the shortcode inside of the ajax processing in my functions.php file:</p>
<pre><code>add_action( 'wp_ajax_nopriv_showads', 'showads' );
function showads(){
echo do_shortcode('[myshortcode]');
wp_die();
}
</code></pre>
<p>Where I would move the output of the shortcode in the response of the ajax call. This shortcode did not execute at all.</p>
<p>So instead after some research in the "wp_localize_script" function inside of the plugin I would call the shortcode:</p>
<pre><code> wp_localize_script( 'script-handle', 'ajax_object',
array('ajaxurl' => admin_url( 'admin-ajax.php' ),
'adspace' => do_shortcode( '[myshortcode]' )
));
</code></pre>
<p>And in the response of the ajax I would move the output of the shortcode. </p>
<p>The problem I'm having at the moment is that as soon as the "wp_localize_script" function is called the output of the shortcode (it should create a google ad) is all stripped. </p>
<p>I'd like to know if there is a way to not have the shortcode output stripped or advice if I'm trying to solve this whole thing the incorrect way.</p>
|
[
{
"answer_id": 227730,
"author": "Antony Gibbs",
"author_id": 93359,
"author_profile": "https://wordpress.stackexchange.com/users/93359",
"pm_score": 1,
"selected": false,
"text": "<p>I was lucky, the theme used it's own function, so it was easy to override.\nInspired by worpdress native get_the_posts_navigation (wp-includes/link-template.php) here is what I end up using:</p>\n\n<pre><code>function my_get_the_posts_navigation( $args = array() ) {\n $limit = 5;\n $navigation = '';\n\n // Don't print empty markup if there's only one page.\n if ( $GLOBALS['wp_query']->max_num_pages > 1 ) {\n $args = wp_parse_args( $args, array(\n 'prev_text' => __( 'Older posts' ),\n 'next_text' => __( 'Newer posts' ),\n 'screen_reader_text' => __( 'Posts navigation' ),\n ) );\n\n\n $next_link = get_previous_posts_link( $args['next_text'] );\n\n $p = (get_query_var('paged')) ? get_query_var('paged') : 1;\n if ($p < $limit) {\n $prev_link = get_next_posts_link( $args['prev_text'] );\n } else {\n $prev_link = false;\n }\n\n if ( $prev_link ) {\n $navigation .= '<div class=\"nav-previous\">' . $prev_link . '</div>';\n }\n\n if ( $next_link ) {\n $navigation .= '<div class=\"nav-next\">' . $next_link . '</div>';\n }\n\n $navigation = _navigation_markup( $navigation, 'posts-navigation', $args['screen_reader_text'] );\n }\n\n return $navigation;\n}\n\nfunction my_the_posts_navigation( $args = array() ) {\n echo my_get_the_posts_navigation( $args );\n}\n\n// now override the theme pagination function\nif ( ! function_exists( 'cactus_paging_nav' ) ) :\nfunction cactus_paging_nav() {\n\n my_the_posts_navigation();\n}\nendif;\n</code></pre>\n"
},
{
"answer_id": 379974,
"author": "Bunty",
"author_id": 109377,
"author_profile": "https://wordpress.stackexchange.com/users/109377",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the following function into your archive template</p>\n<pre><code>paginate_links\n</code></pre>\n<p>And set "total" to your desired number of pages.</p>\n<p>Ref: <a href=\"https://developer.wordpress.org/reference/functions/paginate_links/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/paginate_links/</a></p>\n"
}
] |
2016/05/24
|
[
"https://wordpress.stackexchange.com/questions/227724",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40956/"
] |
I am working on adding some functionality on a Wordpress plugin which after a certain click needs to call on some shortcode through ajax.
What I first attempted was to call the shortcode inside of the ajax processing in my functions.php file:
```
add_action( 'wp_ajax_nopriv_showads', 'showads' );
function showads(){
echo do_shortcode('[myshortcode]');
wp_die();
}
```
Where I would move the output of the shortcode in the response of the ajax call. This shortcode did not execute at all.
So instead after some research in the "wp\_localize\_script" function inside of the plugin I would call the shortcode:
```
wp_localize_script( 'script-handle', 'ajax_object',
array('ajaxurl' => admin_url( 'admin-ajax.php' ),
'adspace' => do_shortcode( '[myshortcode]' )
));
```
And in the response of the ajax I would move the output of the shortcode.
The problem I'm having at the moment is that as soon as the "wp\_localize\_script" function is called the output of the shortcode (it should create a google ad) is all stripped.
I'd like to know if there is a way to not have the shortcode output stripped or advice if I'm trying to solve this whole thing the incorrect way.
|
I was lucky, the theme used it's own function, so it was easy to override.
Inspired by worpdress native get\_the\_posts\_navigation (wp-includes/link-template.php) here is what I end up using:
```
function my_get_the_posts_navigation( $args = array() ) {
$limit = 5;
$navigation = '';
// Don't print empty markup if there's only one page.
if ( $GLOBALS['wp_query']->max_num_pages > 1 ) {
$args = wp_parse_args( $args, array(
'prev_text' => __( 'Older posts' ),
'next_text' => __( 'Newer posts' ),
'screen_reader_text' => __( 'Posts navigation' ),
) );
$next_link = get_previous_posts_link( $args['next_text'] );
$p = (get_query_var('paged')) ? get_query_var('paged') : 1;
if ($p < $limit) {
$prev_link = get_next_posts_link( $args['prev_text'] );
} else {
$prev_link = false;
}
if ( $prev_link ) {
$navigation .= '<div class="nav-previous">' . $prev_link . '</div>';
}
if ( $next_link ) {
$navigation .= '<div class="nav-next">' . $next_link . '</div>';
}
$navigation = _navigation_markup( $navigation, 'posts-navigation', $args['screen_reader_text'] );
}
return $navigation;
}
function my_the_posts_navigation( $args = array() ) {
echo my_get_the_posts_navigation( $args );
}
// now override the theme pagination function
if ( ! function_exists( 'cactus_paging_nav' ) ) :
function cactus_paging_nav() {
my_the_posts_navigation();
}
endif;
```
|
227,737 |
<p>In my settings, I have New York defined as the time zone. But when I run plugins using PHP date() functions, I am getting a time zone of UTC as it shows in WP Admin > Settings > General.</p>
<p><a href="https://i.stack.imgur.com/7Fqlw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7Fqlw.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/Xxn6R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xxn6R.png" alt="enter image description here"></a></p>
<p><strong>Edit:</strong> Here's the mu-plugin I use to add the meta tag:</p>
<pre><code><?php
/**
* Plugin Name: Web Services Global Meta Tag(s)
* Plugin URI: http://example.com/wp-content/mu-plugins/global-metatag-insertion.php
* Description: This plugin fires on every page and post in the WordPress Multisite Network. It adds custom meta tags to meets our needs. One meta tag that is added is for `last-modified` date.
* Version: 1.0
* Author: me
* Author URI: http://me.example.com/
*/
defined( 'ABSPATH' ) or die( 'Direct access not allowed' );
/**
* Insert `last-modified` date meta within `<head></head>` container
*/
function last_modified_date() {
echo '<meta http-equiv="last-modified" content="' . date( 'D, d M Y H:i:s T', strtotime( get_the_date() .' ' . get_the_time() ) ) . '" />' . "\n";
}
add_action( 'wp_head', 'last_modified_date' );
</code></pre>
|
[
{
"answer_id": 227800,
"author": "kaiser",
"author_id": 385,
"author_profile": "https://wordpress.stackexchange.com/users/385",
"pm_score": 2,
"selected": false,
"text": "<h2>Headers</h2>\n\n<p>First off: The <code>http-equiv</code> meta tags are the HTML <strong>equiv</strong>alent of an HTTP response header. They <strong>can not</strong> override a header already sent by your web server. So their only use is as a fallback and they rarely provide any real help. In reality, you want to go in and fix the headers your server(s) is/are sending instead – or ask your host to do so if you are in a shared environment and are not allowed to do so.</p>\n\n<h2>Date and Time options</h2>\n\n<p>All those can be retrieved via: <code>get_option( 'name' );</code>. The possible values are:</p>\n\n<ul>\n<li>Time format: <code>time_format</code> – default: <code>__('g:i a')</code> (string)</li>\n<li>Time zone: <code>timezone_string</code> – default: <code>null</code> (string)</li>\n<li>Date format: <code>date_format</code> – default: <code>__('F j, Y')</code> (string)</li>\n<li>GMT Offset: <code>gmt_offset</code> – default: <code>date('Z') / 3600</code> (integer)</li>\n</ul>\n\n<p>Then there are several other possible functions that you can use, depending on what you are actually displaying (use \"Conditional Tags\" to switch):</p>\n\n<ul>\n<li>Single post or page (or custom post): <a href=\"https://codex.wordpress.org/Function_Reference/the_date\" rel=\"nofollow noreferrer\"><code>the_date()</code></a></li>\n<li>Archives: Use the most current post date for this archive…</li>\n<li>…</li>\n</ul>\n\n<p>Here's your plugin, slightly reformatted to retrieve the timezone name from the GMT offset, account for <a href=\"https://bugs.php.net/bug.php?id=44780\" rel=\"nofollow noreferrer\">PHP Bug #44780</a> (props <a href=\"https://stackoverflow.com/a/11896631/376483\">uınbɐɥs</a>) and also custom settings from your admin UI. If that is not what you want, you will have to play a bit with the options. What is missing is the conditional switches</p>\n\n<pre><code><?php\n/* Plugin Name: \"Last Modified\" meta tag */\nadd_action( 'wp_head', function() \n{\n // Abort if not on at home/ on the front page as this is just an example\n if ( ! ( is_home() or is_front_page() )\n return;\n\n $offset = get_option( 'gmt_offset' ) * 3600;\n $zone = timezone_name_from_abbr( '', $offset, 1 );\n ! $zone and $zone = timezone_name_from_abbr( '', $offset, 0 );\n $format = get_option( 'date_format' ).' '.get_option( 'time_format' ) );\n // @TODO adjust to take post date or similar into account\n $date = 'now';\n\n printf( '<meta http-equiv=\"last-modified\" content=\"%s\" />',\n ( new DateTime( $date, $zone ) )\n ->format( $format )\n );\n} );\n</code></pre>\n"
},
{
"answer_id": 227833,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 2,
"selected": false,
"text": "<p><code>date()</code> is unreliable in WP since it always resets time zone to UTC and uses its own processing for time zones.</p>\n\n<p><code>date_i18n()</code> is usually preferable WP replacement, <em>but</em> it will also localize output, which might be unwanted.</p>\n\n<p>What you want for correct unlocalized output is to:</p>\n\n<ol>\n<li>Get data out of WP API without its offset silliness.</li>\n<li>Get timezone setting out of WP.</li>\n<li>Feed those into <code>DateTime</code> object.</li>\n</ol>\n\n<p>Here is brief (read it basics, not covering all possibilities) introduction to code:</p>\n\n<pre><code>d( date( 'D, d M Y H:i:s T', strtotime( get_the_date() .' ' . get_the_time() ) ) );\n// Sat, 07 Jan 2012 07:07:00 UTC < wrong, date() is always wrong in WP\n\nd( date( 'D, d M Y H:i:s T', get_the_time('U') ) );\n// Sat, 07 Jan 2012 07:07:21 UTC < more short, still wrong\n\nd( date_i18n( 'D, d M Y H:i:s T', get_the_time('U') ) );\n// or simply\nd( get_the_time( 'D, d M Y H:i:s T' ) );\n// Сб, 07 Jan 2012 07:07:21 EEST < correct! but localized\n\n$date = DateTime::createFromFormat( DATE_W3C, get_the_date( DATE_W3C ) );\nd( $date->format( 'D, d M Y H:i:s T' ) );\n// Sat, 07 Jan 2012 07:07:21 GMT+0300 < correct, but meh numeric time zone\n\n$timezone = new DateTimeZone( get_option( 'timezone_string' ) );\n$date->setTimezone( $timezone );\n\nd( $date->format( 'D, d M Y H:i:s T' ) );\n// Sat, 07 Jan 2012 06:07:21 EET < correct and not localized\n</code></pre>\n\n<p>I wrote more on topic in my <a href=\"https://www.rarst.net/wordpress/datetime-crash-course/\" rel=\"nofollow\">DateTime crash course for WordPress developers</a> post.</p>\n\n<p>PS EEST / EET out of sync... I don't even know what's up with that difference. :)</p>\n"
}
] |
2016/05/24
|
[
"https://wordpress.stackexchange.com/questions/227737",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
In my settings, I have New York defined as the time zone. But when I run plugins using PHP date() functions, I am getting a time zone of UTC as it shows in WP Admin > Settings > General.
[](https://i.stack.imgur.com/7Fqlw.png)
[](https://i.stack.imgur.com/Xxn6R.png)
**Edit:** Here's the mu-plugin I use to add the meta tag:
```
<?php
/**
* Plugin Name: Web Services Global Meta Tag(s)
* Plugin URI: http://example.com/wp-content/mu-plugins/global-metatag-insertion.php
* Description: This plugin fires on every page and post in the WordPress Multisite Network. It adds custom meta tags to meets our needs. One meta tag that is added is for `last-modified` date.
* Version: 1.0
* Author: me
* Author URI: http://me.example.com/
*/
defined( 'ABSPATH' ) or die( 'Direct access not allowed' );
/**
* Insert `last-modified` date meta within `<head></head>` container
*/
function last_modified_date() {
echo '<meta http-equiv="last-modified" content="' . date( 'D, d M Y H:i:s T', strtotime( get_the_date() .' ' . get_the_time() ) ) . '" />' . "\n";
}
add_action( 'wp_head', 'last_modified_date' );
```
|
Headers
-------
First off: The `http-equiv` meta tags are the HTML **equiv**alent of an HTTP response header. They **can not** override a header already sent by your web server. So their only use is as a fallback and they rarely provide any real help. In reality, you want to go in and fix the headers your server(s) is/are sending instead – or ask your host to do so if you are in a shared environment and are not allowed to do so.
Date and Time options
---------------------
All those can be retrieved via: `get_option( 'name' );`. The possible values are:
* Time format: `time_format` – default: `__('g:i a')` (string)
* Time zone: `timezone_string` – default: `null` (string)
* Date format: `date_format` – default: `__('F j, Y')` (string)
* GMT Offset: `gmt_offset` – default: `date('Z') / 3600` (integer)
Then there are several other possible functions that you can use, depending on what you are actually displaying (use "Conditional Tags" to switch):
* Single post or page (or custom post): [`the_date()`](https://codex.wordpress.org/Function_Reference/the_date)
* Archives: Use the most current post date for this archive…
* …
Here's your plugin, slightly reformatted to retrieve the timezone name from the GMT offset, account for [PHP Bug #44780](https://bugs.php.net/bug.php?id=44780) (props [uınbɐɥs](https://stackoverflow.com/a/11896631/376483)) and also custom settings from your admin UI. If that is not what you want, you will have to play a bit with the options. What is missing is the conditional switches
```
<?php
/* Plugin Name: "Last Modified" meta tag */
add_action( 'wp_head', function()
{
// Abort if not on at home/ on the front page as this is just an example
if ( ! ( is_home() or is_front_page() )
return;
$offset = get_option( 'gmt_offset' ) * 3600;
$zone = timezone_name_from_abbr( '', $offset, 1 );
! $zone and $zone = timezone_name_from_abbr( '', $offset, 0 );
$format = get_option( 'date_format' ).' '.get_option( 'time_format' ) );
// @TODO adjust to take post date or similar into account
$date = 'now';
printf( '<meta http-equiv="last-modified" content="%s" />',
( new DateTime( $date, $zone ) )
->format( $format )
);
} );
```
|
227,742 |
<p>How do I enqueue a script on the header if the user is on an archive page of a custom post type? The custom post type is called <code>limitedrun</code> and the page is called <code>archive-limitedrun.php</code>.</p>
<p>I tried this and got no response:</p>
<pre><code>function opby_theme() {
wp_register_script('responsive-img', get_template_directory_uri() .'/js/responsive-img.min.js', array('jquery'));
wp_enqueue_script('responsive-img');
wp_enqueue_style( 'opby', get_stylesheet_uri() );
wp_register_style('googleFonts', 'https://fonts.googleapis.co/css?family=Roboto+Slab:400,100|Bitter');
wp_enqueue_style( 'googleFonts');
if (is_singular('limitedrun') ) {
wp_register_style('ltd-run-font', 'https://fonts.googleapis.com/css?family=Roboto:100,500');
wp_enqueue_style( 'ltd-run-font');
}
}
add_action( 'wp_enqueue_scripts', 'opby_theme' );
</code></pre>
|
[
{
"answer_id": 227745,
"author": "vancoder",
"author_id": 26778,
"author_profile": "https://wordpress.stackexchange.com/users/26778",
"pm_score": 2,
"selected": false,
"text": "<p><code>is_singular</code> doesn't handle archives.</p>\n\n<p>Try</p>\n\n<pre><code>is_post_type_archive( 'limitedrun' );\n</code></pre>\n"
},
{
"answer_id": 227764,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 4,
"selected": true,
"text": "<p>You can save your time and server load by not using <code>wp_register_script</code> and <code>wp_register_style</code> when you don't need them definitely. <code>wp_enqueue_style</code> and <code>wp_enqueue_script</code> do the same job themselves when not involving excessive functions.</p>\n\n<p>Here is easier and more readable code up to date with the accepted answer by @vancoder:</p>\n\n<pre><code><?php\nfunction opby_theme()\n{\n wp_enqueue_script(\n 'responsive-img',\n get_template_directory_uri() .'/js/responsive-img.min.js',\n array('jquery')\n );\n\n wp_enqueue_style(\n 'opby',\n get_stylesheet_uri()\n );\n\n wp_enqueue_style(\n 'googleFonts',\n 'https://fonts.googleapis.co/css?family=Roboto+Slab:400,100|Bitter'\n );\n\n if ( is_post_type_archive('limitedrun') ) {\n wp_enqueue_style(\n 'ltd-run-font',\n 'https://fonts.googleapis.com/css?family=Roboto:100,500'\n );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'opby_theme' );\n</code></pre>\n"
},
{
"answer_id": 357990,
"author": "Leon",
"author_id": 134981,
"author_profile": "https://wordpress.stackexchange.com/users/134981",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the <code>template_redirect</code> action hook for exactly that.</p>\n\n<p>This hook is the point where WordPress knows which templates the user is viewing and gets fired just before the template files are loaded.</p>\n\n<p>Here is an example, where a stylesheet is only loaded for the post archive: </p>\n\n<p>`</p>\n\n<pre><code>// Call the hook and register your function\nadd_action( 'template_redirect', 'register_styles_for_post_archive' );\n\n// Call your function which enqueues the stylesheet only for the post archive\nfunction register_styles_for_post_archive() {\n\n// put in your post type as a parameter or leave empty for the actual post type\n if ( is_post_type_archive( $post_types ) ) {\n wp_enqueue_style('your-custom-stylesheet-name', 'your-css-file.css', false, 01, 'screen');\n\n }\n}\n</code></pre>\n\n<p>`</p>\n"
}
] |
2016/05/24
|
[
"https://wordpress.stackexchange.com/questions/227742",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8049/"
] |
How do I enqueue a script on the header if the user is on an archive page of a custom post type? The custom post type is called `limitedrun` and the page is called `archive-limitedrun.php`.
I tried this and got no response:
```
function opby_theme() {
wp_register_script('responsive-img', get_template_directory_uri() .'/js/responsive-img.min.js', array('jquery'));
wp_enqueue_script('responsive-img');
wp_enqueue_style( 'opby', get_stylesheet_uri() );
wp_register_style('googleFonts', 'https://fonts.googleapis.co/css?family=Roboto+Slab:400,100|Bitter');
wp_enqueue_style( 'googleFonts');
if (is_singular('limitedrun') ) {
wp_register_style('ltd-run-font', 'https://fonts.googleapis.com/css?family=Roboto:100,500');
wp_enqueue_style( 'ltd-run-font');
}
}
add_action( 'wp_enqueue_scripts', 'opby_theme' );
```
|
You can save your time and server load by not using `wp_register_script` and `wp_register_style` when you don't need them definitely. `wp_enqueue_style` and `wp_enqueue_script` do the same job themselves when not involving excessive functions.
Here is easier and more readable code up to date with the accepted answer by @vancoder:
```
<?php
function opby_theme()
{
wp_enqueue_script(
'responsive-img',
get_template_directory_uri() .'/js/responsive-img.min.js',
array('jquery')
);
wp_enqueue_style(
'opby',
get_stylesheet_uri()
);
wp_enqueue_style(
'googleFonts',
'https://fonts.googleapis.co/css?family=Roboto+Slab:400,100|Bitter'
);
if ( is_post_type_archive('limitedrun') ) {
wp_enqueue_style(
'ltd-run-font',
'https://fonts.googleapis.com/css?family=Roboto:100,500'
);
}
}
add_action( 'wp_enqueue_scripts', 'opby_theme' );
```
|
227,771 |
<p>I have taken over a website where I work that was developed by a previous employee, it seems that recently this site has been the victim of a string of DDoS attacks through the use of the xmlrpc pingback proven by log entries like this:</p>
<p><code>154.16.63.40 - - [22/May/2016:06:52:49 +0100] "POST /xmlrpc.php HTTP/1.1" 200 596 "-" "Googlebot/2.1 (+http://www.google.com/bot.html)"
</code> (Obviously this isn't a google bot because there is no reason for google to post to this file.)</p>
<p>I believe there are many solutions to this (<a href="https://www.digitalocean.com/community/tutorials/how-to-protect-wordpress-from-xml-rpc-attacks-on-ubuntu-14-04" rel="nofollow">This tutorial</a>) but I tend to lean towards just outright blocking access to the file. However I am unsure as to whether this site is actually using the service xmlrpc allows you to use. Is there any particular way I can check if the previous developer has put anything in place to use wordpress xmlrpc functionality? Could I check for functions in specific files/is there anything that screams out to identify the use?</p>
<p>any help with this would be great!</p>
<p><strong>EDIT:</strong> Would something like this be helpful?</p>
<pre><code><FilesMatch "^(xmlrpc\.php)">
Order Deny,Allow
# IP address Whitelist
Allow from xxx.xxx.xxx.xxx
Deny from all
</FilesMatch>
</code></pre>
<p>If I allow from the ip address of the server would this work for plugins etc or do they all have their own IP address that would need to be added?</p>
|
[
{
"answer_id": 227745,
"author": "vancoder",
"author_id": 26778,
"author_profile": "https://wordpress.stackexchange.com/users/26778",
"pm_score": 2,
"selected": false,
"text": "<p><code>is_singular</code> doesn't handle archives.</p>\n\n<p>Try</p>\n\n<pre><code>is_post_type_archive( 'limitedrun' );\n</code></pre>\n"
},
{
"answer_id": 227764,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 4,
"selected": true,
"text": "<p>You can save your time and server load by not using <code>wp_register_script</code> and <code>wp_register_style</code> when you don't need them definitely. <code>wp_enqueue_style</code> and <code>wp_enqueue_script</code> do the same job themselves when not involving excessive functions.</p>\n\n<p>Here is easier and more readable code up to date with the accepted answer by @vancoder:</p>\n\n<pre><code><?php\nfunction opby_theme()\n{\n wp_enqueue_script(\n 'responsive-img',\n get_template_directory_uri() .'/js/responsive-img.min.js',\n array('jquery')\n );\n\n wp_enqueue_style(\n 'opby',\n get_stylesheet_uri()\n );\n\n wp_enqueue_style(\n 'googleFonts',\n 'https://fonts.googleapis.co/css?family=Roboto+Slab:400,100|Bitter'\n );\n\n if ( is_post_type_archive('limitedrun') ) {\n wp_enqueue_style(\n 'ltd-run-font',\n 'https://fonts.googleapis.com/css?family=Roboto:100,500'\n );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'opby_theme' );\n</code></pre>\n"
},
{
"answer_id": 357990,
"author": "Leon",
"author_id": 134981,
"author_profile": "https://wordpress.stackexchange.com/users/134981",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the <code>template_redirect</code> action hook for exactly that.</p>\n\n<p>This hook is the point where WordPress knows which templates the user is viewing and gets fired just before the template files are loaded.</p>\n\n<p>Here is an example, where a stylesheet is only loaded for the post archive: </p>\n\n<p>`</p>\n\n<pre><code>// Call the hook and register your function\nadd_action( 'template_redirect', 'register_styles_for_post_archive' );\n\n// Call your function which enqueues the stylesheet only for the post archive\nfunction register_styles_for_post_archive() {\n\n// put in your post type as a parameter or leave empty for the actual post type\n if ( is_post_type_archive( $post_types ) ) {\n wp_enqueue_style('your-custom-stylesheet-name', 'your-css-file.css', false, 01, 'screen');\n\n }\n}\n</code></pre>\n\n<p>`</p>\n"
}
] |
2016/05/25
|
[
"https://wordpress.stackexchange.com/questions/227771",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77202/"
] |
I have taken over a website where I work that was developed by a previous employee, it seems that recently this site has been the victim of a string of DDoS attacks through the use of the xmlrpc pingback proven by log entries like this:
`154.16.63.40 - - [22/May/2016:06:52:49 +0100] "POST /xmlrpc.php HTTP/1.1" 200 596 "-" "Googlebot/2.1 (+http://www.google.com/bot.html)"` (Obviously this isn't a google bot because there is no reason for google to post to this file.)
I believe there are many solutions to this ([This tutorial](https://www.digitalocean.com/community/tutorials/how-to-protect-wordpress-from-xml-rpc-attacks-on-ubuntu-14-04)) but I tend to lean towards just outright blocking access to the file. However I am unsure as to whether this site is actually using the service xmlrpc allows you to use. Is there any particular way I can check if the previous developer has put anything in place to use wordpress xmlrpc functionality? Could I check for functions in specific files/is there anything that screams out to identify the use?
any help with this would be great!
**EDIT:** Would something like this be helpful?
```
<FilesMatch "^(xmlrpc\.php)">
Order Deny,Allow
# IP address Whitelist
Allow from xxx.xxx.xxx.xxx
Deny from all
</FilesMatch>
```
If I allow from the ip address of the server would this work for plugins etc or do they all have their own IP address that would need to be added?
|
You can save your time and server load by not using `wp_register_script` and `wp_register_style` when you don't need them definitely. `wp_enqueue_style` and `wp_enqueue_script` do the same job themselves when not involving excessive functions.
Here is easier and more readable code up to date with the accepted answer by @vancoder:
```
<?php
function opby_theme()
{
wp_enqueue_script(
'responsive-img',
get_template_directory_uri() .'/js/responsive-img.min.js',
array('jquery')
);
wp_enqueue_style(
'opby',
get_stylesheet_uri()
);
wp_enqueue_style(
'googleFonts',
'https://fonts.googleapis.co/css?family=Roboto+Slab:400,100|Bitter'
);
if ( is_post_type_archive('limitedrun') ) {
wp_enqueue_style(
'ltd-run-font',
'https://fonts.googleapis.com/css?family=Roboto:100,500'
);
}
}
add_action( 'wp_enqueue_scripts', 'opby_theme' );
```
|
227,824 |
<p>I have a custom post type called 'directory' and it includes a few meta/custom fields. The script below is meant to just change the post status only when run. This isn't on the admin panel where you save the post. This is a stand alone script run by itself.</p>
<pre><code>require('../../../wp-blog-header.php');
global $wpdb;
global $post;
$directories = get_posts( $get_directories );
foreach ($directories as $directory){
wp_update_post(array('ID' => $directory->ID,'post_status' => 'draft'));
};
</code></pre>
<p>The status is updated fine, but the custom meta data is deleted.</p>
<p>I've seen other's with similar problems adding an update on the admin edit page, but this is its own file.</p>
|
[
{
"answer_id": 227828,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think this should happen by default. From quick look through the code the only case in which update call should affect meta is if you provide <code>meta_input</code> in arguments to apply.</p>\n\n<p>As per comment the case might be that you are trying to interact with third party CPT and <em>its</em> code doesn't handle situation well.</p>\n\n<p>Note that \"own file\" doesn't matter much (and is pretty bad practice while at it), the WP core will still boot and load all the plugins.</p>\n"
},
{
"answer_id": 227834,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 1,
"selected": true,
"text": "<p>Not sure about the problem with <code>wp_update_post</code> but it is a simple enough SQL query:</p>\n\n<pre><code>global $wpdb;\n$query = \"UPDATE \".$wpdb->prefix.\"posts SET post_status='draft' WHERE ID = '\".$directory->ID.\"'\";\n$wpdb->query($query);\n</code></pre>\n"
},
{
"answer_id": 227837,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 1,
"selected": false,
"text": "<p>Based on the source code of <a href=\"https://developer.wordpress.org/reference/functions/wp_publish_post/\" rel=\"nofollow\"><code>wp_publish_post()</code></a>, you could update the post status without touching meta data and, at the same time, without losing post transition actions (you are missing them in your code) with something like this:</p>\n\n<pre><code>global $wpdb;\n// Unkown $get_directories, you have not set it\n// in your sample code, I assume it is correct\n$directories = get_posts( $get_directories );\nforeach( $directories as $directory ){\n // Skip already draft posts\n if( $directory->post_status != 'draft' ) {\n $wpdb->update( $wpdb->posts, array( 'post_status' => 'draft' ), array( 'ID' => $directory->ID ) );\n clean_post_cache( $directory->ID );\n $old_status = $directory->post_status;\n $directory->post_status = 'draft';\n // Perform transition actions\n wp_transition_post_status( 'draft', $old_status, $directory );\n }\n}\n</code></pre>\n\n<p>You could include also other actinos triggered when a post is updated:</p>\n\n<pre><code>do_action( 'edit_post', $directory->ID, $post );\ndo_action( \"save_post_{$directory->post_type}\", $directory->ID, $directory, true );\ndo_action( 'save_post', $directory->ID, $directory, true );\ndo_action( 'wp_insert_post', $directory->ID, $directory, true );\n</code></pre>\n\n<p>But, as @Rast said, it is very probably that your problem is with some of these actions hooked by third party code (from another plugin or from the theme). These actions are triggered by <code>wp_update_post()</code> and it is commonly used to update post meta fields, specially <code>save_post</code> action. It is very probably that when these actions are triggered without meta information, like your code does, the third party code deletes the meta fields.</p>\n"
}
] |
2016/05/25
|
[
"https://wordpress.stackexchange.com/questions/227824",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94667/"
] |
I have a custom post type called 'directory' and it includes a few meta/custom fields. The script below is meant to just change the post status only when run. This isn't on the admin panel where you save the post. This is a stand alone script run by itself.
```
require('../../../wp-blog-header.php');
global $wpdb;
global $post;
$directories = get_posts( $get_directories );
foreach ($directories as $directory){
wp_update_post(array('ID' => $directory->ID,'post_status' => 'draft'));
};
```
The status is updated fine, but the custom meta data is deleted.
I've seen other's with similar problems adding an update on the admin edit page, but this is its own file.
|
Not sure about the problem with `wp_update_post` but it is a simple enough SQL query:
```
global $wpdb;
$query = "UPDATE ".$wpdb->prefix."posts SET post_status='draft' WHERE ID = '".$directory->ID."'";
$wpdb->query($query);
```
|
227,854 |
<p>This must be fairly simple, but I'm puzzled. And I may be going about it backwards.</p>
<p><em>How do I output a database option that is an array into a get_posts array?</em></p>
<p>I have an option in the database that stores some post IDs in the array format `1234,5678' . I can retrieve and echo them with</p>
<pre><code>$options = get_option( 'pu_theme_options' );
$newspostids = $options['pu_textbox'];
echo $newspostids;
</code></pre>
<p>so I know am getting the output `1234,5678'. The database "option" is just text, saved from a form field in theme options.</p>
<p>What I need to do is get the data from that option into a <code>get_posts</code> array so I can display the posts by ID.</p>
<p>What I need is for <code>get_posts</code> to function like this:</p>
<pre><code>$news = get_posts( array(
'post_type' => 'post',
'post__in'=> array(1234,5678)
) );
</code></pre>
<p>And, obviously, this doesn't work, putting the variable directly into the array and expecting it to output `1234,5678' :</p>
<pre><code>$news = get_posts( array(
'post_type' => 'post',
'post__in'=> array($newspostids)
) );
</code></pre>
<p>So how should this work?</p>
|
[
{
"answer_id": 227856,
"author": "Gareth Gillman",
"author_id": 33936,
"author_profile": "https://wordpress.stackexchange.com/users/33936",
"pm_score": 0,
"selected": false,
"text": "<p>get_posts doesn't have a post__in \"variable\", that's in wp_query, in get_posts (or get_pages) you would need to use include e.g.</p>\n\n<pre><code>$news = get_posts(\n array(\n 'post_type' => 'post',\n 'include' => $newspostids,\n )\n);\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_posts\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_posts</a></p>\n"
},
{
"answer_id": 227858,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p>You could use <a href=\"https://developer.wordpress.org/reference/functions/wp_parse_id_list/\" rel=\"nofollow\"><code>wp_parse_id_list()</code></a> to sanitize your comma seperated list of post IDs. It's defined as:</p>\n\n<pre><code>function wp_parse_id_list( $list ) {\n if ( !is_array($list) )\n $list = preg_split('/[\\s,]+/', $list);\n\n return array_unique(array_map('absint', $list));\n}\n</code></pre>\n\n<p>where we can see that it returns unique array values as well.</p>\n\n<p>Note that <a href=\"https://developer.wordpress.org/reference/functions/absint/\" rel=\"nofollow\"><code>absint()</code></a> is defined in core as <code>abs( intval() )</code> and there's a difference in the max output of <a href=\"http://php.net/manual/en/function.intval.php\" rel=\"nofollow\"><code>intval()</code></a> for 32 and 64 bit systems according to the PHP docs.</p>\n"
}
] |
2016/05/25
|
[
"https://wordpress.stackexchange.com/questions/227854",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/268/"
] |
This must be fairly simple, but I'm puzzled. And I may be going about it backwards.
*How do I output a database option that is an array into a get\_posts array?*
I have an option in the database that stores some post IDs in the array format `1234,5678' . I can retrieve and echo them with
```
$options = get_option( 'pu_theme_options' );
$newspostids = $options['pu_textbox'];
echo $newspostids;
```
so I know am getting the output `1234,5678'. The database "option" is just text, saved from a form field in theme options.
What I need to do is get the data from that option into a `get_posts` array so I can display the posts by ID.
What I need is for `get_posts` to function like this:
```
$news = get_posts( array(
'post_type' => 'post',
'post__in'=> array(1234,5678)
) );
```
And, obviously, this doesn't work, putting the variable directly into the array and expecting it to output `1234,5678' :
```
$news = get_posts( array(
'post_type' => 'post',
'post__in'=> array($newspostids)
) );
```
So how should this work?
|
You could use [`wp_parse_id_list()`](https://developer.wordpress.org/reference/functions/wp_parse_id_list/) to sanitize your comma seperated list of post IDs. It's defined as:
```
function wp_parse_id_list( $list ) {
if ( !is_array($list) )
$list = preg_split('/[\s,]+/', $list);
return array_unique(array_map('absint', $list));
}
```
where we can see that it returns unique array values as well.
Note that [`absint()`](https://developer.wordpress.org/reference/functions/absint/) is defined in core as `abs( intval() )` and there's a difference in the max output of [`intval()`](http://php.net/manual/en/function.intval.php) for 32 and 64 bit systems according to the PHP docs.
|
227,857 |
<p>I have a big problem rendering shortcodes in my template I designed for my Tennis Club which works fine. However, now I wanted to integrate the standard WordPress Gallery, which is implemented by a shortcode but the shortcode is not being displayed as a normal Gallery, it is displayed as a text without any images. Is there a way I can fix this?</p>
<p>Code:</p>
<pre><code><?php get_header(); ?>
<?php $options = get_option('tcs_theme_options'); ?>
<section id="page-content">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div id="headerpic">
<?php
$url = get_the_permalink();
$title = get_the_title();
$content = get_the_content();
$categories = get_the_category(', ');
$date = get_the_date('d.m.Y');
if (has_post_thumbnail()) {
the_post_thumbnail();
} else {
slideshow();
}?>
</div>
<section class="content">
<h1><a href="<?php echo $url; ?>"><?php echo $title; ?></a><span style="font-size: 14px;"></span></h1>
<p><?php echo $content; ?></p>
<div class="options col-xs-12">
<span class="fa fa-calendar pull-right"> <?php echo $date; ?></span>
</div>
</section>
<?php endwhile; endif; ?>
</section>
<?php get_sidebar(); ?>
<div class="clearfix"></div>
<?php get_footer(); ?>
</code></pre>
|
[
{
"answer_id": 227927,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p><code>get_the_content</code> doesn't apply all of the filters that <code>the_content</code> runs before outputting the result. You can fix this by simply using:</p>\n\n<pre><code><?php the_content(); ?>\n</code></pre>\n\n<p>in place of:</p>\n\n<pre><code><?php echo $content; ?>\n</code></pre>\n\n<p>If you look at <a href=\"https://developer.wordpress.org/reference/functions/the_content/#source-code\" rel=\"nofollow\">the source for <code>the_content</code></a>, you'll see the extra step it performs on what is returned from <code>get_the_content</code>.</p>\n"
},
{
"answer_id": 227931,
"author": "FullContactCoder",
"author_id": 48013,
"author_profile": "https://wordpress.stackexchange.com/users/48013",
"pm_score": 0,
"selected": false,
"text": "<p>Add the shortcode to your template like this:</p>\n\n<p><code><?php echo do_shortcode('[*shortcode here*]'); ?></code></p>\n"
},
{
"answer_id": 228193,
"author": "Karthikeyani Srijish",
"author_id": 86125,
"author_profile": "https://wordpress.stackexchange.com/users/86125",
"pm_score": 0,
"selected": false,
"text": "<p>Try <code>do_shortcode( get_the_content() );</code> or <code>apply_filters( 'the_content', get_the_content() );</code> in your post file.</p>\n"
}
] |
2016/05/25
|
[
"https://wordpress.stackexchange.com/questions/227857",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94693/"
] |
I have a big problem rendering shortcodes in my template I designed for my Tennis Club which works fine. However, now I wanted to integrate the standard WordPress Gallery, which is implemented by a shortcode but the shortcode is not being displayed as a normal Gallery, it is displayed as a text without any images. Is there a way I can fix this?
Code:
```
<?php get_header(); ?>
<?php $options = get_option('tcs_theme_options'); ?>
<section id="page-content">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div id="headerpic">
<?php
$url = get_the_permalink();
$title = get_the_title();
$content = get_the_content();
$categories = get_the_category(', ');
$date = get_the_date('d.m.Y');
if (has_post_thumbnail()) {
the_post_thumbnail();
} else {
slideshow();
}?>
</div>
<section class="content">
<h1><a href="<?php echo $url; ?>"><?php echo $title; ?></a><span style="font-size: 14px;"></span></h1>
<p><?php echo $content; ?></p>
<div class="options col-xs-12">
<span class="fa fa-calendar pull-right"> <?php echo $date; ?></span>
</div>
</section>
<?php endwhile; endif; ?>
</section>
<?php get_sidebar(); ?>
<div class="clearfix"></div>
<?php get_footer(); ?>
```
|
`get_the_content` doesn't apply all of the filters that `the_content` runs before outputting the result. You can fix this by simply using:
```
<?php the_content(); ?>
```
in place of:
```
<?php echo $content; ?>
```
If you look at [the source for `the_content`](https://developer.wordpress.org/reference/functions/the_content/#source-code), you'll see the extra step it performs on what is returned from `get_the_content`.
|
227,871 |
<p>Here's something odd, I want to print out a certain post on any page request, if you have a constant $idnumber of your favorite page/message, then add:</p>
<pre><code>$GLOBALS['post'] = get_post( $idnumber );
</code></pre>
<p><code>the_title();</code> echos that specific page's title, </p>
<p><code>get_permalink();</code> looks ok too,</p>
<p>but <code>the_content()</code> actually ignores the post set, and just prints whatever page was requested, again.</p>
|
[
{
"answer_id": 227873,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>There are many globals that are being set in a loop, not only <code>$post</code>, and you need to set all of them to get exactly the same behavior. To get this it is not enough to set <code>$post</code> but you also need to use <a href=\"https://developer.wordpress.org/reference/functions/setup_postdata/\" rel=\"nofollow\">setup_postdata</a></p>\n"
},
{
"answer_id": 227874,
"author": "NoBugs",
"author_id": 25767,
"author_profile": "https://wordpress.stackexchange.com/users/25767",
"pm_score": -1,
"selected": false,
"text": "<p>Really the_content filter is most of what you need to do to be like the_content, but not require all those other variables the_content() expects.</p>\n"
},
{
"answer_id": 227895,
"author": "Ivijan Stefan Stipić",
"author_id": 82023,
"author_profile": "https://wordpress.stackexchange.com/users/82023",
"pm_score": 0,
"selected": false,
"text": "<p>Well, from my side is better to use <code>WP_query()</code> for this and define all in variables. Reason for that is because you can define sparate loops foreah WP_query. Also you need to clean all prevous query when you get info. </p>\n"
}
] |
2016/05/26
|
[
"https://wordpress.stackexchange.com/questions/227871",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25767/"
] |
Here's something odd, I want to print out a certain post on any page request, if you have a constant $idnumber of your favorite page/message, then add:
```
$GLOBALS['post'] = get_post( $idnumber );
```
`the_title();` echos that specific page's title,
`get_permalink();` looks ok too,
but `the_content()` actually ignores the post set, and just prints whatever page was requested, again.
|
There are many globals that are being set in a loop, not only `$post`, and you need to set all of them to get exactly the same behavior. To get this it is not enough to set `$post` but you also need to use [setup\_postdata](https://developer.wordpress.org/reference/functions/setup_postdata/)
|
227,875 |
<p>I am currently working on an entertainment website and I am having issues with page load time. I would love to know if there is any method I can use to remove blank spaces from PHP, JS , CSS scripts running via the website.</p>
<p>As I believe this will reduce load time efficiently. Also please any pointers to how can I significantly reduce page load time. I am currently using Cloudflare CDN nameservers.</p>
|
[
{
"answer_id": 227878,
"author": "bakar",
"author_id": 58787,
"author_profile": "https://wordpress.stackexchange.com/users/58787",
"pm_score": 0,
"selected": false,
"text": "<p>You should install Wp total Cache plugin and configure it as instructed on this page <a href=\"https://gtmetrix.com/wordpress-optimization-guide.html\" rel=\"nofollow\">https://gtmetrix.com/wordpress-optimization-guide.html</a></p>\n\n<p>WP total cache minify settings will remove blank spaces from css and js files but it will not remove blank spaces from php code and for that you can use php beautifier. There are many free online tools available, google for it. </p>\n\n<p>If you are using cloudflare flexible ssl then enable it on only specific pages that require security (checkout, my account, login pages etc)</p>\n\n<p>You should also optimize all of the images on your site. You can use EWWW image optimizer or WP Smush plugin for this.</p>\n\n<p>Please note site speed also depends upon hosting server so if you are using a shared hosting, you can have site speed increases upto a limit.</p>\n"
},
{
"answer_id": 227896,
"author": "Ivijan Stefan Stipić",
"author_id": 82023,
"author_profile": "https://wordpress.stackexchange.com/users/82023",
"pm_score": 4,
"selected": true,
"text": "<p>I write one php code what totaly filter all html elements but is integrated in main index.php on the root. That made rendering a little faster but you also can do CDN for all your images and media. That will speedup your page a mutch better. I normaly point <code>/wp-content/uploads/</code> to subdomain and my WP get all media from that subdomain what made WP 20 times faster.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>I made one great regex what can work inside buffer. Copy/Paste this script in your theme <code>functions.php</code> and see magic.</p>\n\n<blockquote>\n <p>NOTE: If your source contain bad javascript or css what's not follow\n rules, this may broke website. But I use it on arround 100 templates,\n I never experience some issue. Work nice With Elementor and WC Builder</p>\n</blockquote>\n\n<pre><code>/* ----------------------------------------------------------------------------\n\n W3C Fix and HTML minifier by Ivijan-Stefan Stipic <[email protected]>\n\n---------------------------------------------------------------------------- */\nadd_action('wp_loaded', 'atm_output_buffer_start');\nadd_action('shutdown', 'atm_output_buffer_end');\n\nfunction atm_output_buffer_start() { \n ob_start(\"atm_output_callback\");\n}\n\nfunction atm_output_buffer_end() { \n ob_get_clean();\n}\n\nfunction atm_output_callback($buffer) {\n if(!is_admin() && !(defined('DOING_AJAX') && DOING_AJAX))\n {\n // Remove type from javascript and CSS\n $buffer = preg_replace( \"%[ ]type=[\\'\\\"]text\\/(javascript|css)[\\'\\\"]%\", '', $buffer );\n // Add alt attribute to images where not exists\n $buffer = preg_replace( '%(<img(?!.*?alt=([\\'\"]).*?\\2)[^>]*?)(/?>)%', '$1 alt=\"\" $3', $buffer );\n $buffer = preg_replace( '%\\s+alt=\"%', ' alt=\"', $buffer );\n // clear HEAD\n $buffer = preg_replace_callback('/(?=<head(.*?)>)(.*?)(?<=<\\/head>)/s',\n function($matches) {\n return preg_replace(array(\n '/<!--(?!\\s*(?:\\[if [^\\]]+]|<!|>))(?:(?!-->).)*-->/s', // delete HTML comments\n /* Fix HTML */\n '/\\>[^\\S ]+/s', // strip whitespaces after tags, except space\n '/[^\\S ]+\\</s', // strip whitespaces before tags, except space\n '/\\>\\s+\\</', // strip whitespaces between tags\n ), array(\n '',\n /* Fix HTML */\n '>', // strip whitespaces after tags, except space\n '<', // strip whitespaces before tags, except space\n '><', // strip whitespaces between tags\n ), $matches[2]);\n }, $buffer);\n // clear BODY\n $buffer = preg_replace_callback('/(?=<body(.*?)>)(.*?)(?<=<\\/body>)/s',\n function($matches) {\n return preg_replace(array(\n '/<!--(?!\\s*(?:\\[if [^\\]]+]|<!|>))(?:(?!-->).)*-->/s', // delete HTML comments\n /* Fix HTML */\n '/\\>[^\\S ]+/s', // strip whitespaces after tags, except space\n '/[^\\S ]+\\</s', // strip whitespaces before tags, except space\n '/\\>\\s+\\</', // strip whitespaces between tags\n ), array(\n '', // delete HTML comments\n /* Fix HTML */\n '>', // strip whitespaces after tags, except space\n '<', // strip whitespaces before tags, except space\n '> <', // strip whitespaces between tags\n ), $matches[2]);\n }, $buffer);\n $buffer = preg_replace_callback('/(?=<script(.*?)>)(.*?)(?<=<\\/script>)/s',\n function($matches) {\n return preg_replace(array(\n '@\\/\\*(.*?)\\*\\/@s', // delete JavaScript comments\n '@((^|\\t|\\s|\\r)\\/{2,}.+?(\\n|$))@s', // delete JavaScript comments\n '@(\\}(\\n|\\s+)else(\\n|\\s+)\\{)@s', // fix \"else\" statemant\n '@((\\)\\{)|(\\)(\\n|\\s+)\\{))@s', // fix brackets position\n //'@(\\}\\)(\\t+|\\s+|\\n+))@s', // fix closed functions\n '@(\\}(\\n+|\\t+|\\s+)else\\sif(\\s+|)\\()@s', // fix \"else if\"\n '@(if|for|while|switch|function)\\(@s', // fix \"if, for, while, switch, function\"\n '@\\s+(\\={1,3}|\\:)\\s+@s', // fix \" = and : \"\n '@\\$\\((.*?)\\)@s', // fix $( )\n '@(if|while)\\s\\((.*?)\\)\\s\\{@s', // fix \"if|while ( ) {\"\n '@function\\s\\(\\s+\\)\\s{@s', // fix \"function ( ) {\"\n '@(\\n{2,})@s', // fix multi new lines\n '@([\\r\\n\\s\\t]+)(,)@s', // Fix comma\n '@([\\r\\n\\s\\t]+)?([;,{}()]+)([\\r\\n\\s\\t]+)?@', // Put all inline\n ), array(\n \"\\n\", // delete JavaScript comments\n \"\\n\", // delete JavaScript comments\n '}else{', // fix \"else\" statemant\n '){', // fix brackets position\n //\"});\\n\", // fix closed functions\n '}else if(', // fix \"else if\"\n \"$1(\", // fix \"if, for, while, switch, function\"\n \" $1 \", // fix \" = and : \"\n '$'.\"($1)\", // fix $( )\n \"$1 ($2) {\", // fix \"if|while ( ) {\"\n 'function(){', // fix \"function ( ) {\"\n \"\\n\", // fix multi new lines\n ',', // fix comma\n \"$2\", // Put all inline\n ), $matches[2]);\n }, $buffer);\n // Clear CSS\n $buffer = preg_replace_callback('/(?=<style(.*?)>)(.*?)(?<=<\\/style>)/s',\n function($matches) {\n return preg_replace(array(\n '/([.#]?)([a-zA-Z0-9,_-]|\\)|\\])([\\s|\\t|\\n|\\r]+)?{([\\s|\\t|\\n|\\r]+)(.*?)([\\s|\\t|\\n|\\r]+)}([\\s|\\t|\\n|\\r]+)/s', // Clear brackets and whitespaces\n '/([0-9a-zA-Z]+)([;,])([\\s|\\t|\\n|\\r]+)?/s', // Let's fix ,;\n '@([\\r\\n\\s\\t]+)?([;:,{}()]+)([\\r\\n\\s\\t]+)?@', // Put all inline\n ), array(\n '$1$2{$5} ', // Clear brackets and whitespaces\n '$1$2', // Let's fix ,;\n \"$2\", // Put all inline\n ), $matches[2]);\n }, $buffer);\n\n // Clean between HEAD and BODY\n $buffer = preg_replace( \"%</head>([\\s\\t\\n\\r]+)<body%\", '</head><body', $buffer );\n // Clean between BODY and HTML\n $buffer = preg_replace( \"%</body>([\\s\\t\\n\\r]+)</html>%\", '</body></html>', $buffer );\n // Clean between HTML and HEAD\n $buffer = preg_replace( \"%<html(.*?)>([\\s\\t\\n\\r]+)<head%\", '<html$1><head', $buffer );\n }\n\n return $buffer;\n}\n</code></pre>\n\n<p>For CDN read <strong><a href=\"http://www.shoutmeloud.com/how-to-serve-images-from-a-sub-domain-wordpress.html\" rel=\"nofollow noreferrer\">THIS</a></strong> article. </p>\n"
}
] |
2016/05/26
|
[
"https://wordpress.stackexchange.com/questions/227875",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81543/"
] |
I am currently working on an entertainment website and I am having issues with page load time. I would love to know if there is any method I can use to remove blank spaces from PHP, JS , CSS scripts running via the website.
As I believe this will reduce load time efficiently. Also please any pointers to how can I significantly reduce page load time. I am currently using Cloudflare CDN nameservers.
|
I write one php code what totaly filter all html elements but is integrated in main index.php on the root. That made rendering a little faster but you also can do CDN for all your images and media. That will speedup your page a mutch better. I normaly point `/wp-content/uploads/` to subdomain and my WP get all media from that subdomain what made WP 20 times faster.
**UPDATE**
I made one great regex what can work inside buffer. Copy/Paste this script in your theme `functions.php` and see magic.
>
> NOTE: If your source contain bad javascript or css what's not follow
> rules, this may broke website. But I use it on arround 100 templates,
> I never experience some issue. Work nice With Elementor and WC Builder
>
>
>
```
/* ----------------------------------------------------------------------------
W3C Fix and HTML minifier by Ivijan-Stefan Stipic <[email protected]>
---------------------------------------------------------------------------- */
add_action('wp_loaded', 'atm_output_buffer_start');
add_action('shutdown', 'atm_output_buffer_end');
function atm_output_buffer_start() {
ob_start("atm_output_callback");
}
function atm_output_buffer_end() {
ob_get_clean();
}
function atm_output_callback($buffer) {
if(!is_admin() && !(defined('DOING_AJAX') && DOING_AJAX))
{
// Remove type from javascript and CSS
$buffer = preg_replace( "%[ ]type=[\'\"]text\/(javascript|css)[\'\"]%", '', $buffer );
// Add alt attribute to images where not exists
$buffer = preg_replace( '%(<img(?!.*?alt=([\'"]).*?\2)[^>]*?)(/?>)%', '$1 alt="" $3', $buffer );
$buffer = preg_replace( '%\s+alt="%', ' alt="', $buffer );
// clear HEAD
$buffer = preg_replace_callback('/(?=<head(.*?)>)(.*?)(?<=<\/head>)/s',
function($matches) {
return preg_replace(array(
'/<!--(?!\s*(?:\[if [^\]]+]|<!|>))(?:(?!-->).)*-->/s', // delete HTML comments
/* Fix HTML */
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/\>\s+\</', // strip whitespaces between tags
), array(
'',
/* Fix HTML */
'>', // strip whitespaces after tags, except space
'<', // strip whitespaces before tags, except space
'><', // strip whitespaces between tags
), $matches[2]);
}, $buffer);
// clear BODY
$buffer = preg_replace_callback('/(?=<body(.*?)>)(.*?)(?<=<\/body>)/s',
function($matches) {
return preg_replace(array(
'/<!--(?!\s*(?:\[if [^\]]+]|<!|>))(?:(?!-->).)*-->/s', // delete HTML comments
/* Fix HTML */
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/\>\s+\</', // strip whitespaces between tags
), array(
'', // delete HTML comments
/* Fix HTML */
'>', // strip whitespaces after tags, except space
'<', // strip whitespaces before tags, except space
'> <', // strip whitespaces between tags
), $matches[2]);
}, $buffer);
$buffer = preg_replace_callback('/(?=<script(.*?)>)(.*?)(?<=<\/script>)/s',
function($matches) {
return preg_replace(array(
'@\/\*(.*?)\*\/@s', // delete JavaScript comments
'@((^|\t|\s|\r)\/{2,}.+?(\n|$))@s', // delete JavaScript comments
'@(\}(\n|\s+)else(\n|\s+)\{)@s', // fix "else" statemant
'@((\)\{)|(\)(\n|\s+)\{))@s', // fix brackets position
//'@(\}\)(\t+|\s+|\n+))@s', // fix closed functions
'@(\}(\n+|\t+|\s+)else\sif(\s+|)\()@s', // fix "else if"
'@(if|for|while|switch|function)\(@s', // fix "if, for, while, switch, function"
'@\s+(\={1,3}|\:)\s+@s', // fix " = and : "
'@\$\((.*?)\)@s', // fix $( )
'@(if|while)\s\((.*?)\)\s\{@s', // fix "if|while ( ) {"
'@function\s\(\s+\)\s{@s', // fix "function ( ) {"
'@(\n{2,})@s', // fix multi new lines
'@([\r\n\s\t]+)(,)@s', // Fix comma
'@([\r\n\s\t]+)?([;,{}()]+)([\r\n\s\t]+)?@', // Put all inline
), array(
"\n", // delete JavaScript comments
"\n", // delete JavaScript comments
'}else{', // fix "else" statemant
'){', // fix brackets position
//"});\n", // fix closed functions
'}else if(', // fix "else if"
"$1(", // fix "if, for, while, switch, function"
" $1 ", // fix " = and : "
'$'."($1)", // fix $( )
"$1 ($2) {", // fix "if|while ( ) {"
'function(){', // fix "function ( ) {"
"\n", // fix multi new lines
',', // fix comma
"$2", // Put all inline
), $matches[2]);
}, $buffer);
// Clear CSS
$buffer = preg_replace_callback('/(?=<style(.*?)>)(.*?)(?<=<\/style>)/s',
function($matches) {
return preg_replace(array(
'/([.#]?)([a-zA-Z0-9,_-]|\)|\])([\s|\t|\n|\r]+)?{([\s|\t|\n|\r]+)(.*?)([\s|\t|\n|\r]+)}([\s|\t|\n|\r]+)/s', // Clear brackets and whitespaces
'/([0-9a-zA-Z]+)([;,])([\s|\t|\n|\r]+)?/s', // Let's fix ,;
'@([\r\n\s\t]+)?([;:,{}()]+)([\r\n\s\t]+)?@', // Put all inline
), array(
'$1$2{$5} ', // Clear brackets and whitespaces
'$1$2', // Let's fix ,;
"$2", // Put all inline
), $matches[2]);
}, $buffer);
// Clean between HEAD and BODY
$buffer = preg_replace( "%</head>([\s\t\n\r]+)<body%", '</head><body', $buffer );
// Clean between BODY and HTML
$buffer = preg_replace( "%</body>([\s\t\n\r]+)</html>%", '</body></html>', $buffer );
// Clean between HTML and HEAD
$buffer = preg_replace( "%<html(.*?)>([\s\t\n\r]+)<head%", '<html$1><head', $buffer );
}
return $buffer;
}
```
For CDN read **[THIS](http://www.shoutmeloud.com/how-to-serve-images-from-a-sub-domain-wordpress.html)** article.
|
227,882 |
<p>Can I just get everyone's ok that using shortcodes embedded within templates is the 'correct' thing to do? I've tested them and they work just fine - but I just wanted everyone's thoughts. Thanks</p>
<p>Here's an example:</p>
<pre><code><?php echo do_shortcode('[course_complete]'); ?>
</code></pre>
|
[
{
"answer_id": 227884,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 1,
"selected": false,
"text": "<p>A shortcode is a placeholder for a PHP callback. As placeholder, it is intended to be used where PHP can not be used directly.</p>\n\n<p>Additionally, <code>do_shortcode()</code> will do a regex in the passed string looking for all registered shortcodes, which is not appropiate from a performance point of view if you just want to execute one shortocode, not to look for all shortcodes in a string.</p>\n\n<p>So, there is almost no reason to use <code>do_shortcode( '[my_shortcode]' )</code> in a template file; it is more appropiate to use the callback instead of the placeholder.</p>\n\n<p>However, it is OK to use <code>do_shortcode()</code> to parse strings or to filter content that may contain shortcodes that you want to be executed, but again a template file may be not the correct place to parse strings or filter content. For example, you may want to filter Text Widget content and allow shortcodes in it:</p>\n\n<pre><code>add_filter( 'widget_text', 'do_shortcode' );\n</code></pre>\n\n<p><code>do_shortcode()</code> can be also useful when you need the functionality of a shortcode, no matter the exact output you get or what callback it is used, you need the functionality.</p>\n\n<p>For example, a plugin/theme could redefine a shortcode, for example the gallery shortcode:</p>\n\n<pre><code>remove_shortcode( 'gallery', 'gallery_shortcode' );\nadd_shortcode( 'gallery', 'my_gallery_shortcode' );\n</code></pre>\n\n<p>In this case, if you need the gallery functionality, not the specific output of callback, using <code>do_shortcode( '[gallery]' )</code> within a theme could be justified. But no one should redeclare the gallery shortcode, instead <a href=\"https://developer.wordpress.org/reference/hooks/post_gallery/\" rel=\"nofollow\"><code>post_gallery</code> filter</a> should be used to modify the gallery shortcode output. So, the use of <code>do_shortcode('[gallery]')</code> would be a very edge use case.</p>\n\n<p>Same argument applies to any shortcode and the use of <code>do_shortcode()</code> is a very edge case in general.</p>\n"
},
{
"answer_id": 227916,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>Shortcodes done that way is a less sinister relative of <code>eval</code>. It is ok if you intend to give a user an option but not an acceptable coding practice. </p>\n\n<p>When activating a function that way you lose three things</p>\n\n<ol>\n<li><p>Code readability. What is exactly you intended to do there? I will not be able to guess it without looking at the implementation of the shortcode which no tool will help me to find.</p></li>\n<li><p>Predictability. What happens when the shortcode attributes are changed in a new version? What happens when the short code itself is just doing something totally else than you expect? When you call a function directly you are likely to get errors that will prompt your attention to incompatible changes in the interface but using a shortcode you will just not know before users complain.</p></li>\n<li><p>Testability. Follows from the second point but worth to emphasize it. How are you going to test your code when you don't actually know what supposed to happen?</p></li>\n</ol>\n\n<p>If you are specifically looking for flexibility, It seems to me that a better approach is to create your own action hook and let people hook on it. You can supply what ever implementations of the hook you feel are useful, and people will be able to change it if they will want to. The point here is that the intention of the hook as a means to \"something random can go here\" is more explicit then using a shortcode.</p>\n"
},
{
"answer_id": 227953,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": false,
"text": "<h2>Is it Ok?</h2>\n\n<p>Yes!</p>\n\n<h2>Is it Optimal?</h2>\n\n<p>No</p>\n\n<h2>What Would Be Better?</h2>\n\n<p>Shortcodes map on to PHP functions, so why not cut out the middle man and go straight to the original function?</p>\n\n<h2>Are there any other downsides?</h2>\n\n<p>Yes!</p>\n\n<p>That shortcode had to come from somewhere, now you have a dependency, maybe the plugin that has the shortcode gets deactivated, who knows</p>\n\n<h2>Are There Any Upsides?</h2>\n\n<p>Yes! It's much easier to build a gallery shortcode programmatically then pass it into <code>do_shortcode</code> than it is to create one from scratch.</p>\n\n<p>Even if you do bypass the shortcode and go straight to the original function, you still have the same problem mentioned above. If the shortcode doesn't exist, it'll degrade gracefully back to an empty string. You can use the shortcode inside post content too</p>\n\n<h2>So, best to use shotcodes ONLY in widgets + pages + posts?</h2>\n\n<p>Is it <strong>Ok</strong>? Yes! But is it the <strong>best</strong>? Probably not</p>\n\n<p>Shortcodes are awesome! But remember their purpose, if you need to put stuff in a template, you don't need to use a shortcode, but if needs must, that option's always there. The <code>do_shortcode</code> function is just a tool, and they're for embedding things in content, don't go using it as the foundations for your site or framework. I've built plenty of sites, and I've not had to do this</p>\n"
}
] |
2016/05/26
|
[
"https://wordpress.stackexchange.com/questions/227882",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93691/"
] |
Can I just get everyone's ok that using shortcodes embedded within templates is the 'correct' thing to do? I've tested them and they work just fine - but I just wanted everyone's thoughts. Thanks
Here's an example:
```
<?php echo do_shortcode('[course_complete]'); ?>
```
|
Is it Ok?
---------
Yes!
Is it Optimal?
--------------
No
What Would Be Better?
---------------------
Shortcodes map on to PHP functions, so why not cut out the middle man and go straight to the original function?
Are there any other downsides?
------------------------------
Yes!
That shortcode had to come from somewhere, now you have a dependency, maybe the plugin that has the shortcode gets deactivated, who knows
Are There Any Upsides?
----------------------
Yes! It's much easier to build a gallery shortcode programmatically then pass it into `do_shortcode` than it is to create one from scratch.
Even if you do bypass the shortcode and go straight to the original function, you still have the same problem mentioned above. If the shortcode doesn't exist, it'll degrade gracefully back to an empty string. You can use the shortcode inside post content too
So, best to use shotcodes ONLY in widgets + pages + posts?
----------------------------------------------------------
Is it **Ok**? Yes! But is it the **best**? Probably not
Shortcodes are awesome! But remember their purpose, if you need to put stuff in a template, you don't need to use a shortcode, but if needs must, that option's always there. The `do_shortcode` function is just a tool, and they're for embedding things in content, don't go using it as the foundations for your site or framework. I've built plenty of sites, and I've not had to do this
|
227,892 |
<p>I have created a custom post type <code>portfolio_posts</code> using the CPT UI plugin. Using the same plugin, I have created a taxonomy <code>portfolio_category</code>. I have made multiple entries under this taxonomy.</p>
<p>I want to list all the entries under <code>portfolio_category</code>, but all I'm getting is an empty array.</p>
<p>Here's what I've tried: </p>
<pre><code>$args = array(
'taxonomy' => 'portfolio_category'
);
$taxonomy = get_categories ($args);
echo '<pre>';
print_r($taxonomy);
exit;
</code></pre>
<p>When I replace <code>portfolio_category</code> with <code>category</code> I am successfully getting all the entries under <code>category</code>.</p>
<p>What am I missing here?</p>
<p><a href="https://i.stack.imgur.com/HYFB5.png" rel="nofollow noreferrer">Here is a screenshot of the entries under portfolio_category</a> and below is an example of how they are saved in the <code>wp_term_taxonomy</code> table.</p>
<p><a href="https://i.stack.imgur.com/P0FdQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P0FdQ.png" alt="How they are saved in wp_term_taxonomy table"></a></p>
|
[
{
"answer_id": 227898,
"author": "umair.ashfr",
"author_id": 93354,
"author_profile": "https://wordpress.stackexchange.com/users/93354",
"pm_score": 3,
"selected": true,
"text": "<p>Here is how i did it </p>\n\n<pre><code>$taxonomy = get_terms('portfolio_category', array( 'hide_empty' => 0 ));\n</code></pre>\n\n<p>i am able get all the items under portfolio_category.</p>\n"
},
{
"answer_id": 227902,
"author": "Baba",
"author_id": 74538,
"author_profile": "https://wordpress.stackexchange.com/users/74538",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$terms = get_the_terms( $post->ID , 'yourtaxonomyhere' ); \n\nforeach ( $terms as $term ) {\n\n $term_link = get_term_link( $term, 'yourtaxonomyhere' );\n\n if ( is_wp_error( $term_link ) )\n continue;\n\n echo '<a href=\"' . $term_link . '\">' . $term->name . '</a>';\n\n} \n</code></pre>\n"
}
] |
2016/05/26
|
[
"https://wordpress.stackexchange.com/questions/227892",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93354/"
] |
I have created a custom post type `portfolio_posts` using the CPT UI plugin. Using the same plugin, I have created a taxonomy `portfolio_category`. I have made multiple entries under this taxonomy.
I want to list all the entries under `portfolio_category`, but all I'm getting is an empty array.
Here's what I've tried:
```
$args = array(
'taxonomy' => 'portfolio_category'
);
$taxonomy = get_categories ($args);
echo '<pre>';
print_r($taxonomy);
exit;
```
When I replace `portfolio_category` with `category` I am successfully getting all the entries under `category`.
What am I missing here?
[Here is a screenshot of the entries under portfolio\_category](https://i.stack.imgur.com/HYFB5.png) and below is an example of how they are saved in the `wp_term_taxonomy` table.
[](https://i.stack.imgur.com/P0FdQ.png)
|
Here is how i did it
```
$taxonomy = get_terms('portfolio_category', array( 'hide_empty' => 0 ));
```
i am able get all the items under portfolio\_category.
|
227,905 |
<p>I have created a custom post type "brochures" which i am currently displaying with the code below (using ACF to display the brochure file).<br>
At the moment this displays all the brochures individually.<br></p>
<p>I have set up a custom taxonomy for this post type called "brochure_categories" so that i can categories the brochures into separate folders like the below.<br></p>
<p><strong>Brochure Category 1</strong><br>
Brochure 1<br>
Brochure 2<br>
<br>
<strong>Brochure Category 2</strong><br>
Brochure 3<br>
Brochure 4<br>
<br>
<strong>Brochure Category 3</strong><br>
Brochure 5<br>
Brochure 6<br></p>
<p>Rather displaying all the posts (like im doing with the code below), i want to display all of the brochure categories, and when a category is clicked it then displays the posts within that category.<br></p>
<p>How am i able to achieve this?</p>
<pre><code><ul class="brochures">
<?php
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query();
$wp_query->query('showposts=18&orderby=title&order=ASC&post_type=brochures'.'&paged='.$paged);
while ($wp_query->have_posts()) : $wp_query->the_post();
?>
<li><a target="_blank" href="<?php the_field('brochure_file'); ?>"><img src="<?php the_field('brochure_logo'); ?>"><h3><?php echo get_the_title(); ?></h3><h4>Click to view</h4></a>
</li>
<?php endwhile; ?>
<nav class="nextPrev">
<div class="prev"><?php previous_posts_link('&laquo; Previous') ?></div>
<div class="next"><?php next_posts_link('Next &raquo;') ?></div>
</nav>
<?php
$wp_query = null;
$wp_query = $temp; // Reset
?>
</ul>
</code></pre>
|
[
{
"answer_id": 227898,
"author": "umair.ashfr",
"author_id": 93354,
"author_profile": "https://wordpress.stackexchange.com/users/93354",
"pm_score": 3,
"selected": true,
"text": "<p>Here is how i did it </p>\n\n<pre><code>$taxonomy = get_terms('portfolio_category', array( 'hide_empty' => 0 ));\n</code></pre>\n\n<p>i am able get all the items under portfolio_category.</p>\n"
},
{
"answer_id": 227902,
"author": "Baba",
"author_id": 74538,
"author_profile": "https://wordpress.stackexchange.com/users/74538",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$terms = get_the_terms( $post->ID , 'yourtaxonomyhere' ); \n\nforeach ( $terms as $term ) {\n\n $term_link = get_term_link( $term, 'yourtaxonomyhere' );\n\n if ( is_wp_error( $term_link ) )\n continue;\n\n echo '<a href=\"' . $term_link . '\">' . $term->name . '</a>';\n\n} \n</code></pre>\n"
}
] |
2016/05/26
|
[
"https://wordpress.stackexchange.com/questions/227905",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91405/"
] |
I have created a custom post type "brochures" which i am currently displaying with the code below (using ACF to display the brochure file).
At the moment this displays all the brochures individually.
I have set up a custom taxonomy for this post type called "brochure\_categories" so that i can categories the brochures into separate folders like the below.
**Brochure Category 1**
Brochure 1
Brochure 2
**Brochure Category 2**
Brochure 3
Brochure 4
**Brochure Category 3**
Brochure 5
Brochure 6
Rather displaying all the posts (like im doing with the code below), i want to display all of the brochure categories, and when a category is clicked it then displays the posts within that category.
How am i able to achieve this?
```
<ul class="brochures">
<?php
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query();
$wp_query->query('showposts=18&orderby=title&order=ASC&post_type=brochures'.'&paged='.$paged);
while ($wp_query->have_posts()) : $wp_query->the_post();
?>
<li><a target="_blank" href="<?php the_field('brochure_file'); ?>"><img src="<?php the_field('brochure_logo'); ?>"><h3><?php echo get_the_title(); ?></h3><h4>Click to view</h4></a>
</li>
<?php endwhile; ?>
<nav class="nextPrev">
<div class="prev"><?php previous_posts_link('« Previous') ?></div>
<div class="next"><?php next_posts_link('Next »') ?></div>
</nav>
<?php
$wp_query = null;
$wp_query = $temp; // Reset
?>
</ul>
```
|
Here is how i did it
```
$taxonomy = get_terms('portfolio_category', array( 'hide_empty' => 0 ));
```
i am able get all the items under portfolio\_category.
|
227,946 |
<p>I'm using this plugin to add tags for a page:
<a href="http://wordpress.org/extend/plugins/post-tags-and-categories-for-pages/" rel="nofollow">http://wordpress.org/extend/plugins/post-tags-and-categories-for-pages/</a></p>
<p>And I've added tags support for the custom post:</p>
<pre><code>function codex_custom_init() {
$args = array(
'public' => true,
'has_archive' => true,
'label' => 'Doing',
'taxonomies' => array('post_tag'),
'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt')
);
register_post_type( 'doing', $args );
}
add_action( 'init', 'codex_custom_init' );
</code></pre>
<p>In every page with an specific tag I want to display related custom posts that have the same tag as the page, is this possible to do? How can I get to load on the page the tag related custom posts?</p>
<p>I've tried with this code but is not showing any related post:</p>
<pre><code> <?php
$tags = wp_get_post_tags($post->ID);
if ($tags) {
echo 'Related Posts';
$first_tag = $tags[0]->term_id;
$args=array(
'tag__in' => array($first_tag),
'post__not_in' => array($post->ID),
'posts_per_page'=>5,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
<?php
endwhile;
}
wp_reset_query();
}
?>
</code></pre>
|
[
{
"answer_id": 227948,
"author": "Gareth Gillman",
"author_id": 33936,
"author_profile": "https://wordpress.stackexchange.com/users/33936",
"pm_score": 2,
"selected": false,
"text": "<p>My first port of call is to call <code>global $post;</code> - as that sets you up to use <code>$post->ID</code> ... if you are using it then the next step is to display each part separately e.g.</p>\n\n<pre><code>print_r($tags);\n\necho $first_tag;\n</code></pre>\n\n<p>see what's displayed in each part, this will help diagnose where the issue is, as without seeing your code working, we can't say why it's not working.</p>\n"
},
{
"answer_id": 228235,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>You need to specify a post type in your <code>WP_Query</code> arguments when you need to query any other post type accept the build in post type <code>post</code>.</p>\n\n<p>By default, <code>post_type</code> is set to <code>post</code>, so when no specific post type is set manually by the user, <code>WP_Query</code> will query posts from the post type <code>post</code></p>\n\n<p>Additionally, <code>caller_get_posts</code> have been deprecated for a very very long time now. If you had debug turned on, you would have recieved a deprecation notice about this. The correct arguments to use is <code>ignore_sticky_posts</code>.</p>\n\n<p>I would also not use the <code>$post</code> global as it is unreliable, for reliability, rather use <code>$GLOBALS['wp_the_query']->get_queried_object()</code>. You can read up on this subject in <a href=\"https://wordpress.stackexchange.com/a/220624/31545\">my answer here</a></p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_the_tags/\" rel=\"nofollow noreferrer\"><code>get_the_tags()</code></a> is also faster than <code>wp_get_post_tags()</code> as the latter requires an extra db call. </p>\n\n<p>One last note, <code>wp_reset_query()</code> is used with <code>query_posts</code>, the correct function to use with <code>WP_Query</code> is <code>wp_reset_postdata()</code></p>\n\n<p>In essence, you can try the following</p>\n\n<pre><code>$post_id = $GLOBALS['wp_the_query']->get_queried_object_id();\n$tags = get_the_tags( $post_id );\nif ( $tags\n && !is_wp_error( $tags ) \n) {\n $args = [\n 'post__not_in' => [$post_id],\n 'post_type' => 'doing',\n 'tag__in' => [$tags[0]->term_id],\n // Rest of your args\n ];\n $my_query = new WP_Query( $args );\n\n // Your loop\n\n wp_reset_postdata();\n}\n</code></pre>\n"
}
] |
2016/05/26
|
[
"https://wordpress.stackexchange.com/questions/227946",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22933/"
] |
I'm using this plugin to add tags for a page:
<http://wordpress.org/extend/plugins/post-tags-and-categories-for-pages/>
And I've added tags support for the custom post:
```
function codex_custom_init() {
$args = array(
'public' => true,
'has_archive' => true,
'label' => 'Doing',
'taxonomies' => array('post_tag'),
'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt')
);
register_post_type( 'doing', $args );
}
add_action( 'init', 'codex_custom_init' );
```
In every page with an specific tag I want to display related custom posts that have the same tag as the page, is this possible to do? How can I get to load on the page the tag related custom posts?
I've tried with this code but is not showing any related post:
```
<?php
$tags = wp_get_post_tags($post->ID);
if ($tags) {
echo 'Related Posts';
$first_tag = $tags[0]->term_id;
$args=array(
'tag__in' => array($first_tag),
'post__not_in' => array($post->ID),
'posts_per_page'=>5,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
<?php
endwhile;
}
wp_reset_query();
}
?>
```
|
You need to specify a post type in your `WP_Query` arguments when you need to query any other post type accept the build in post type `post`.
By default, `post_type` is set to `post`, so when no specific post type is set manually by the user, `WP_Query` will query posts from the post type `post`
Additionally, `caller_get_posts` have been deprecated for a very very long time now. If you had debug turned on, you would have recieved a deprecation notice about this. The correct arguments to use is `ignore_sticky_posts`.
I would also not use the `$post` global as it is unreliable, for reliability, rather use `$GLOBALS['wp_the_query']->get_queried_object()`. You can read up on this subject in [my answer here](https://wordpress.stackexchange.com/a/220624/31545)
[`get_the_tags()`](https://developer.wordpress.org/reference/functions/get_the_tags/) is also faster than `wp_get_post_tags()` as the latter requires an extra db call.
One last note, `wp_reset_query()` is used with `query_posts`, the correct function to use with `WP_Query` is `wp_reset_postdata()`
In essence, you can try the following
```
$post_id = $GLOBALS['wp_the_query']->get_queried_object_id();
$tags = get_the_tags( $post_id );
if ( $tags
&& !is_wp_error( $tags )
) {
$args = [
'post__not_in' => [$post_id],
'post_type' => 'doing',
'tag__in' => [$tags[0]->term_id],
// Rest of your args
];
$my_query = new WP_Query( $args );
// Your loop
wp_reset_postdata();
}
```
|
227,972 |
<p>I have a custom page template with a form, that any visitor of the website can upload a file. Now, I want to restrict the file type that will be upload (docx, doc and pdf only) and I limit the file size into 2MB only.</p>
<p>How to do this? I already have a function that the user allowed to upload, but I don't know how to restrict the file type that allowed to be upload. Please help me.</p>
<p>I tried to change</p>
<p><code>'post_mime_type' => $file_return['type']</code></p>
<p>into this</p>
<p><code>'post_mime_type' => 'application/msword,vnd.openxmlformats-officedocument.wordprocessingml.document,pdf'</code></p>
<p>but still it's not working.</p>
<p>PHP in custom page template</p>
<pre><code>if(isset($_POST['submit'])){
$firstName = isset($_POST['firstName']) ? $_POST['firstName'] : '';
$middleName = isset($_POST['middleName']) ? $_POST['middleName'] : '';
$lastName = isset($_POST['lastName']) ? $_POST['lastName'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$mobile = isset($_POST['mobile']) ? $_POST['mobile'] : '';
$locations = isset($_POST['locations_list']) ? $_POST['locations_list'] : '';
$position = isset($_POST['position']) ? $_POST['position'] : '';
$message = isset($_POST['message']) ? $_POST['message'] : '';
if( ! empty($_FILES)){
$file=$_FILES['resumeFile'];
$attachment_id = upload_user_file($file);
}
$sql=$wpdb->query($wpdb->prepare("INSERT INTO resume_databank(submit_time,last_name,first_name,middle_name,mobile_number,email,location,position,message,process_resume,attachment_resume_id) VALUES (now(),'$lastName','$firstName','$middleName','$mobile','$email','$locations','$position','$message','No','$attachment_id')"));
}
</code></pre>
<p>PHP in functions.php</p>
<pre><code>function upload_user_file($file = array()){
require_once(ABSPATH . 'wp-admin/includes/admin.php');
$file_return = wp_handle_upload($file, array('test_form' => false));
if(isset($file_return['error']) || isset($file_return['upload_error_handler'])){
return false;
} else {
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment($attachment, $file_return['url']);
require_once(ABSPATH . 'wp-admin/includes/file.php');
$attachment_data = wp_generate_attachment_metadata($attachment_id, $filename);
wp_update_attachment_metadata($attachment_id, $attachment_data);
if(0 < intval($attachment_id)){
return $attachment_id;
}
}
return false;
}
</code></pre>
|
[
{
"answer_id": 227979,
"author": "iyass.si",
"author_id": 94652,
"author_profile": "https://wordpress.stackexchange.com/users/94652",
"pm_score": 0,
"selected": false,
"text": "<p>You simply add an if statement like :</p>\n\n<pre>\n if ( $file[\"type\"] != \"application/pdf\" ){\n exit;\n }\n</pre>\n\n<p>You can add a message in $_SESSION and redirect the url to show for user what is wrong </p>\n\n<pre>\nif(session_id() == '') {\n session_start();\n}\n$_SESSION['error_uplaod'] = '.pdf with 2MB maxsize files is only allowed';\nsession_write_close();\nwp_redirect( $_SERVER[\"REQUEST_URI\"] );\n</pre>\n\n<hr>\n\n<p>in other way if you want to use $mimes :</p>\n\n<pre>\nfunction your_mimes($mimes) {\n $mimes = array('pdf' => 'application/pdf');\n return $mimes;\n}\n</pre>\n\n<p>you can see list of all types : <a href=\"http://www.iana.org/assignments/media-types/media-types.xhtml\" rel=\"nofollow\">here</a>\nthen just before and after the upload method add : </p>\n\n<pre>\nadd_filter('upload_mimes','your_mimes');\n</pre>\n\n<p>and :</p>\n\n<pre>\nremove_filter('upload_mimes','your_mimes');\n</pre>\n\n<p>if you leaved that with out remove it then thats will applied for all uploads in site after executing it .<br/>\nHope that help you</p>\n"
},
{
"answer_id": 227981,
"author": "N00b",
"author_id": 80903,
"author_profile": "https://wordpress.stackexchange.com/users/80903",
"pm_score": 1,
"selected": false,
"text": "<p>This is a full working example with file type and size limits and all the error handling. </p>\n\n<p>Every step is commented. Let me know if you have any more questions.</p>\n\n<ul>\n<li>You can find all the mime types from <a href=\"https://www.sitepoint.com/web-foundations/mime-types-summary-list/\" rel=\"nofollow\">here</a>.</li>\n<li>Make sure to check if it's <a href=\"https://codex.wordpress.org/Uploading_Files\" rel=\"nofollow\">allowed</a> in WP too.</li>\n</ul>\n\n<hr>\n\n<pre><code>// Allowed file types -> search online for desired mime types\n$allowed_file_types = array( \"image/jpeg\", \"image/jpg\", \"image/png\" );\n// Allowed file size -> 2MB\n$allowed_file_size = 2000000;\n\n$upload_errors = '';\n\n// Check if has a file -> this assumes your file input \"name\" is \"uploaded-file\"\nif ( ! empty( $_FILES['uploaded-file']['name'] ) ) {\n\n // Check file type\n if ( ! in_array( $_FILES['uploaded-file']['type'], $allowed_file_types ) ) {\n\n $upload_errors .= '<p>Invalid file type: ' . \n $_FILES['uploaded-file']['type'] . \n '. Supported file types: jpg, jpeg, png</p>';\n }\n\n // Check file size\n if ( $_FILES['uploaded-file']['size'] > $allowed_file_size ) {\n\n $upload_errors .= '<p>File is too large. Max. upload file size is 2MB</p>';\n }\n\n // No errors -> upload image\n if ( empty( $upload_errors ) ) {\n\n if ( $_FILES['uploaded-file']['error'] !== UPLOAD_ERR_OK ) __return_false();\n\n require_once( ABSPATH . 'wp-admin/includes/file.php' );\n\n // Upload the file -> if you don't want to attach it to post, pass $post_id as 0\n $upload_id = media_handle_upload( 'uploaded-file', $post_id ); \n\n if ( is_wp_error( $upload_id ) ) {\n\n // Error uploading the file -> show it\n echo '<p>Upload failed. Please submit again</p>';\n } \n else {\n\n // No errors -> show success message\n echo '<p>Upload was successful</p>';\n }\n }\n\n // Had an error -> show error(s) \n else {\n\n echo $upload_errors;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 308514,
"author": "vee",
"author_id": 41315,
"author_profile": "https://wordpress.stackexchange.com/users/41315",
"pm_score": 0,
"selected": false,
"text": "<pre><code>if ($_FILES['myfile']['size'] <= '2000000') {\n // if file size is not larger than 2MB\n $overrides['mimes'] = [\n 'jpg|jpeg|jpe' => 'image/jpeg',\n 'gif' => 'image/gif',\n 'png' => 'image/png',\n ];\n $uploadResult = wp_handle_upload($_FILES['myfile'], $overrides);\n // use $uploadResult to continue working with your code.\n} else {\n // if file size is larger than 2MB.\n // handle with the error below by yourself. it is just example.\n wp_die('Upload file size is too large.');\n}\n</code></pre>\n\n<p>Reference: <a href=\"https://rundiz.com/?p=448\" rel=\"nofollow noreferrer\">https://rundiz.com/?p=448</a></p>\n\n<p>In <code>mimes</code> array key, you can use multiple file extensions but it must be able to use in regular expression.<br>\nFrom my example: <code>jpg|jpeg|jpe</code> means file extension can be one of these the <code>|</code> sign means <strong>OR</strong> and the array value is mime type.</p>\n"
}
] |
2016/05/27
|
[
"https://wordpress.stackexchange.com/questions/227972",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78787/"
] |
I have a custom page template with a form, that any visitor of the website can upload a file. Now, I want to restrict the file type that will be upload (docx, doc and pdf only) and I limit the file size into 2MB only.
How to do this? I already have a function that the user allowed to upload, but I don't know how to restrict the file type that allowed to be upload. Please help me.
I tried to change
`'post_mime_type' => $file_return['type']`
into this
`'post_mime_type' => 'application/msword,vnd.openxmlformats-officedocument.wordprocessingml.document,pdf'`
but still it's not working.
PHP in custom page template
```
if(isset($_POST['submit'])){
$firstName = isset($_POST['firstName']) ? $_POST['firstName'] : '';
$middleName = isset($_POST['middleName']) ? $_POST['middleName'] : '';
$lastName = isset($_POST['lastName']) ? $_POST['lastName'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$mobile = isset($_POST['mobile']) ? $_POST['mobile'] : '';
$locations = isset($_POST['locations_list']) ? $_POST['locations_list'] : '';
$position = isset($_POST['position']) ? $_POST['position'] : '';
$message = isset($_POST['message']) ? $_POST['message'] : '';
if( ! empty($_FILES)){
$file=$_FILES['resumeFile'];
$attachment_id = upload_user_file($file);
}
$sql=$wpdb->query($wpdb->prepare("INSERT INTO resume_databank(submit_time,last_name,first_name,middle_name,mobile_number,email,location,position,message,process_resume,attachment_resume_id) VALUES (now(),'$lastName','$firstName','$middleName','$mobile','$email','$locations','$position','$message','No','$attachment_id')"));
}
```
PHP in functions.php
```
function upload_user_file($file = array()){
require_once(ABSPATH . 'wp-admin/includes/admin.php');
$file_return = wp_handle_upload($file, array('test_form' => false));
if(isset($file_return['error']) || isset($file_return['upload_error_handler'])){
return false;
} else {
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment($attachment, $file_return['url']);
require_once(ABSPATH . 'wp-admin/includes/file.php');
$attachment_data = wp_generate_attachment_metadata($attachment_id, $filename);
wp_update_attachment_metadata($attachment_id, $attachment_data);
if(0 < intval($attachment_id)){
return $attachment_id;
}
}
return false;
}
```
|
This is a full working example with file type and size limits and all the error handling.
Every step is commented. Let me know if you have any more questions.
* You can find all the mime types from [here](https://www.sitepoint.com/web-foundations/mime-types-summary-list/).
* Make sure to check if it's [allowed](https://codex.wordpress.org/Uploading_Files) in WP too.
---
```
// Allowed file types -> search online for desired mime types
$allowed_file_types = array( "image/jpeg", "image/jpg", "image/png" );
// Allowed file size -> 2MB
$allowed_file_size = 2000000;
$upload_errors = '';
// Check if has a file -> this assumes your file input "name" is "uploaded-file"
if ( ! empty( $_FILES['uploaded-file']['name'] ) ) {
// Check file type
if ( ! in_array( $_FILES['uploaded-file']['type'], $allowed_file_types ) ) {
$upload_errors .= '<p>Invalid file type: ' .
$_FILES['uploaded-file']['type'] .
'. Supported file types: jpg, jpeg, png</p>';
}
// Check file size
if ( $_FILES['uploaded-file']['size'] > $allowed_file_size ) {
$upload_errors .= '<p>File is too large. Max. upload file size is 2MB</p>';
}
// No errors -> upload image
if ( empty( $upload_errors ) ) {
if ( $_FILES['uploaded-file']['error'] !== UPLOAD_ERR_OK ) __return_false();
require_once( ABSPATH . 'wp-admin/includes/file.php' );
// Upload the file -> if you don't want to attach it to post, pass $post_id as 0
$upload_id = media_handle_upload( 'uploaded-file', $post_id );
if ( is_wp_error( $upload_id ) ) {
// Error uploading the file -> show it
echo '<p>Upload failed. Please submit again</p>';
}
else {
// No errors -> show success message
echo '<p>Upload was successful</p>';
}
}
// Had an error -> show error(s)
else {
echo $upload_errors;
}
}
```
|
227,989 |
<p>I'm trying to display a list of all my custom taxonomy terms with an image field that I have created in ACF. The ACF image field I have is <code><img src="<?php the_field('brochure_logo'); ?>"></code>, but how can I display that image in my code below? I have left a gap where the field needs to go, but I can't seem to output the image URL.</p>
<pre><code>$taxonomy = 'brochure_categories';
$tax_terms = get_terms( $taxonomy );
?>
<ul class="downloadGrid">
<?php
foreach ( $tax_terms as $tax_term ) {
echo '<li>';
echo '<a href="' . esc_attr( get_term_link( $tax_term, $taxonomy ) ) .
'" title="' . sprintf( __( "View all posts in %s" ), $tax_term->name ) .
'" ' . '>';
echo '<img src=" " >';
echo $tax_term->name;
echo '</a>';
echo '</li>';
}
</code></pre>
|
[
{
"answer_id": 227990,
"author": "windyjonas",
"author_id": 221,
"author_profile": "https://wordpress.stackexchange.com/users/221",
"pm_score": 2,
"selected": false,
"text": "<p>You can pass the term object as the second parameter to the_field/get_field.</p>\n\n<pre><code>echo '<img src=\"' . get_field( 'brochure_logo', $tax_term ) . '\">';\n</code></pre>\n"
},
{
"answer_id": 227993,
"author": "Wiljan van Dalen",
"author_id": 94775,
"author_profile": "https://wordpress.stackexchange.com/users/94775",
"pm_score": 1,
"selected": false,
"text": "<p>In the settings from that field you can select to output the image URL. If it returns a object, use: </p>\n\n<pre><code>$img = get_field( 'brochure_logo' );\n</code></pre>\n\n<p>And to output the URL, use:</p>\n\n<pre><code>echo $img[0]['url']\n</code></pre>\n"
}
] |
2016/05/27
|
[
"https://wordpress.stackexchange.com/questions/227989",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94771/"
] |
I'm trying to display a list of all my custom taxonomy terms with an image field that I have created in ACF. The ACF image field I have is `<img src="<?php the_field('brochure_logo'); ?>">`, but how can I display that image in my code below? I have left a gap where the field needs to go, but I can't seem to output the image URL.
```
$taxonomy = 'brochure_categories';
$tax_terms = get_terms( $taxonomy );
?>
<ul class="downloadGrid">
<?php
foreach ( $tax_terms as $tax_term ) {
echo '<li>';
echo '<a href="' . esc_attr( get_term_link( $tax_term, $taxonomy ) ) .
'" title="' . sprintf( __( "View all posts in %s" ), $tax_term->name ) .
'" ' . '>';
echo '<img src=" " >';
echo $tax_term->name;
echo '</a>';
echo '</li>';
}
```
|
You can pass the term object as the second parameter to the\_field/get\_field.
```
echo '<img src="' . get_field( 'brochure_logo', $tax_term ) . '">';
```
|
228,004 |
<p>trying to filter the output of term_description to include a class <a href="https://codex.wordpress.org/Function_Reference/term_description" rel="nofollow">https://codex.wordpress.org/Function_Reference/term_description</a></p>
<pre><code>function add_class_to_term_description() { ?>
<?php echo '<div class="cell">' . term_description() . '</div>'; ?>
<?php }
add_filter( 'term_description', 'add_class_to_term_description' ); ?>
</code></pre>
<p>im getting and empty cell class returned hundreds of times which is exhausting the memory. what am i doing wrong?</p>
|
[
{
"answer_id": 228309,
"author": "user3316",
"author_id": 3316,
"author_profile": "https://wordpress.stackexchange.com/users/3316",
"pm_score": 0,
"selected": false,
"text": "<p>you have to use passed <code>$value</code> instead of <code>term_description()</code> function:</p>\n\n<pre><code>function add_class_to_term_description() {\n echo '<div class=\"cell\">' . $value . '</div>';\n}\nadd_filter( 'term_description', 'add_class_to_term_description' );\n</code></pre>\n"
},
{
"answer_id": 228641,
"author": "Daniel Florido",
"author_id": 57838,
"author_profile": "https://wordpress.stackexchange.com/users/57838",
"pm_score": 2,
"selected": true,
"text": "<p>this does the trick</p>\n\n<pre><code><?php function add_class_to_term_description($term_description) {\n echo '<div class=\"cell\">' . $term_description. '</div>';\n}\nadd_filter( 'term_description', 'add_class_to_term_description' ); ?>\n</code></pre>\n"
},
{
"answer_id": 350333,
"author": "Luke Gedeon",
"author_id": 11310,
"author_profile": "https://wordpress.stackexchange.com/users/11310",
"pm_score": 1,
"selected": false,
"text": "<p>Daniel is on the right track, using the value that is passed into the function. However, you should not be echoing anything because this is a filter. You should instead return the value.</p>\n\n<pre><code><?php\nfunction add_class_to_term_description( $term_description ) {\n return '<div class=\"cell\">' . $term_description. '</div>';\n}\nadd_filter( 'term_description', 'add_class_to_term_description' ); ?>\n</code></pre>\n"
},
{
"answer_id": 367235,
"author": "Marinski",
"author_id": 188573,
"author_profile": "https://wordpress.stackexchange.com/users/188573",
"pm_score": 0,
"selected": false,
"text": "<p>I tested many potential solutions, including all the answers above. They either did not work or did not work as expected - some output empty paragraphs, other do nothing. The best solution for me was to use the PHP function <a href=\"https://www.php.net/manual/en/function.preg-replace.php\" rel=\"nofollow noreferrer\">preg_replace</a> to perform a search for the opening paragraph HTML tag and to insert the class attribute with the value I need like this:</p>\n\n<pre><code>function add_class_to_term_descr($content){\n return preg_replace('/<p([^>]+)?>/', '<p$1 class=\"lead\">', $content, 1);\n}\nadd_filter('term_description', 'add_class_to_term_descr');\n</code></pre>\n\n<p>This solution can be easily modified to match other types of WordPress output, like \"div\" tag for example. I based my solution on <a href=\"https://wordpress.stackexchange.com/a/51682/188573\">this answer</a> and modified it according to my needs.</p>\n"
}
] |
2016/05/27
|
[
"https://wordpress.stackexchange.com/questions/228004",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57838/"
] |
trying to filter the output of term\_description to include a class <https://codex.wordpress.org/Function_Reference/term_description>
```
function add_class_to_term_description() { ?>
<?php echo '<div class="cell">' . term_description() . '</div>'; ?>
<?php }
add_filter( 'term_description', 'add_class_to_term_description' ); ?>
```
im getting and empty cell class returned hundreds of times which is exhausting the memory. what am i doing wrong?
|
this does the trick
```
<?php function add_class_to_term_description($term_description) {
echo '<div class="cell">' . $term_description. '</div>';
}
add_filter( 'term_description', 'add_class_to_term_description' ); ?>
```
|
228,011 |
<p>I want to display an archive page with pagination that lists all the categories on my site, and each link goes to that particular category archive page. So this would be like an archive page of category archives.</p>
<p>Each category on my site has a custom thumbnail created manually to match the category's permalink. I already have a layout setup to display all the categories but I'm doing this with a custom page template, so there's no pagination. This means all categories display on a single page which is a tad annoying(I have 100+ categories).</p>
<p>My current archive is setup with a specific custom page template name <code>page-catlist.php</code> but I'm willing to change this to any other type of template file.</p>
<p>Here's the current code I'm using to output all categories on one page:</p>
<pre><code>$args = array(
'orderby' => 'name',
'order' => 'ASC'
);
$cats = get_categories( $args );
$thm_pre = 'http://example.com/images/thumbs/';
$thm_end = '.png';
foreach($cats as $cat) {
$thumbnail = $thm_pre.$cat->slug.$thm_end;
// output the loop HTML here
// basically a list of category names & thumbs
// all linked to the cat URL by get_category_link()
}
</code></pre>
<p>I'm hoping there's a better way to do this so that I can add natural pagination, ideally with WP-PageNavi. Any help would be greatly appreciated!</p>
|
[
{
"answer_id": 228035,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not familiar with WP-PageNavi, but I suspect it assumes to be dealing with posts, so it might easily screw up if you use it on a loop like yours. Perhaps the css might still be helpful in styling your html. Anyway, setting up your own pagination is not that difficult.</p>\n\n<p>First, you need to know how many categories there are: </p>\n\n<pre><code>$cat_amounts=count($cats);\n</code></pre>\n\n<p>Next you need to determine how many items per page you want: </p>\n\n<pre><code>$cats_per_page=20;\n</code></pre>\n\n<p>This will give you the amount of pages: </p>\n\n<pre><code>$max_pages=ceil($cat_amounts/$cats_per_page);\n</code></pre>\n\n<p>The third piece of information you need is the page you are on. You can keep track of this by introducing a <a href=\"https://codex.wordpress.org/WordPress_Query_Vars\" rel=\"nofollow\"><code>query_var</code></a> Your url will then look something like this: <code>www.example.com/yourcatpage?catpage=2</code></p>\n\n<p>Before you start the loop, you need to know which page is called: </p>\n\n<pre><code>$page_called=get_query_var ( $catpage, 1 )\n</code></pre>\n\n<p>From this you can call the first element you want to display: </p>\n\n<pre><code>$first_element=($page_called-1)*$cats_per_page)\n</code></pre>\n\n<p>and the last one: </p>\n\n<pre><code>$last_element=$page_called*$cats_per_page-1;\n</code></pre>\n\n<p>The last page may contain less than <code>$cats_per_page</code> categories, so additionally you need:</p>\n\n<pre><code>if ($last_element > $cat_amounts) $last_element = $cat_amounts;\n</code></pre>\n\n<p>Now, loop through the desired elements of <code>$cats</code>:</p>\n\n<pre><code>for ($i=$first_element;$i=<$last_element;$i++) {\n //do your thing with $cats[$i];\n}\n</code></pre>\n\n<p>After the loop you can use the variables to generate previous/next tags or nay other type of navigation.</p>\n\n<p>Beware that I didn't actually test this code. I may have made some mistakes when taking into account that the first element in an array has key 0.</p>\n"
},
{
"answer_id": 228071,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>Paging a list of terms/categories/tags are quite easy, and to achieve that, you need minimal info. </p>\n\n<p>Lets look at we need</p>\n\n<ul>\n<li><p>the amount of terms</p></li>\n<li><p>the amount of terms per page</p></li>\n<li><p><a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow\"><code>get_terms()</code></a> (<em>Just note, the usage of <code>get_terms()</code> have changed in version 4.5</em>). You can also use <code>get_categories()</code> if you wish, <code>get_categories()</code> is just a wrapper function for <code>get_terms()</code></p></li>\n</ul>\n\n<p>So first we need to count the amount of terms. For this, we will use the <code>count</code> parameter in <code>get_terms()</code></p>\n\n<h2>NOTE:</h2>\n\n<ul>\n<li><p>All code is untested and requires at least</p>\n\n<ul>\n<li><p>PHP 5.4</p></li>\n<li><p>WordPress 4.5</p></li>\n</ul></li>\n</ul>\n\n<p>You can easily convert this to work with older versions of PHP and WordPress</p>\n\n<pre><code>$taxonomy = 'category';\n$term_count = get_terms( \n [\n 'taxonomy' => $taxonomy,\n 'fields' => 'count'\n ]\n);\n</code></pre>\n\n<p>Now that we know the amount of terms, we can set the amount of terms we need per page, lets say 10</p>\n\n<pre><code>$terms_per_page = 10;\n</code></pre>\n\n<p>From the above, we can now work out how many pages we will have. The value here will be passed to the requires pagination function, in your case, to <code>wp_pagenavi()</code></p>\n\n<pre><code>$max_num_pages = ceil( $term_count/$terms_per_page );\n</code></pre>\n\n<p>In this case, you would pass <code>$max_num_pages</code> to your pagination function</p>\n\n<p>The next part would be to calculate our offset. We only want to retrieve the relevant amount of terms per page to keep things optimized. We do not need all 100+ terms per page. Querying only the needed 10 is much faster. So, we need to know on which page we are, are from that, we will calculate an offset. This will be passed to <code>get_terms()</code>, and will tell <code>get_terms()</code> how many terms to skip from the initial starting point. </p>\n\n<p>Once have that, we must also tell <code>get_terms()</code> to only return 10 terms. Let look at the code for this piece</p>\n\n<pre><code>$current_page = get_query_var( 'paged', 1 ); // Change to 'page' for static front page\n$offset = ( $terms_per_page * $current_page ) - $terms_per_page;\n$terms = get_terms(\n [\n 'taxonomy' => $taxonomy,\n 'order' => 'ASC',\n 'orderby' => 'name',\n 'number' => $terms_per_page,\n 'offset' => $offset\n ]\n);\n</code></pre>\n\n<p>You will only have 10 terms per page according to pagination. You can now just loop normally through your terms</p>\n\n<p>Just a note, you would want to make sure that you actually have terms returned from your <code>get_terms()</code> function. </p>\n"
}
] |
2016/05/27
|
[
"https://wordpress.stackexchange.com/questions/228011",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94787/"
] |
I want to display an archive page with pagination that lists all the categories on my site, and each link goes to that particular category archive page. So this would be like an archive page of category archives.
Each category on my site has a custom thumbnail created manually to match the category's permalink. I already have a layout setup to display all the categories but I'm doing this with a custom page template, so there's no pagination. This means all categories display on a single page which is a tad annoying(I have 100+ categories).
My current archive is setup with a specific custom page template name `page-catlist.php` but I'm willing to change this to any other type of template file.
Here's the current code I'm using to output all categories on one page:
```
$args = array(
'orderby' => 'name',
'order' => 'ASC'
);
$cats = get_categories( $args );
$thm_pre = 'http://example.com/images/thumbs/';
$thm_end = '.png';
foreach($cats as $cat) {
$thumbnail = $thm_pre.$cat->slug.$thm_end;
// output the loop HTML here
// basically a list of category names & thumbs
// all linked to the cat URL by get_category_link()
}
```
I'm hoping there's a better way to do this so that I can add natural pagination, ideally with WP-PageNavi. Any help would be greatly appreciated!
|
Paging a list of terms/categories/tags are quite easy, and to achieve that, you need minimal info.
Lets look at we need
* the amount of terms
* the amount of terms per page
* [`get_terms()`](https://developer.wordpress.org/reference/functions/get_terms/) (*Just note, the usage of `get_terms()` have changed in version 4.5*). You can also use `get_categories()` if you wish, `get_categories()` is just a wrapper function for `get_terms()`
So first we need to count the amount of terms. For this, we will use the `count` parameter in `get_terms()`
NOTE:
-----
* All code is untested and requires at least
+ PHP 5.4
+ WordPress 4.5
You can easily convert this to work with older versions of PHP and WordPress
```
$taxonomy = 'category';
$term_count = get_terms(
[
'taxonomy' => $taxonomy,
'fields' => 'count'
]
);
```
Now that we know the amount of terms, we can set the amount of terms we need per page, lets say 10
```
$terms_per_page = 10;
```
From the above, we can now work out how many pages we will have. The value here will be passed to the requires pagination function, in your case, to `wp_pagenavi()`
```
$max_num_pages = ceil( $term_count/$terms_per_page );
```
In this case, you would pass `$max_num_pages` to your pagination function
The next part would be to calculate our offset. We only want to retrieve the relevant amount of terms per page to keep things optimized. We do not need all 100+ terms per page. Querying only the needed 10 is much faster. So, we need to know on which page we are, are from that, we will calculate an offset. This will be passed to `get_terms()`, and will tell `get_terms()` how many terms to skip from the initial starting point.
Once have that, we must also tell `get_terms()` to only return 10 terms. Let look at the code for this piece
```
$current_page = get_query_var( 'paged', 1 ); // Change to 'page' for static front page
$offset = ( $terms_per_page * $current_page ) - $terms_per_page;
$terms = get_terms(
[
'taxonomy' => $taxonomy,
'order' => 'ASC',
'orderby' => 'name',
'number' => $terms_per_page,
'offset' => $offset
]
);
```
You will only have 10 terms per page according to pagination. You can now just loop normally through your terms
Just a note, you would want to make sure that you actually have terms returned from your `get_terms()` function.
|
228,031 |
<p>I have a homepage, work (as parent pages) and several pages (as child), but when it comes to articles, I can't choose the relation between them and the page Blog.</p>
<p>Resuming, I can choose the hierarchy relation between pages, but I'm in trouble putting the articles under a "directory" called blog.
If change the permalinks, I will change it for all pages and articles, so I'm lost on this.</p>
<p>Note: I have a blog page where there is a list of articles, but instead of www.claro.pt/blog/article - I have www.claro.pt/article</p>
<p>Thank you for your help</p>
|
[
{
"answer_id": 228035,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not familiar with WP-PageNavi, but I suspect it assumes to be dealing with posts, so it might easily screw up if you use it on a loop like yours. Perhaps the css might still be helpful in styling your html. Anyway, setting up your own pagination is not that difficult.</p>\n\n<p>First, you need to know how many categories there are: </p>\n\n<pre><code>$cat_amounts=count($cats);\n</code></pre>\n\n<p>Next you need to determine how many items per page you want: </p>\n\n<pre><code>$cats_per_page=20;\n</code></pre>\n\n<p>This will give you the amount of pages: </p>\n\n<pre><code>$max_pages=ceil($cat_amounts/$cats_per_page);\n</code></pre>\n\n<p>The third piece of information you need is the page you are on. You can keep track of this by introducing a <a href=\"https://codex.wordpress.org/WordPress_Query_Vars\" rel=\"nofollow\"><code>query_var</code></a> Your url will then look something like this: <code>www.example.com/yourcatpage?catpage=2</code></p>\n\n<p>Before you start the loop, you need to know which page is called: </p>\n\n<pre><code>$page_called=get_query_var ( $catpage, 1 )\n</code></pre>\n\n<p>From this you can call the first element you want to display: </p>\n\n<pre><code>$first_element=($page_called-1)*$cats_per_page)\n</code></pre>\n\n<p>and the last one: </p>\n\n<pre><code>$last_element=$page_called*$cats_per_page-1;\n</code></pre>\n\n<p>The last page may contain less than <code>$cats_per_page</code> categories, so additionally you need:</p>\n\n<pre><code>if ($last_element > $cat_amounts) $last_element = $cat_amounts;\n</code></pre>\n\n<p>Now, loop through the desired elements of <code>$cats</code>:</p>\n\n<pre><code>for ($i=$first_element;$i=<$last_element;$i++) {\n //do your thing with $cats[$i];\n}\n</code></pre>\n\n<p>After the loop you can use the variables to generate previous/next tags or nay other type of navigation.</p>\n\n<p>Beware that I didn't actually test this code. I may have made some mistakes when taking into account that the first element in an array has key 0.</p>\n"
},
{
"answer_id": 228071,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>Paging a list of terms/categories/tags are quite easy, and to achieve that, you need minimal info. </p>\n\n<p>Lets look at we need</p>\n\n<ul>\n<li><p>the amount of terms</p></li>\n<li><p>the amount of terms per page</p></li>\n<li><p><a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow\"><code>get_terms()</code></a> (<em>Just note, the usage of <code>get_terms()</code> have changed in version 4.5</em>). You can also use <code>get_categories()</code> if you wish, <code>get_categories()</code> is just a wrapper function for <code>get_terms()</code></p></li>\n</ul>\n\n<p>So first we need to count the amount of terms. For this, we will use the <code>count</code> parameter in <code>get_terms()</code></p>\n\n<h2>NOTE:</h2>\n\n<ul>\n<li><p>All code is untested and requires at least</p>\n\n<ul>\n<li><p>PHP 5.4</p></li>\n<li><p>WordPress 4.5</p></li>\n</ul></li>\n</ul>\n\n<p>You can easily convert this to work with older versions of PHP and WordPress</p>\n\n<pre><code>$taxonomy = 'category';\n$term_count = get_terms( \n [\n 'taxonomy' => $taxonomy,\n 'fields' => 'count'\n ]\n);\n</code></pre>\n\n<p>Now that we know the amount of terms, we can set the amount of terms we need per page, lets say 10</p>\n\n<pre><code>$terms_per_page = 10;\n</code></pre>\n\n<p>From the above, we can now work out how many pages we will have. The value here will be passed to the requires pagination function, in your case, to <code>wp_pagenavi()</code></p>\n\n<pre><code>$max_num_pages = ceil( $term_count/$terms_per_page );\n</code></pre>\n\n<p>In this case, you would pass <code>$max_num_pages</code> to your pagination function</p>\n\n<p>The next part would be to calculate our offset. We only want to retrieve the relevant amount of terms per page to keep things optimized. We do not need all 100+ terms per page. Querying only the needed 10 is much faster. So, we need to know on which page we are, are from that, we will calculate an offset. This will be passed to <code>get_terms()</code>, and will tell <code>get_terms()</code> how many terms to skip from the initial starting point. </p>\n\n<p>Once have that, we must also tell <code>get_terms()</code> to only return 10 terms. Let look at the code for this piece</p>\n\n<pre><code>$current_page = get_query_var( 'paged', 1 ); // Change to 'page' for static front page\n$offset = ( $terms_per_page * $current_page ) - $terms_per_page;\n$terms = get_terms(\n [\n 'taxonomy' => $taxonomy,\n 'order' => 'ASC',\n 'orderby' => 'name',\n 'number' => $terms_per_page,\n 'offset' => $offset\n ]\n);\n</code></pre>\n\n<p>You will only have 10 terms per page according to pagination. You can now just loop normally through your terms</p>\n\n<p>Just a note, you would want to make sure that you actually have terms returned from your <code>get_terms()</code> function. </p>\n"
}
] |
2016/05/27
|
[
"https://wordpress.stackexchange.com/questions/228031",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94801/"
] |
I have a homepage, work (as parent pages) and several pages (as child), but when it comes to articles, I can't choose the relation between them and the page Blog.
Resuming, I can choose the hierarchy relation between pages, but I'm in trouble putting the articles under a "directory" called blog.
If change the permalinks, I will change it for all pages and articles, so I'm lost on this.
Note: I have a blog page where there is a list of articles, but instead of www.claro.pt/blog/article - I have www.claro.pt/article
Thank you for your help
|
Paging a list of terms/categories/tags are quite easy, and to achieve that, you need minimal info.
Lets look at we need
* the amount of terms
* the amount of terms per page
* [`get_terms()`](https://developer.wordpress.org/reference/functions/get_terms/) (*Just note, the usage of `get_terms()` have changed in version 4.5*). You can also use `get_categories()` if you wish, `get_categories()` is just a wrapper function for `get_terms()`
So first we need to count the amount of terms. For this, we will use the `count` parameter in `get_terms()`
NOTE:
-----
* All code is untested and requires at least
+ PHP 5.4
+ WordPress 4.5
You can easily convert this to work with older versions of PHP and WordPress
```
$taxonomy = 'category';
$term_count = get_terms(
[
'taxonomy' => $taxonomy,
'fields' => 'count'
]
);
```
Now that we know the amount of terms, we can set the amount of terms we need per page, lets say 10
```
$terms_per_page = 10;
```
From the above, we can now work out how many pages we will have. The value here will be passed to the requires pagination function, in your case, to `wp_pagenavi()`
```
$max_num_pages = ceil( $term_count/$terms_per_page );
```
In this case, you would pass `$max_num_pages` to your pagination function
The next part would be to calculate our offset. We only want to retrieve the relevant amount of terms per page to keep things optimized. We do not need all 100+ terms per page. Querying only the needed 10 is much faster. So, we need to know on which page we are, are from that, we will calculate an offset. This will be passed to `get_terms()`, and will tell `get_terms()` how many terms to skip from the initial starting point.
Once have that, we must also tell `get_terms()` to only return 10 terms. Let look at the code for this piece
```
$current_page = get_query_var( 'paged', 1 ); // Change to 'page' for static front page
$offset = ( $terms_per_page * $current_page ) - $terms_per_page;
$terms = get_terms(
[
'taxonomy' => $taxonomy,
'order' => 'ASC',
'orderby' => 'name',
'number' => $terms_per_page,
'offset' => $offset
]
);
```
You will only have 10 terms per page according to pagination. You can now just loop normally through your terms
Just a note, you would want to make sure that you actually have terms returned from your `get_terms()` function.
|
228,095 |
<p>I can't figure out how to filter the comment permalink on certain WP page that I use like this:</p>
<pre><code>if(condition is met) {
(filter the comment url)
}
</code></pre>
<p>...so that all the comment permalinks inside the page can be changed from this:</p>
<pre><code>http://example.com/slug-to-page/#comment-n
</code></pre>
<p>to this:</p>
<pre><code>http://example.com/new-slug/#comment-n
</code></pre>
<p>In short, I'm trying to change the url structure pointing out to the page permalink, excluding the <strong>site_url</strong> (front page url) and the <strong>comment slug</strong> (e.g. #comment-n)</p>
<p>So far, I've tried the example in the <a href="https://codex.wordpress.org/Plugin_API/Filter_Reference/comment_link" rel="nofollow">comment_link filter</a> and nothing happens here:</p>
<pre><code>function my_comment_link_filter( $link ) {
$link = str_replace( get_permalink() , $new_permalink_structure , $link );
return $link;
}
add_filter( 'comment_link', 'my_comment_link_filter', 10, 3 );
</code></pre>
<p>I'm doing it wrong, it seems, and would certainly appreciate any help.</p>
|
[
{
"answer_id": 228035,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not familiar with WP-PageNavi, but I suspect it assumes to be dealing with posts, so it might easily screw up if you use it on a loop like yours. Perhaps the css might still be helpful in styling your html. Anyway, setting up your own pagination is not that difficult.</p>\n\n<p>First, you need to know how many categories there are: </p>\n\n<pre><code>$cat_amounts=count($cats);\n</code></pre>\n\n<p>Next you need to determine how many items per page you want: </p>\n\n<pre><code>$cats_per_page=20;\n</code></pre>\n\n<p>This will give you the amount of pages: </p>\n\n<pre><code>$max_pages=ceil($cat_amounts/$cats_per_page);\n</code></pre>\n\n<p>The third piece of information you need is the page you are on. You can keep track of this by introducing a <a href=\"https://codex.wordpress.org/WordPress_Query_Vars\" rel=\"nofollow\"><code>query_var</code></a> Your url will then look something like this: <code>www.example.com/yourcatpage?catpage=2</code></p>\n\n<p>Before you start the loop, you need to know which page is called: </p>\n\n<pre><code>$page_called=get_query_var ( $catpage, 1 )\n</code></pre>\n\n<p>From this you can call the first element you want to display: </p>\n\n<pre><code>$first_element=($page_called-1)*$cats_per_page)\n</code></pre>\n\n<p>and the last one: </p>\n\n<pre><code>$last_element=$page_called*$cats_per_page-1;\n</code></pre>\n\n<p>The last page may contain less than <code>$cats_per_page</code> categories, so additionally you need:</p>\n\n<pre><code>if ($last_element > $cat_amounts) $last_element = $cat_amounts;\n</code></pre>\n\n<p>Now, loop through the desired elements of <code>$cats</code>:</p>\n\n<pre><code>for ($i=$first_element;$i=<$last_element;$i++) {\n //do your thing with $cats[$i];\n}\n</code></pre>\n\n<p>After the loop you can use the variables to generate previous/next tags or nay other type of navigation.</p>\n\n<p>Beware that I didn't actually test this code. I may have made some mistakes when taking into account that the first element in an array has key 0.</p>\n"
},
{
"answer_id": 228071,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>Paging a list of terms/categories/tags are quite easy, and to achieve that, you need minimal info. </p>\n\n<p>Lets look at we need</p>\n\n<ul>\n<li><p>the amount of terms</p></li>\n<li><p>the amount of terms per page</p></li>\n<li><p><a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow\"><code>get_terms()</code></a> (<em>Just note, the usage of <code>get_terms()</code> have changed in version 4.5</em>). You can also use <code>get_categories()</code> if you wish, <code>get_categories()</code> is just a wrapper function for <code>get_terms()</code></p></li>\n</ul>\n\n<p>So first we need to count the amount of terms. For this, we will use the <code>count</code> parameter in <code>get_terms()</code></p>\n\n<h2>NOTE:</h2>\n\n<ul>\n<li><p>All code is untested and requires at least</p>\n\n<ul>\n<li><p>PHP 5.4</p></li>\n<li><p>WordPress 4.5</p></li>\n</ul></li>\n</ul>\n\n<p>You can easily convert this to work with older versions of PHP and WordPress</p>\n\n<pre><code>$taxonomy = 'category';\n$term_count = get_terms( \n [\n 'taxonomy' => $taxonomy,\n 'fields' => 'count'\n ]\n);\n</code></pre>\n\n<p>Now that we know the amount of terms, we can set the amount of terms we need per page, lets say 10</p>\n\n<pre><code>$terms_per_page = 10;\n</code></pre>\n\n<p>From the above, we can now work out how many pages we will have. The value here will be passed to the requires pagination function, in your case, to <code>wp_pagenavi()</code></p>\n\n<pre><code>$max_num_pages = ceil( $term_count/$terms_per_page );\n</code></pre>\n\n<p>In this case, you would pass <code>$max_num_pages</code> to your pagination function</p>\n\n<p>The next part would be to calculate our offset. We only want to retrieve the relevant amount of terms per page to keep things optimized. We do not need all 100+ terms per page. Querying only the needed 10 is much faster. So, we need to know on which page we are, are from that, we will calculate an offset. This will be passed to <code>get_terms()</code>, and will tell <code>get_terms()</code> how many terms to skip from the initial starting point. </p>\n\n<p>Once have that, we must also tell <code>get_terms()</code> to only return 10 terms. Let look at the code for this piece</p>\n\n<pre><code>$current_page = get_query_var( 'paged', 1 ); // Change to 'page' for static front page\n$offset = ( $terms_per_page * $current_page ) - $terms_per_page;\n$terms = get_terms(\n [\n 'taxonomy' => $taxonomy,\n 'order' => 'ASC',\n 'orderby' => 'name',\n 'number' => $terms_per_page,\n 'offset' => $offset\n ]\n);\n</code></pre>\n\n<p>You will only have 10 terms per page according to pagination. You can now just loop normally through your terms</p>\n\n<p>Just a note, you would want to make sure that you actually have terms returned from your <code>get_terms()</code> function. </p>\n"
}
] |
2016/05/28
|
[
"https://wordpress.stackexchange.com/questions/228095",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94080/"
] |
I can't figure out how to filter the comment permalink on certain WP page that I use like this:
```
if(condition is met) {
(filter the comment url)
}
```
...so that all the comment permalinks inside the page can be changed from this:
```
http://example.com/slug-to-page/#comment-n
```
to this:
```
http://example.com/new-slug/#comment-n
```
In short, I'm trying to change the url structure pointing out to the page permalink, excluding the **site\_url** (front page url) and the **comment slug** (e.g. #comment-n)
So far, I've tried the example in the [comment\_link filter](https://codex.wordpress.org/Plugin_API/Filter_Reference/comment_link) and nothing happens here:
```
function my_comment_link_filter( $link ) {
$link = str_replace( get_permalink() , $new_permalink_structure , $link );
return $link;
}
add_filter( 'comment_link', 'my_comment_link_filter', 10, 3 );
```
I'm doing it wrong, it seems, and would certainly appreciate any help.
|
Paging a list of terms/categories/tags are quite easy, and to achieve that, you need minimal info.
Lets look at we need
* the amount of terms
* the amount of terms per page
* [`get_terms()`](https://developer.wordpress.org/reference/functions/get_terms/) (*Just note, the usage of `get_terms()` have changed in version 4.5*). You can also use `get_categories()` if you wish, `get_categories()` is just a wrapper function for `get_terms()`
So first we need to count the amount of terms. For this, we will use the `count` parameter in `get_terms()`
NOTE:
-----
* All code is untested and requires at least
+ PHP 5.4
+ WordPress 4.5
You can easily convert this to work with older versions of PHP and WordPress
```
$taxonomy = 'category';
$term_count = get_terms(
[
'taxonomy' => $taxonomy,
'fields' => 'count'
]
);
```
Now that we know the amount of terms, we can set the amount of terms we need per page, lets say 10
```
$terms_per_page = 10;
```
From the above, we can now work out how many pages we will have. The value here will be passed to the requires pagination function, in your case, to `wp_pagenavi()`
```
$max_num_pages = ceil( $term_count/$terms_per_page );
```
In this case, you would pass `$max_num_pages` to your pagination function
The next part would be to calculate our offset. We only want to retrieve the relevant amount of terms per page to keep things optimized. We do not need all 100+ terms per page. Querying only the needed 10 is much faster. So, we need to know on which page we are, are from that, we will calculate an offset. This will be passed to `get_terms()`, and will tell `get_terms()` how many terms to skip from the initial starting point.
Once have that, we must also tell `get_terms()` to only return 10 terms. Let look at the code for this piece
```
$current_page = get_query_var( 'paged', 1 ); // Change to 'page' for static front page
$offset = ( $terms_per_page * $current_page ) - $terms_per_page;
$terms = get_terms(
[
'taxonomy' => $taxonomy,
'order' => 'ASC',
'orderby' => 'name',
'number' => $terms_per_page,
'offset' => $offset
]
);
```
You will only have 10 terms per page according to pagination. You can now just loop normally through your terms
Just a note, you would want to make sure that you actually have terms returned from your `get_terms()` function.
|
228,111 |
<p>I'm currently working with a company to make a few basic tweeks to their WordPress site and I noticed that they have this on their sidebar:</p>
<p><a href="https://i.stack.imgur.com/H75vK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H75vK.png" alt="enter image description here"></a></p>
<p>I am looking particularly at the "Clients", "Offers", "Portfolio" and "Slider Offer" sections, I have never seen these before and believe that they have not been added with a plugin. It appears that they are post categories, as they have the same pin icon as the "Posts" section. Can anyone explain what these are, how they work and how to add them?</p>
<p>Thanks</p>
|
[
{
"answer_id": 229075,
"author": "Mayeenul Islam",
"author_id": 22728,
"author_profile": "https://wordpress.stackexchange.com/users/22728",
"pm_score": 2,
"selected": true,
"text": "<p>WordPress Core post types are <code>post</code> and <code>page</code> that are visible in the admin menu. Other than these can be either a registered custom post type or a menu page.</p>\n\n<p>A menu page can be added with the <a href=\"https://developer.wordpress.org/reference/functions/add_menu_page/\" rel=\"nofollow\"><code>add_menu_page()</code></a> function, and a similar thing can be done using <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow\"><code>register_post_type()</code></a>, where a registered post type gets its own menu item where the following arguments are <code>true</code>:</p>\n\n<pre><code><?php\n$args = array(\n 'show_ui' => true,\n 'show_in_menu' => true\n );\n\nregister_post_type( 'mycpt', $args );\n</code></pre>\n\n<p>Note that, <code>register_post_type()</code> is a plugin-territory function. But some themes include them into their <code>functions.php</code>. And in that case, it's also possible, a parent theme didn't include 'em, but a child theme did so into its <code>functions.php</code>. :)</p>\n"
},
{
"answer_id": 229077,
"author": "Chirag S Modi",
"author_id": 94923,
"author_profile": "https://wordpress.stackexchange.com/users/94923",
"pm_score": 0,
"selected": false,
"text": "<p>I Believe this are the Custom Post type of wordpress. Custom post type will work in same way as the post is working, you can make different category for each post type and also will able to create different archive and single page. I am posting a sample post type code if you want to experiment more on this. This code you simply copy and past into function.php of your theme or you can put this in different .php file and you can <code>require_once</code> in function.php file like i am doing <code>require_once('custom-post-type/team.php');</code> I always create different folder of custom post type and then put all post type files there and make it require in function file.</p>\n\n<pre><code><?php\n/* Custom Post Type ===> team_member */\nadd_action( 'init', 'register_cpt_team_member' );\nfunction register_cpt_team_member() {\n$labels = array( \n 'name' => _x( 'Team Member', 'team_member' ),\n 'singular_name' => _x( 'Team Member', 'team_member' ),\n 'add_new' => _x( 'Add New', 'team_member' ),\n 'add_new_item' => _x( 'Add New Team Member', 'team_member' ),\n 'edit_item' => _x( 'Edit Team Member', 'team_member' ),\n 'new_item' => _x( 'New Team Member', 'team_member' ),\n 'view_item' => _x( 'View Team Member', 'team_member' ),\n 'search_items' => _x( 'Search Team Member', 'team_member' ),\n 'not_found' => _x( 'No Team Member found', 'team_member' ),\n 'not_found_in_trash' => _x( 'No Team Member found in Trash', 'team_member' ),\n 'menu_name' => _x( 'Team Member', 'team_member' ),\n);\n$args = array( \n 'labels' => $labels,\n 'hierarchical' => false, \n 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'custom-fields', 'revisions', 'page-attributes' ),\n //'taxonomies' => array('post_tag'),\n 'public' => true,\n 'show_ui' => true,\n 'show_in_menu' => true, \n 'menu_icon' => 'dashicons-admin-users', \n 'show_in_nav_menus' => true,\n 'publicly_queryable' => true,\n 'exclude_from_search' => false,\n 'has_archive' => true,\n 'query_var' => true,\n 'can_export' => true,\n 'rewrite' => array('slug' => 'team_member'),\n 'capability_type' => 'post'\n);\nregister_post_type( 'team_member', $args );\nflush_rewrite_rules(); // <- do this only once!\n}\n?>\n</code></pre>\n\n<p>If you want to Know more details on custom post type refer to wordpress codex. \n<a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow\">https://codex.wordpress.org/Post_Types</a></p>\n"
}
] |
2016/05/28
|
[
"https://wordpress.stackexchange.com/questions/228111",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86794/"
] |
I'm currently working with a company to make a few basic tweeks to their WordPress site and I noticed that they have this on their sidebar:
[](https://i.stack.imgur.com/H75vK.png)
I am looking particularly at the "Clients", "Offers", "Portfolio" and "Slider Offer" sections, I have never seen these before and believe that they have not been added with a plugin. It appears that they are post categories, as they have the same pin icon as the "Posts" section. Can anyone explain what these are, how they work and how to add them?
Thanks
|
WordPress Core post types are `post` and `page` that are visible in the admin menu. Other than these can be either a registered custom post type or a menu page.
A menu page can be added with the [`add_menu_page()`](https://developer.wordpress.org/reference/functions/add_menu_page/) function, and a similar thing can be done using [`register_post_type()`](https://codex.wordpress.org/Function_Reference/register_post_type), where a registered post type gets its own menu item where the following arguments are `true`:
```
<?php
$args = array(
'show_ui' => true,
'show_in_menu' => true
);
register_post_type( 'mycpt', $args );
```
Note that, `register_post_type()` is a plugin-territory function. But some themes include them into their `functions.php`. And in that case, it's also possible, a parent theme didn't include 'em, but a child theme did so into its `functions.php`. :)
|
228,123 |
<p>Can anyone tell me how to enable Bootstrap on a site using the twentyeleven theme? I followed the instructions for activating Bootstrap with the <a href="https://wordpress.stackexchange.com/questions/163209/how-to-install-bootstrap-to-twentyfourteen-theme">twentyfourteen theme</a> without success.</p>
<p>This is the code I uploaded in the functions.php in my twentyeleven-child folder:</p>
<pre><code><?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
function my_scripts_enqueue() {
wp_register_script( 'bootstrap-js', '://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js', array('jquery'), NULL, true );
wp_register_style( 'bootstrap-css', '://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css', false, NULL, 'all' );
wp_enqueue_script( 'bootstrap-js' );
wp_enqueue_style( 'bootstrap-css' );
}
add_action( 'wp_enqueue_scripts', 'my_scripts_enqueue' );
?>
</code></pre>
<p>Do I have to manually activate it somehow after I upload the file?</p>
<p><strong>EDIT:</strong></p>
<p>I just checked my source code and discovered that I have "enabled" Bootstrap...</p>
<p>http://mysite://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css' type='text/css' media='all' /></p>
<p>The obvious problem is that the style sheet links point to my site, rather than maxcdn. Does anyone know how I can fix that?</p>
<p>I guess the obvious answer is to just find the files that hold the style sheet and JS links and insert the Bootstrap links manually?</p>
|
[
{
"answer_id": 228130,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>Caching can be anywhere, starting with request caching on mysql components side (unlikely to impact in this case), and object caching on wordpress side.</p>\n\n<p>You are probably doing something wrong in your code, but it is always better to use the API (or wordpress admin as a front end to it) to delete things then to try to delete them by directly accessing the DB. It is not only caching that might give you problems but also user meta and other configuration settings that you are not going to take into account.</p>\n"
},
{
"answer_id": 228247,
"author": "wpclevel",
"author_id": 92212,
"author_profile": "https://wordpress.stackexchange.com/users/92212",
"pm_score": 3,
"selected": true,
"text": "<p>By default, WordPress uses <code>$wp_object_cache</code> which is an instance of <a href=\"https://developer.wordpress.org/reference/classes/wp_object_cache/\" rel=\"nofollow\"><code>WP_Object_Cache</code></a> to save on trips to the database.</p>\n\n<p>Trace back <a href=\"https://developer.wordpress.org/reference/functions/username_exists/#source-code\" rel=\"nofollow\"><code>username_exists()</code></a> function, you will notice that <a href=\"https://developer.wordpress.org/reference/functions/get_user_by/\" rel=\"nofollow\"><code>get_user_by()</code></a> uses <a href=\"https://developer.wordpress.org/reference/classes/wp_user/get_data_by/#source-code\" rel=\"nofollow\"><code>WP_User::get_data_by()</code></a> which return user data from <code>$wp_object_cache</code> immediately without checking if that user exists in database. Note that <code>$wp_object_cache</code> is stored in memory.</p>\n\n<p>It means that if you deleted an user record directly in your database without cleaning up user cache, user data is still available. That's the problem.</p>\n\n<p>So what you're missing?</p>\n\n<ol>\n<li><p>Missing to <a href=\"https://developer.wordpress.org/reference/functions/wp_delete_user/#source-code\" rel=\"nofollow\">delete user the right way</a>.</p></li>\n<li><p>Missing to <a href=\"https://developer.wordpress.org/reference/functions/clean_user_cache/\" rel=\"nofollow\">clean user cache</a>.</p></li>\n</ol>\n"
}
] |
2016/05/29
|
[
"https://wordpress.stackexchange.com/questions/228123",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94575/"
] |
Can anyone tell me how to enable Bootstrap on a site using the twentyeleven theme? I followed the instructions for activating Bootstrap with the [twentyfourteen theme](https://wordpress.stackexchange.com/questions/163209/how-to-install-bootstrap-to-twentyfourteen-theme) without success.
This is the code I uploaded in the functions.php in my twentyeleven-child folder:
```
<?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
function my_scripts_enqueue() {
wp_register_script( 'bootstrap-js', '://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js', array('jquery'), NULL, true );
wp_register_style( 'bootstrap-css', '://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css', false, NULL, 'all' );
wp_enqueue_script( 'bootstrap-js' );
wp_enqueue_style( 'bootstrap-css' );
}
add_action( 'wp_enqueue_scripts', 'my_scripts_enqueue' );
?>
```
Do I have to manually activate it somehow after I upload the file?
**EDIT:**
I just checked my source code and discovered that I have "enabled" Bootstrap...
http://mysite://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css' type='text/css' media='all' />
The obvious problem is that the style sheet links point to my site, rather than maxcdn. Does anyone know how I can fix that?
I guess the obvious answer is to just find the files that hold the style sheet and JS links and insert the Bootstrap links manually?
|
By default, WordPress uses `$wp_object_cache` which is an instance of [`WP_Object_Cache`](https://developer.wordpress.org/reference/classes/wp_object_cache/) to save on trips to the database.
Trace back [`username_exists()`](https://developer.wordpress.org/reference/functions/username_exists/#source-code) function, you will notice that [`get_user_by()`](https://developer.wordpress.org/reference/functions/get_user_by/) uses [`WP_User::get_data_by()`](https://developer.wordpress.org/reference/classes/wp_user/get_data_by/#source-code) which return user data from `$wp_object_cache` immediately without checking if that user exists in database. Note that `$wp_object_cache` is stored in memory.
It means that if you deleted an user record directly in your database without cleaning up user cache, user data is still available. That's the problem.
So what you're missing?
1. Missing to [delete user the right way](https://developer.wordpress.org/reference/functions/wp_delete_user/#source-code).
2. Missing to [clean user cache](https://developer.wordpress.org/reference/functions/clean_user_cache/).
|
228,152 |
<p>Consider the simplest <code>archive.php</code> possible:</p>
<pre><code><?php
get_header();
while ( have_posts() ) {
the_post();
the_title();
}
get_footer();
</code></pre>
<p><strong>What address should I type into the browser to get to this page and display all posts?</strong> The permalink Custom Struction is set as "/%category%/%postname%/". I have tried going <a href="http://example.com/posts" rel="nofollow">http://example.com/posts</a> but that page returns simply a 404 error.</p>
|
[
{
"answer_id": 228153,
"author": "dotancohen",
"author_id": 34330,
"author_profile": "https://wordpress.stackexchange.com/users/34330",
"pm_score": 0,
"selected": false,
"text": "<p>The URL for <code>archive.php</code> to list all posts which do not have a category assigned is:</p>\n\n<blockquote>\n <p><strong><a href=\"http://example.com/uncategorized/\" rel=\"nofollow\">http://example.com/uncategorized/</a></strong></p>\n</blockquote>\n\n<p>This can be found be going to any post which has not been assigned a category, and examining the URL. Just remove the post slug to arrive at the relevant archive:</p>\n\n<blockquote>\n <p><a href=\"http://local.example.com/uncategorized/hello-world/\" rel=\"nofollow\">http://local.example.com/uncategorized/hello-world/</a></p>\n</blockquote>\n"
},
{
"answer_id": 228171,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 1,
"selected": false,
"text": "<p><code>archive.php</code> is very broad template, possibly used for many kinds of archives.</p>\n\n<p>If you mean common reverse chronological view the link to that would be return of <a href=\"https://developer.wordpress.org/reference/functions/get_post_type_archive_link/\" rel=\"nofollow\"><code>get_post_type_archive_link()</code></a> for the specific post type.</p>\n\n<p>Note that the native <code>post</code> post type is special case. For it archive is typically either site root or posts page, depending on site's configuration. Those <em>never</em> use <code>archive.php</code>, according to <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow\">template hierarchy</a>.</p>\n"
}
] |
2016/05/29
|
[
"https://wordpress.stackexchange.com/questions/228152",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34330/"
] |
Consider the simplest `archive.php` possible:
```
<?php
get_header();
while ( have_posts() ) {
the_post();
the_title();
}
get_footer();
```
**What address should I type into the browser to get to this page and display all posts?** The permalink Custom Struction is set as "/%category%/%postname%/". I have tried going <http://example.com/posts> but that page returns simply a 404 error.
|
`archive.php` is very broad template, possibly used for many kinds of archives.
If you mean common reverse chronological view the link to that would be return of [`get_post_type_archive_link()`](https://developer.wordpress.org/reference/functions/get_post_type_archive_link/) for the specific post type.
Note that the native `post` post type is special case. For it archive is typically either site root or posts page, depending on site's configuration. Those *never* use `archive.php`, according to [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/).
|
228,157 |
<p>Is there any way to determine if a particular custom post type will be displayed on default archive pages or search results?</p>
<p>e.g.
Given a post type named (badly) <strong>books</strong>, is there a way to tell <strong>via code</strong> any of the following:</p>
<ul>
<li>If books show up on date archives</li>
<li>If books show up in search results</li>
<li>If books show up in author archives</li>
</ul>
<p>I know how to make custom post types show up in these, but I've been doing a bit of digging and can see no clean way to determine if a particular custom post type will show up in any of the above or not.</p>
<p>The main reason I'm looking for this is that I'm creating custom breadcrumb bars for a theme... and it would be nice to be able to show an authors breadcrumb bar if the custom post being viewed supports author functionality <strong>and</strong> shows up in the author archive.</p>
|
[
{
"answer_id": 228161,
"author": "Gregcta",
"author_id": 94533,
"author_profile": "https://wordpress.stackexchange.com/users/94533",
"pm_score": 0,
"selected": false,
"text": "<p>If you are on the front, on template you can use the <a href=\"https://codex.wordpress.org/Function_Reference/is_post_type_archive\" rel=\"nofollow\"><code>is_post_type_archive( $post_types )</code></a> conditional tag function. <code>$post_types</code> can be a <code>string</code> or an <code>array</code> of posts types to check against.</p>\n"
},
{
"answer_id": 228167,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 3,
"selected": true,
"text": "<p>You can <a href=\"https://developer.wordpress.org/reference/functions/get_post_type_object/\" rel=\"nofollow\">get the post type object</a> and check its properties. For example:</p>\n\n<pre><code>$post_type = get_post_type_object( 'books' );\nif( $post_type->exclude_from_search ) {\n // The post type is not included in search results\n}\nif( $post_type->has_archive ) {\n // The post type has archive\n}\n</code></pre>\n\n<p>As far I know, custom post types are not included in dates archives nor author archives if you don't code for it (using <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow\"><code>pre_get_posts</code></a> for example). I mean, those options are not available while registering a post type. So, there is no way to check it from post type object.</p>\n"
}
] |
2016/05/29
|
[
"https://wordpress.stackexchange.com/questions/228157",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66020/"
] |
Is there any way to determine if a particular custom post type will be displayed on default archive pages or search results?
e.g.
Given a post type named (badly) **books**, is there a way to tell **via code** any of the following:
* If books show up on date archives
* If books show up in search results
* If books show up in author archives
I know how to make custom post types show up in these, but I've been doing a bit of digging and can see no clean way to determine if a particular custom post type will show up in any of the above or not.
The main reason I'm looking for this is that I'm creating custom breadcrumb bars for a theme... and it would be nice to be able to show an authors breadcrumb bar if the custom post being viewed supports author functionality **and** shows up in the author archive.
|
You can [get the post type object](https://developer.wordpress.org/reference/functions/get_post_type_object/) and check its properties. For example:
```
$post_type = get_post_type_object( 'books' );
if( $post_type->exclude_from_search ) {
// The post type is not included in search results
}
if( $post_type->has_archive ) {
// The post type has archive
}
```
As far I know, custom post types are not included in dates archives nor author archives if you don't code for it (using [`pre_get_posts`](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) for example). I mean, those options are not available while registering a post type. So, there is no way to check it from post type object.
|
228,163 |
<p>I want to change some (20-30) of the defaults strings on Wordpress back-end (not to translate).</p>
<p>I know there is gettext filter but I think could lead to performance issues if we have a lot of strings.</p>
<p>Another method I tried was to create and use an admin-en_US.po file.</p>
<p>Which of the above methods are faster? Is there any better way? What do you suggest without affect performance?</p>
|
[
{
"answer_id": 228164,
"author": "kaiser",
"author_id": 385,
"author_profile": "https://wordpress.stackexchange.com/users/385",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, you can <a href=\"https://wordpress.stackexchange.com/questions/188332/override-default-wordpress-core-translation\">use the <code>gettext</code> filter</a>. No, it's not the fastest filter, but that is only true when you add a callback to that filter in the wild:</p>\n\n<h2>Bad Example</h2>\n\n<p>This is <strong>bad</strong> as it makes a string comparison for every of the hundreds of translatable requests in the current request:</p>\n\n<pre><code>add_filter( 'gettext', function( $translated, $original, $domain ) {\n return 'foo' === $original ? 'bar' : $translated;\n}, 10, 3 );\n</code></pre>\n\n<h2>Good Example</h2>\n\n<p>You can speed things up by adding the filter <em>right before you need it</em>, then remove it:</p>\n\n<p>Imagine the following bit of core, plugin or theme code (example):</p>\n\n<pre><code>do_action( 'before' );\n_e( 'foo', 'textdomain' );\n</code></pre>\n\n<p>Now let's write a callback for the <code>gettext</code> filter:</p>\n\n<pre><code>add_action( 'before', 'wpse228163GettextReplacement', 10, 3 );\n\nfunction wpse228163GettextReplacement( $translated, $original, $domain ) \n{\n // Instantly remove the filter so it only runs once\n remove_filter( current_filter(), __FUNCTION__ );\n\n return 'foo' === $original \n ? 'bar' \n : $translated;\n}\n</code></pre>\n\n<p><strong>ProTip:</strong> When you have multiple strings to replace, you can hook into the latest action or filter <em>before</em> your first string, then remove the callback in the next action or filter <em>after</em> your last string.</p>\n\n<pre><code>do_action( 'before' );\n_e( 'foo', 'textdomain' );\ndo_action( 'after' );\n</code></pre>\n\n<p>Add & Remove it:</p>\n\n<pre><code>add_action( 'before', function() {\n // Add filter\n add_filter( 'gettext', 'wpse228163GettextReplacement', 10, 3 );\n\n // Remove filter when we are done\n add_action( 'after', function() {\n remove_filter( 'gettext', 'wpse228163GettextReplacement' );\n } );\n} );\n</code></pre>\n"
},
{
"answer_id": 228165,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 3,
"selected": true,
"text": "<p>Additionally to kaiser's answer, you can load customized .mo files that overrides the original file using <a href=\"https://developer.wordpress.org/reference/hooks/load_textdomain_mofile/\" rel=\"nofollow\"><code>load_textdomain_mofile</code> filter</a>. For example:</p>\n\n<pre><code>add_filter( 'load_textdomain_mofile', 'cyb_filter_load_textdomain_mofile', 10, 2 );\nfunction cyb_filter_load_textdomain_mofile( $mofile, $domain ) {\n if ( $domain == 'some-textdomain-to-override' ) {\n $mofile = WP_LANG_DIR . '/overrides/' . basename( $mofile );\n }\n return $mofile;\n}\n</code></pre>\n\n<p>It may be faster but you will be required to check for changes on every update in order to keep your .mo file syncrhonized with the original.</p>\n"
},
{
"answer_id": 228166,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": -1,
"selected": false,
"text": "<p>After upvoting kaiser's answer I still feel the urge to point out that you are unlikely to write php code without DB access which will impact performance in a measurable way (unless you totally fuck it up).</p>\n\n<p>Theoretically speaking, the filter option should be more performant, especially in memory consumption (this is due to the fact core handles translation in a non optimized way) but there is something to be said for keeping things that do not actually belong to code out of the code.</p>\n"
}
] |
2016/05/29
|
[
"https://wordpress.stackexchange.com/questions/228163",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/30792/"
] |
I want to change some (20-30) of the defaults strings on Wordpress back-end (not to translate).
I know there is gettext filter but I think could lead to performance issues if we have a lot of strings.
Another method I tried was to create and use an admin-en\_US.po file.
Which of the above methods are faster? Is there any better way? What do you suggest without affect performance?
|
Additionally to kaiser's answer, you can load customized .mo files that overrides the original file using [`load_textdomain_mofile` filter](https://developer.wordpress.org/reference/hooks/load_textdomain_mofile/). For example:
```
add_filter( 'load_textdomain_mofile', 'cyb_filter_load_textdomain_mofile', 10, 2 );
function cyb_filter_load_textdomain_mofile( $mofile, $domain ) {
if ( $domain == 'some-textdomain-to-override' ) {
$mofile = WP_LANG_DIR . '/overrides/' . basename( $mofile );
}
return $mofile;
}
```
It may be faster but you will be required to check for changes on every update in order to keep your .mo file syncrhonized with the original.
|
228,183 |
<p>Can i add the <code>itemprop</code> to the <code>title</code> element and still use <code>wp_head()</code> and <code>add_theme_support( "title-tag" )</code>?</p>
<p>I want to create a theme and <a href="https://themes.trac.wordpress.org/ticket/29732#comment:23" rel="nofollow">get it approved on wordpres.org</a> which uses microdata.</p>
<p>The preceding mean i want the HTML code looks as follows:</p>
<pre><code><html itemscope itemtype="http://schema.org/WebPage" lang="en-US">
....
<title itemprop="name">WordPress Weblog Theme &#8211; Just another WordPress site</title>
....
</code></pre>
<p>Now i do not use <code>add_theme_support( "title-tag" )</code> and use the following code in header.php?</p>
<pre><code><title itemprop="name"><?php echo wp_get_document_title(); ?></title>
<?php wp_head(); ?>
</code></pre>
<p>Now the theme check plugin says:</p>
<blockquote>
<p>REQUIRED: The theme needs to have a call to wp_title(), ideally in the
header.php file. REQUIRED: The theme needs to have tags,
ideally in the header.php file. RECOMMENDED: No reference to
add_theme_support( "title-tag" ) was found in the theme. It is
recommended that the theme implement this functionality for WordPress
4.1 and above.</p>
</blockquote>
|
[
{
"answer_id": 228203,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>Unfortunately echoing the <code><title></code> tag is currently hardwired in <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/general-template.php\" rel=\"nofollow\"><code>general-template.php</code></a> (line 1062). It's in a private function, meaning that you cannot modify or overrule it. So, at the moment you cannot modify the tag. You might want to issue a <a href=\"https://core.trac.wordpress.org/\" rel=\"nofollow\">trac</a> to ask that they support this in the future.</p>\n"
},
{
"answer_id": 228225,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 3,
"selected": true,
"text": "<p>Since all <code>_wp_render_title_tag</code> does is check for <code>title-tag</code> theme support and wrap in <code><title></code> tags, there is really no reason why your existing implementation \"shall not pass\", since the proper implementation is already identical via:</p>\n\n<pre><code><title itemprop=\"name\"><?php echo wp_get_document_title(); ?></title>\n</code></pre>\n\n<p>when <code>_wp_render_title_tag</code> does:</p>\n\n<pre><code>echo '<title>' . wp_get_document_title() . '</title>' . \"\\n\";\n</code></pre>\n\n<p>(since Theme Check is a guideline check, so what if it can't tell that a standard actually has been followed, that should in theory not stop it from passing?)</p>\n\n<p>But in any case, you <em>can</em> get around this <em>and</em> improve the existing implementation at the same time by adding a customization override filter... by unhooking the existing action (as suggested by @birgire) and (my addition) hooking a wrapping function that calls <code>_wp_render_title_tag</code> and applies the filter to it:</p>\n\n<pre><code>if (has_action('wp_head','_wp_render_title_tag') == 1) {\n remove_action('wp_head','_wp_render_title_tag',1);\n add_action('wp_head','custom_wp_render_title_tag_filtered',1);\n}\n\nfunction custom_wp_render_title_tag_filtered() {\n if (function_exists('_wp_render_title_tag')) {\n ob_start(); \n _wp_render_title_tag(); \n $titletag = ob_get_contents();\n ob_end_clean();\n } else {$titletag = '';}\n return apply_filters('wp_render_title_tag_filter',$titletag);\n}\n</code></pre>\n\n<p>Since it's better practice to have a filter available anyway....... Then you can add your own use case customizations easily by using the new filter:</p>\n\n<pre><code>add_filter('wp_render_title_tag_filter','custom_wp_render_title_tag');\n\nfunction custom_wp_render_title_tag($titletag) {\n $titletag = str_replace('<title>','<title itemprop=\"name\">',$titletag);\n return $titletag;\n}\n</code></pre>\n\n<p>Of course it would be much cleaner if the core function was simply updated to:</p>\n\n<pre><code>function _wp_render_title_tag() {\n if ( ! current_theme_supports( 'title-tag' ) ) {\n return;\n }\n echo apply_filters( 'wp_render_title_tag' , '<title>' . wp_get_document_title() . '</title>' . \"\\n\" );\n}\n</code></pre>\n"
}
] |
2016/05/29
|
[
"https://wordpress.stackexchange.com/questions/228183",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31759/"
] |
Can i add the `itemprop` to the `title` element and still use `wp_head()` and `add_theme_support( "title-tag" )`?
I want to create a theme and [get it approved on wordpres.org](https://themes.trac.wordpress.org/ticket/29732#comment:23) which uses microdata.
The preceding mean i want the HTML code looks as follows:
```
<html itemscope itemtype="http://schema.org/WebPage" lang="en-US">
....
<title itemprop="name">WordPress Weblog Theme – Just another WordPress site</title>
....
```
Now i do not use `add_theme_support( "title-tag" )` and use the following code in header.php?
```
<title itemprop="name"><?php echo wp_get_document_title(); ?></title>
<?php wp_head(); ?>
```
Now the theme check plugin says:
>
> REQUIRED: The theme needs to have a call to wp\_title(), ideally in the
> header.php file. REQUIRED: The theme needs to have tags,
> ideally in the header.php file. RECOMMENDED: No reference to
> add\_theme\_support( "title-tag" ) was found in the theme. It is
> recommended that the theme implement this functionality for WordPress
> 4.1 and above.
>
>
>
|
Since all `_wp_render_title_tag` does is check for `title-tag` theme support and wrap in `<title>` tags, there is really no reason why your existing implementation "shall not pass", since the proper implementation is already identical via:
```
<title itemprop="name"><?php echo wp_get_document_title(); ?></title>
```
when `_wp_render_title_tag` does:
```
echo '<title>' . wp_get_document_title() . '</title>' . "\n";
```
(since Theme Check is a guideline check, so what if it can't tell that a standard actually has been followed, that should in theory not stop it from passing?)
But in any case, you *can* get around this *and* improve the existing implementation at the same time by adding a customization override filter... by unhooking the existing action (as suggested by @birgire) and (my addition) hooking a wrapping function that calls `_wp_render_title_tag` and applies the filter to it:
```
if (has_action('wp_head','_wp_render_title_tag') == 1) {
remove_action('wp_head','_wp_render_title_tag',1);
add_action('wp_head','custom_wp_render_title_tag_filtered',1);
}
function custom_wp_render_title_tag_filtered() {
if (function_exists('_wp_render_title_tag')) {
ob_start();
_wp_render_title_tag();
$titletag = ob_get_contents();
ob_end_clean();
} else {$titletag = '';}
return apply_filters('wp_render_title_tag_filter',$titletag);
}
```
Since it's better practice to have a filter available anyway....... Then you can add your own use case customizations easily by using the new filter:
```
add_filter('wp_render_title_tag_filter','custom_wp_render_title_tag');
function custom_wp_render_title_tag($titletag) {
$titletag = str_replace('<title>','<title itemprop="name">',$titletag);
return $titletag;
}
```
Of course it would be much cleaner if the core function was simply updated to:
```
function _wp_render_title_tag() {
if ( ! current_theme_supports( 'title-tag' ) ) {
return;
}
echo apply_filters( 'wp_render_title_tag' , '<title>' . wp_get_document_title() . '</title>' . "\n" );
}
```
|
228,208 |
<p>I have a multi author blog and i need show a global info message in top of add post page, so all authors can read it when they come in this specific page, how i can add it?
Thank you</p>
|
[
{
"answer_id": 228211,
"author": "Christine Cooper",
"author_id": 24875,
"author_profile": "https://wordpress.stackexchange.com/users/24875",
"pm_score": 1,
"selected": false,
"text": "<p>You can do this by hooking into the <code>edit-post.php</code> page. There are a variety of hooks you could use, for example, if you want to display a message below the edit title field, you could hook into <code>edit_form_after_title</code>.</p>\n\n<p>See the example code I have below with comments:</p>\n\n<pre><code>add_action(\n 'edit_form_after_title', // the hook\n 'wpse_228208' // the function\n);\n\nfunction wpse_228208() {\n\n global $post;\n\n // confirm if the post_type is 'post'\n if ($post->post_type!== 'post')\n return;\n\n // you can also perform a condition for post_status, for example, if you don't want to display the message if post is already published:\n if ($post->post_status!== 'publish')\n return;\n\n // here goes your message\n echo '<div style=\"\">Hello world!</div>';\n}\n</code></pre>\n"
},
{
"answer_id": 228212,
"author": "Patrick S",
"author_id": 30753,
"author_profile": "https://wordpress.stackexchange.com/users/30753",
"pm_score": 0,
"selected": false,
"text": "<p>To show it above the title you can do this.</p>\n\n<p>Add the following to your functions.php and make a js file of the same name in your theme directory.</p>\n\n<pre><code>function admin_js_custom() {\n $adminjs = get_stylesheet_directory_uri() . '/admin-js.js';\n echo '\"<script type=\"text/javascript\" src=\"'. $adminjs . '\"></script>\"';\n}\n\nadd_action('admin_footer', 'admin_js_custom');\n</code></pre>\n\n<p>And then place this code in the js file.</p>\n\n<pre><code>jQuery(function($) {\n var message = \"Message for the authors.\";\n $('<p>' + message + '</p>').insertBefore('#titlediv')\n});\n</code></pre>\n"
},
{
"answer_id": 228389,
"author": "Stew",
"author_id": 28605,
"author_profile": "https://wordpress.stackexchange.com/users/28605",
"pm_score": 1,
"selected": false,
"text": "<p>i solved with this code placed in functions.php</p>\n\n<pre><code>function my_admin_notice(){\necho '<div class=\"updated\">\n<p>message here!</p>\n</div>';\n}\nadd_action('admin_notices', 'my_admin_notice');\n</code></pre>\n"
}
] |
2016/05/30
|
[
"https://wordpress.stackexchange.com/questions/228208",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28605/"
] |
I have a multi author blog and i need show a global info message in top of add post page, so all authors can read it when they come in this specific page, how i can add it?
Thank you
|
You can do this by hooking into the `edit-post.php` page. There are a variety of hooks you could use, for example, if you want to display a message below the edit title field, you could hook into `edit_form_after_title`.
See the example code I have below with comments:
```
add_action(
'edit_form_after_title', // the hook
'wpse_228208' // the function
);
function wpse_228208() {
global $post;
// confirm if the post_type is 'post'
if ($post->post_type!== 'post')
return;
// you can also perform a condition for post_status, for example, if you don't want to display the message if post is already published:
if ($post->post_status!== 'publish')
return;
// here goes your message
echo '<div style="">Hello world!</div>';
}
```
|
228,220 |
<p>i'have added thumbnail image to Rss of my blog and I'm using this code to display the rss in another website .</p>
<p>please guide me how to add image thumbnail to this code ...</p>
<p>see the result at : <a href="http://pmanagers.org" rel="nofollow">Pmanagers.org</a></p>
<pre><code><?php // Get RSS Feed(s)
include_once( ABSPATH . WPINC . '/feed.php' );
// Get a SimplePie feed object from the specified feed source.
$rss = fetch_feed( 'http://pmanagers.org/blog/feed/' );
$maxitems = 0;
if ( ! is_wp_error( $rss ) ) :
$maxitems = $rss->get_item_quantity( 6 );
$rss_items = $rss->get_items( 0, $maxitems );
endif;
?>
<div class="headwrp">
<h4>Latest Blog posts</h4>
</div>
<ul>
<?php if ( $maxitems == 0 ) : ?>
<li><?php _e( 'No items', 'my-text-domain' ); ?></li>
<?php else : ?>
<?php // Loop through each feed item and display each item as a hyperlink. ?>
<div class=" owl-carousel">
<?php foreach ( $rss_items as $item ) : ?>
<div class="item">
<li id="news-single">
<a href="<?php echo esc_url( $item->get_permalink() ); ?>" target="_blank"
title="<?php printf( __( 'Posted %s', 'my-text-domain' ), $item->get_date('j F Y | g:i a') ); ?>">
<?php echo esc_html( $item->get_title() ); ?>
</a>
</li>
</div>
<?php endforeach; ?>
<?php endif; ?>
</ul>
</div>
</code></pre>
|
[
{
"answer_id": 230983,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 1,
"selected": false,
"text": "<p>Answer from comments:</p>\n\n<p>First, create a conditional to check if the user has already 'published' a post. If yes, simply redirect them.</p>\n\n<p>One can use <code>update_post_meta</code> with the post ID without any problem. Simply use that information to populate the fields.</p>\n"
},
{
"answer_id": 237456,
"author": "The J",
"author_id": 98010,
"author_profile": "https://wordpress.stackexchange.com/users/98010",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://codex.wordpress.org/wp_get_current_user\" rel=\"nofollow\">Check</a> the current user info, then <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Author_Parameters\" rel=\"nofollow\">query</a> for posts by that user, depending on query (has posts?), output the data/form you need.</p>\n\n<pre><code><?php\n // Retrieve current user info\n $current_user = wp_get_current_user(); \n\n // Prepare the query for posts by that author\n $args = array(\n 'author' => $current_user->ID, \n );\n $author_posts = new WP_Query( $args );\n\n // Depending on query results, output what you need\n if($author_posts->have_posts()) {\n // display the edit form\n } else {\n // display the new post form\n }\n\n?>\n</code></pre>\n"
}
] |
2016/05/30
|
[
"https://wordpress.stackexchange.com/questions/228220",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94919/"
] |
i'have added thumbnail image to Rss of my blog and I'm using this code to display the rss in another website .
please guide me how to add image thumbnail to this code ...
see the result at : [Pmanagers.org](http://pmanagers.org)
```
<?php // Get RSS Feed(s)
include_once( ABSPATH . WPINC . '/feed.php' );
// Get a SimplePie feed object from the specified feed source.
$rss = fetch_feed( 'http://pmanagers.org/blog/feed/' );
$maxitems = 0;
if ( ! is_wp_error( $rss ) ) :
$maxitems = $rss->get_item_quantity( 6 );
$rss_items = $rss->get_items( 0, $maxitems );
endif;
?>
<div class="headwrp">
<h4>Latest Blog posts</h4>
</div>
<ul>
<?php if ( $maxitems == 0 ) : ?>
<li><?php _e( 'No items', 'my-text-domain' ); ?></li>
<?php else : ?>
<?php // Loop through each feed item and display each item as a hyperlink. ?>
<div class=" owl-carousel">
<?php foreach ( $rss_items as $item ) : ?>
<div class="item">
<li id="news-single">
<a href="<?php echo esc_url( $item->get_permalink() ); ?>" target="_blank"
title="<?php printf( __( 'Posted %s', 'my-text-domain' ), $item->get_date('j F Y | g:i a') ); ?>">
<?php echo esc_html( $item->get_title() ); ?>
</a>
</li>
</div>
<?php endforeach; ?>
<?php endif; ?>
</ul>
</div>
```
|
Answer from comments:
First, create a conditional to check if the user has already 'published' a post. If yes, simply redirect them.
One can use `update_post_meta` with the post ID without any problem. Simply use that information to populate the fields.
|
228,222 |
<p>I'm looking for a way to show a certain pinterest pinboard in a post. </p>
<p>I've found in the <a href="https://en.support.wordpress.com/embed-from-pinterest/" rel="nofollow">WordPress.com Documentation</a> that you can simply post your pinboards URL there. This is not possible on a selfhosted Wordpress installation so I guess that is something specific to wordpress.com.</p>
<p>What would be the easiest way to add a URL Handler that translates the pinterest URL into the needed embed code and include the pinterest js file?</p>
|
[
{
"answer_id": 228226,
"author": "Karthikeyani Srijish",
"author_id": 86125,
"author_profile": "https://wordpress.stackexchange.com/users/86125",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://i.stack.imgur.com/KCG6K.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KCG6K.png\" alt=\"enter image description here\"></a>Go to Pinterest site and open a pin which you want to embed on your post. Now you can find <strong>3 dots</strong> near <strong>send</strong> button in the top of the pin. Click that dots and you can see \"<strong>Embed</strong>\" option. Now click that.</p>\n\n<p>Pinterest will give you 5 options to embed their content.</p>\n\n<ol>\n<li>Pin</li>\n<li>Profile</li>\n<li>Board</li>\n<li>Follow</li>\n<li>and Pin it button</li>\n</ol>\n\n<p>Based on your requirement, select the option and scroll down. You can find embed code at the bottom of the page. Just copy and paste in your post.</p>\n\n<p><strong>Note :</strong> The script tag should be included once in a page.</p>\n"
},
{
"answer_id": 228228,
"author": "heine",
"author_id": 94921,
"author_profile": "https://wordpress.stackexchange.com/users/94921",
"pm_score": 2,
"selected": true,
"text": "<p>I found that <a href=\"https://wordpress.org/plugins/pinterest-widgets\" rel=\"nofollow\">https://wordpress.org/plugins/pinterest-widgets</a> actually has the needed functionality but doesn't mention it in the description.</p>\n\n<p>After installing and activating you can add a pinboard to a post by using the following shortcodes</p>\n\n<pre><code>[pin_board url=\"http://www.pinterest.com/pinterest/pin-pets/\"]\n[pin_board url=\"http://www.pinterest.com/pinterest/pin-pets/\" size=\"header\"]\n[pin_board url=\"http://www.pinterest.com/pinterest/pin-pets/\" size=\"custom\" image_width=\"100\" board_width=\"900\" board_height=\"450\"]\n</code></pre>\n\n<p>more options can be found on the plugins \"settings\" page after installing.</p>\n"
}
] |
2016/05/30
|
[
"https://wordpress.stackexchange.com/questions/228222",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94921/"
] |
I'm looking for a way to show a certain pinterest pinboard in a post.
I've found in the [WordPress.com Documentation](https://en.support.wordpress.com/embed-from-pinterest/) that you can simply post your pinboards URL there. This is not possible on a selfhosted Wordpress installation so I guess that is something specific to wordpress.com.
What would be the easiest way to add a URL Handler that translates the pinterest URL into the needed embed code and include the pinterest js file?
|
I found that <https://wordpress.org/plugins/pinterest-widgets> actually has the needed functionality but doesn't mention it in the description.
After installing and activating you can add a pinboard to a post by using the following shortcodes
```
[pin_board url="http://www.pinterest.com/pinterest/pin-pets/"]
[pin_board url="http://www.pinterest.com/pinterest/pin-pets/" size="header"]
[pin_board url="http://www.pinterest.com/pinterest/pin-pets/" size="custom" image_width="100" board_width="900" board_height="450"]
```
more options can be found on the plugins "settings" page after installing.
|
228,223 |
<p>I am including a partial file both in <code>header.php</code> and in <code>footer.php</code> with <code>get_template_part('content-form');</code> </p>
<p>Is there an <code>if</code> clause I can use to check from where the file is being called? If it is called from within <code>footer.php</code>, then I would like to add a class name.</p>
<pre><code><div class="default-class <?php if (called_from_footer) echo 'footer-class'; ?>">
</div>
</code></pre>
<p>I could do this and style accordingly if there isn't a better solution, I am just curious:</p>
<pre><code><div class=footer-container">
<?php get_template_part('content-form') ;?>
</div>
</code></pre>
|
[
{
"answer_id": 228233,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 2,
"selected": false,
"text": "<p>There are many good solutions for doing this, you should follow the link that cjbj has provided in the comments.</p>\n\n<p>I am suggesting to use PHP's <a href=\"http://php.net/manual/en/function.debug-backtrace.php\" rel=\"nofollow\"><code>debug_backtrace()</code></a> function:</p>\n\n<pre><code>function wpse_228223_verify_caller_file( $file_name, $files = array(), $dir = '' ) {\n\n if( empty( $files ) ) {\n $files = debug_backtrace();\n }\n\n if( ! $dir ) {\n $dir = get_stylesheet_directory() . '/';\n }\n\n $dir = str_replace( \"/\", \"\\\\\", $dir );\n $caller_theme_file = array();\n\n foreach( $files as $file ) {\n if( false !== mb_strpos($file['file'], $dir) ) {\n $caller_theme_file[] = $file['file'];\n }\n }\n\n if( $file_name ) {\n return in_array( $dir . $file_name, $caller_theme_file );\n }\n\n return;\n\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<p>In your <code>content-form</code> template, pass the file name in the first param:</p>\n\n<pre><code>echo var_dump( wpse_228223_verify_caller_file( 'header.php' ) ); // called from header\necho var_dump( wpse_228223_verify_caller_file( 'footer.php' ) ); // called from footer\n</code></pre>\n\n<p>and there in your template you can add the appropriate class names..</p>\n\n<p>Please give it few tests first. The way I tested it it worked fine. Since you are creating your own custom template which won't be called by default unless your call it, it should work fine.</p>\n"
},
{
"answer_id": 228236,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 4,
"selected": true,
"text": "<p>This is not a <em>true</em> solution to your problem (checking which template loaded another), but it will work to test if the footer has been loaded or not, and thus if it's loading your partial:</p>\n\n<pre><code>if ( did_action( 'get_footer' ) ) echo 'footer-class';\n</code></pre>\n"
},
{
"answer_id": 228274,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>If you really want it quick 'n dirty, just use a global variable (hey, WP is doing it all the time, so why can't you?). Set it before the call and read it afterwards. Like this:</p>\n\n<p>In <code>functions.php</code>: <code>global $contentform_origin = '';</code></p>\n\n<p>In <code>header.php</code>: <code>$contentform_origin = 'header'; get_template_part('content-form');</code></p>\n\n<p>In <code>footer.php</code>: <code>$contentform_origin = 'footer'; get_template_part('content-form');</code></p>\n\n<p>In <code>content-form.php</code>: <code><div class=\"default-class <?php echo $contentform_origin ?>-class\">\n</div></code></p>\n\n<p>Don't forget to declare <code>$contentform_origin</code> at the beginning op each php file.</p>\n"
},
{
"answer_id": 228277,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 2,
"selected": false,
"text": "<p>Honestly, I think that best solution for your specific issue is <a href=\"https://wordpress.stackexchange.com/a/228236/35541\">the one form <strong>@TheDeadMedic</strong></a>.</p>\n\n<p>It might be a little \"fragile\" because <code>do_action('get_footer')</code> can be done in any file... but what's not fragile in WordPress?</p>\n\n<p>An alternative solution, just for \"academic purpose\" could be make use of PHP <a href=\"http://php.net/manual/en/function.get-included-files.php\" rel=\"nofollow noreferrer\"><code>get_included_files()</code></a> checking that <code>footer.php</code> was required:</p>\n\n<pre><code>function themeFileRequired($file) {\n\n $paths = array(\n wp_normalize_path(get_stylesheet_directory().'/'.$file.'.php'),\n wp_normalize_path(get_template_directory().'/'.$file.'.php'),\n );\n\n $included = array_map('wp_normalize_path', get_included_files());\n\n $intersect = array_intersect($paths, $included);\n\n return ! empty($intersect);\n}\n</code></pre>\n\n<p>And then:</p>\n\n<pre><code><div class=\"default-class <?= if (themeFileRequired('footer') echo 'footer-class'; ?>\">\n</div>\n</code></pre>\n"
}
] |
2016/05/30
|
[
"https://wordpress.stackexchange.com/questions/228223",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85304/"
] |
I am including a partial file both in `header.php` and in `footer.php` with `get_template_part('content-form');`
Is there an `if` clause I can use to check from where the file is being called? If it is called from within `footer.php`, then I would like to add a class name.
```
<div class="default-class <?php if (called_from_footer) echo 'footer-class'; ?>">
</div>
```
I could do this and style accordingly if there isn't a better solution, I am just curious:
```
<div class=footer-container">
<?php get_template_part('content-form') ;?>
</div>
```
|
This is not a *true* solution to your problem (checking which template loaded another), but it will work to test if the footer has been loaded or not, and thus if it's loading your partial:
```
if ( did_action( 'get_footer' ) ) echo 'footer-class';
```
|
228,251 |
<p>Using the google page speed test i saw that some images were too large and needed to be resized. I used the ftp to download the necessary images, resized them locally, and then used the media upload tool to import them into Wordpress. </p>
<p>I went to each relevant post and changed the feature image to use the new ones. In the media library the file name is the same as the updated images. However after updating and using the chrome inspect tool, I see that it is still using the old image size even though the visible appearance has changed.</p>
<p>The filenames are confusing me. The original images were named as follows: <code>image-1000x1000</code>. The new ones were named <code>image-500x500</code>. After updating the posts with the new images, chrome inspect is now showing: <code>image-500-1000x500-100</code>. What does this mean? Also, the original size of the photo is still the larger one. </p>
<p>Below is an image of the problem. Notice the size of the <strong>natural image</strong> it should be <code>450x450</code> now but it isn't.</p>
<p><a href="https://i.stack.imgur.com/veW7P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/veW7P.png" alt="enter image description here"></a></p>
|
[
{
"answer_id": 228233,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 2,
"selected": false,
"text": "<p>There are many good solutions for doing this, you should follow the link that cjbj has provided in the comments.</p>\n\n<p>I am suggesting to use PHP's <a href=\"http://php.net/manual/en/function.debug-backtrace.php\" rel=\"nofollow\"><code>debug_backtrace()</code></a> function:</p>\n\n<pre><code>function wpse_228223_verify_caller_file( $file_name, $files = array(), $dir = '' ) {\n\n if( empty( $files ) ) {\n $files = debug_backtrace();\n }\n\n if( ! $dir ) {\n $dir = get_stylesheet_directory() . '/';\n }\n\n $dir = str_replace( \"/\", \"\\\\\", $dir );\n $caller_theme_file = array();\n\n foreach( $files as $file ) {\n if( false !== mb_strpos($file['file'], $dir) ) {\n $caller_theme_file[] = $file['file'];\n }\n }\n\n if( $file_name ) {\n return in_array( $dir . $file_name, $caller_theme_file );\n }\n\n return;\n\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<p>In your <code>content-form</code> template, pass the file name in the first param:</p>\n\n<pre><code>echo var_dump( wpse_228223_verify_caller_file( 'header.php' ) ); // called from header\necho var_dump( wpse_228223_verify_caller_file( 'footer.php' ) ); // called from footer\n</code></pre>\n\n<p>and there in your template you can add the appropriate class names..</p>\n\n<p>Please give it few tests first. The way I tested it it worked fine. Since you are creating your own custom template which won't be called by default unless your call it, it should work fine.</p>\n"
},
{
"answer_id": 228236,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 4,
"selected": true,
"text": "<p>This is not a <em>true</em> solution to your problem (checking which template loaded another), but it will work to test if the footer has been loaded or not, and thus if it's loading your partial:</p>\n\n<pre><code>if ( did_action( 'get_footer' ) ) echo 'footer-class';\n</code></pre>\n"
},
{
"answer_id": 228274,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>If you really want it quick 'n dirty, just use a global variable (hey, WP is doing it all the time, so why can't you?). Set it before the call and read it afterwards. Like this:</p>\n\n<p>In <code>functions.php</code>: <code>global $contentform_origin = '';</code></p>\n\n<p>In <code>header.php</code>: <code>$contentform_origin = 'header'; get_template_part('content-form');</code></p>\n\n<p>In <code>footer.php</code>: <code>$contentform_origin = 'footer'; get_template_part('content-form');</code></p>\n\n<p>In <code>content-form.php</code>: <code><div class=\"default-class <?php echo $contentform_origin ?>-class\">\n</div></code></p>\n\n<p>Don't forget to declare <code>$contentform_origin</code> at the beginning op each php file.</p>\n"
},
{
"answer_id": 228277,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 2,
"selected": false,
"text": "<p>Honestly, I think that best solution for your specific issue is <a href=\"https://wordpress.stackexchange.com/a/228236/35541\">the one form <strong>@TheDeadMedic</strong></a>.</p>\n\n<p>It might be a little \"fragile\" because <code>do_action('get_footer')</code> can be done in any file... but what's not fragile in WordPress?</p>\n\n<p>An alternative solution, just for \"academic purpose\" could be make use of PHP <a href=\"http://php.net/manual/en/function.get-included-files.php\" rel=\"nofollow noreferrer\"><code>get_included_files()</code></a> checking that <code>footer.php</code> was required:</p>\n\n<pre><code>function themeFileRequired($file) {\n\n $paths = array(\n wp_normalize_path(get_stylesheet_directory().'/'.$file.'.php'),\n wp_normalize_path(get_template_directory().'/'.$file.'.php'),\n );\n\n $included = array_map('wp_normalize_path', get_included_files());\n\n $intersect = array_intersect($paths, $included);\n\n return ! empty($intersect);\n}\n</code></pre>\n\n<p>And then:</p>\n\n<pre><code><div class=\"default-class <?= if (themeFileRequired('footer') echo 'footer-class'; ?>\">\n</div>\n</code></pre>\n"
}
] |
2016/05/30
|
[
"https://wordpress.stackexchange.com/questions/228251",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92793/"
] |
Using the google page speed test i saw that some images were too large and needed to be resized. I used the ftp to download the necessary images, resized them locally, and then used the media upload tool to import them into Wordpress.
I went to each relevant post and changed the feature image to use the new ones. In the media library the file name is the same as the updated images. However after updating and using the chrome inspect tool, I see that it is still using the old image size even though the visible appearance has changed.
The filenames are confusing me. The original images were named as follows: `image-1000x1000`. The new ones were named `image-500x500`. After updating the posts with the new images, chrome inspect is now showing: `image-500-1000x500-100`. What does this mean? Also, the original size of the photo is still the larger one.
Below is an image of the problem. Notice the size of the **natural image** it should be `450x450` now but it isn't.
[](https://i.stack.imgur.com/veW7P.png)
|
This is not a *true* solution to your problem (checking which template loaded another), but it will work to test if the footer has been loaded or not, and thus if it's loading your partial:
```
if ( did_action( 'get_footer' ) ) echo 'footer-class';
```
|
228,256 |
<p>Semi-new to WordPress, so apologies is this is an obvious question!</p>
<p>I'm trying to execute some JavaScript on a WordPress site, but only on the child pages of a specific parent page - so, I have example.com/books, and I want the script to run on example.com/books/foo, example.com/books/bar, example.com/books/wee, and so forth. I don't want it to run on example.com/books.</p>
<p>I know that I could just add in the script on each individual page, but I have other people editing the site who may add new book child pages, and they will not feel comfortable adding in Javascript.</p>
<p>Any solutions?</p>
|
[
{
"answer_id": 228233,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 2,
"selected": false,
"text": "<p>There are many good solutions for doing this, you should follow the link that cjbj has provided in the comments.</p>\n\n<p>I am suggesting to use PHP's <a href=\"http://php.net/manual/en/function.debug-backtrace.php\" rel=\"nofollow\"><code>debug_backtrace()</code></a> function:</p>\n\n<pre><code>function wpse_228223_verify_caller_file( $file_name, $files = array(), $dir = '' ) {\n\n if( empty( $files ) ) {\n $files = debug_backtrace();\n }\n\n if( ! $dir ) {\n $dir = get_stylesheet_directory() . '/';\n }\n\n $dir = str_replace( \"/\", \"\\\\\", $dir );\n $caller_theme_file = array();\n\n foreach( $files as $file ) {\n if( false !== mb_strpos($file['file'], $dir) ) {\n $caller_theme_file[] = $file['file'];\n }\n }\n\n if( $file_name ) {\n return in_array( $dir . $file_name, $caller_theme_file );\n }\n\n return;\n\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<p>In your <code>content-form</code> template, pass the file name in the first param:</p>\n\n<pre><code>echo var_dump( wpse_228223_verify_caller_file( 'header.php' ) ); // called from header\necho var_dump( wpse_228223_verify_caller_file( 'footer.php' ) ); // called from footer\n</code></pre>\n\n<p>and there in your template you can add the appropriate class names..</p>\n\n<p>Please give it few tests first. The way I tested it it worked fine. Since you are creating your own custom template which won't be called by default unless your call it, it should work fine.</p>\n"
},
{
"answer_id": 228236,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 4,
"selected": true,
"text": "<p>This is not a <em>true</em> solution to your problem (checking which template loaded another), but it will work to test if the footer has been loaded or not, and thus if it's loading your partial:</p>\n\n<pre><code>if ( did_action( 'get_footer' ) ) echo 'footer-class';\n</code></pre>\n"
},
{
"answer_id": 228274,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>If you really want it quick 'n dirty, just use a global variable (hey, WP is doing it all the time, so why can't you?). Set it before the call and read it afterwards. Like this:</p>\n\n<p>In <code>functions.php</code>: <code>global $contentform_origin = '';</code></p>\n\n<p>In <code>header.php</code>: <code>$contentform_origin = 'header'; get_template_part('content-form');</code></p>\n\n<p>In <code>footer.php</code>: <code>$contentform_origin = 'footer'; get_template_part('content-form');</code></p>\n\n<p>In <code>content-form.php</code>: <code><div class=\"default-class <?php echo $contentform_origin ?>-class\">\n</div></code></p>\n\n<p>Don't forget to declare <code>$contentform_origin</code> at the beginning op each php file.</p>\n"
},
{
"answer_id": 228277,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 2,
"selected": false,
"text": "<p>Honestly, I think that best solution for your specific issue is <a href=\"https://wordpress.stackexchange.com/a/228236/35541\">the one form <strong>@TheDeadMedic</strong></a>.</p>\n\n<p>It might be a little \"fragile\" because <code>do_action('get_footer')</code> can be done in any file... but what's not fragile in WordPress?</p>\n\n<p>An alternative solution, just for \"academic purpose\" could be make use of PHP <a href=\"http://php.net/manual/en/function.get-included-files.php\" rel=\"nofollow noreferrer\"><code>get_included_files()</code></a> checking that <code>footer.php</code> was required:</p>\n\n<pre><code>function themeFileRequired($file) {\n\n $paths = array(\n wp_normalize_path(get_stylesheet_directory().'/'.$file.'.php'),\n wp_normalize_path(get_template_directory().'/'.$file.'.php'),\n );\n\n $included = array_map('wp_normalize_path', get_included_files());\n\n $intersect = array_intersect($paths, $included);\n\n return ! empty($intersect);\n}\n</code></pre>\n\n<p>And then:</p>\n\n<pre><code><div class=\"default-class <?= if (themeFileRequired('footer') echo 'footer-class'; ?>\">\n</div>\n</code></pre>\n"
}
] |
2016/05/30
|
[
"https://wordpress.stackexchange.com/questions/228256",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94934/"
] |
Semi-new to WordPress, so apologies is this is an obvious question!
I'm trying to execute some JavaScript on a WordPress site, but only on the child pages of a specific parent page - so, I have example.com/books, and I want the script to run on example.com/books/foo, example.com/books/bar, example.com/books/wee, and so forth. I don't want it to run on example.com/books.
I know that I could just add in the script on each individual page, but I have other people editing the site who may add new book child pages, and they will not feel comfortable adding in Javascript.
Any solutions?
|
This is not a *true* solution to your problem (checking which template loaded another), but it will work to test if the footer has been loaded or not, and thus if it's loading your partial:
```
if ( did_action( 'get_footer' ) ) echo 'footer-class';
```
|
228,266 |
<p>I'm developing a WordPress theme using a template engine. I want my code to be as much compatible as possible with WP core functionality.</p>
<h2>Some context first</h2>
<p>My first problem was to find a way to <em>resolve</em> the template starting from a WP query. I solved that one using a library of mine, <a href="https://github.com/Brain-WP/Hierarchy">Brain\Hierarchy</a>.</p>
<p>Regarding <code>get_template_part()</code> and other functions that loads partials like <code>get_header()</code>, <code>get_footer()</code> and similar, it was pretty easy to write wrapper to template engine partial functionality. </p>
<h2>The issue</h2>
<p>My problem is now how to load comments template.</p>
<p>WordPress function <a href="https://developer.wordpress.org/reference/functions/comments_template/"><code>comments_template()</code></a> is a ~200 lines function that does a lot of things, which I want to do as well for maximum core compatibility.</p>
<p>However, as soon as I call <code>comments_template()</code>, a file is <code>require</code>d, it is the first of:</p>
<ul>
<li>the file in the constant <code>COMMENTS_TEMPLATE</code>, if defined</li>
<li><code>comments.php</code> in theme folder, if found</li>
<li><code>/theme-compat/comments.php</code> in WP includes folder as last resort fallback</li>
</ul>
<p>In short, there's no way to prevent the function to load a PHP file, which is not desirable for me, because I need to <em>render</em> my templates and not simply use <code>require</code>.</p>
<h2>Current solution</h2>
<p>At the moment, I'm shipping an empty <code>comments.php</code> file and I'm using <a href="https://developer.wordpress.org/reference/hooks/comments_template/"><code>'comments_template'</code></a> filter hook, to know which template WordPress wants to loads, and use feature from my template engine to load the template.</p>
<p>Something like this:</p>
<pre><code>function engineCommentsTemplate($myEngine) {
$toLoad = null; // this will hold the template path
$tmplGetter = function($tmpl) use(&$toLoad) {
$toLoad = $tmpl;
return $tmpl;
};
// late priority to allow filters attached here to do their job
add_filter('comments_template', $tmplGetter, PHP_INT_MAX);
// this will load an empty comments.php file I ship in my theme
comments_template();
remove_filter('comments_template', $tmplGetter, PHP_INT_MAX);
if (is_file($toLoad) && is_readable($toLoad)) {
return $myEngine->render($toLoad);
}
return '';
}
</code></pre>
<h2>The question</h2>
<p>This works, is core compatible, but... is there a way to make it work without having to ship an empty <code>comments.php</code>?</p>
<p>Because I don't like it.</p>
|
[
{
"answer_id": 228268,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 3,
"selected": true,
"text": "<p>Not sure the following solution is <em>better</em> than the solution in OP, let's just say is an alternative, probably more hackish, solution.</p>\n\n<p>I think you can use a PHP exception to stop WordPress execution when <code>'comments_template'</code> filter is applied.</p>\n\n<p>You can use a custom exception class as a DTO to <em>carry</em> the template.</p>\n\n<p>This is a draft for the excepion:</p>\n\n<pre><code>class CommentsTemplateException extends \\Exception {\n\n protected $template;\n\n public static function forTemplate($template) {\n $instance = new static();\n $instance->template = $template;\n\n return $instance;\n }\n\n public function template() {\n return $this->template;\n }\n}\n</code></pre>\n\n<p>With this exception class available, your function becomes:</p>\n\n<pre><code>function engineCommentsTemplate($myEngine) {\n\n $filter = function($template) {\n throw CommentsTemplateException::forTemplate($template);\n }; \n\n try {\n add_filter('comments_template', $filter, PHP_INT_MAX); \n // this will throw the excption that makes `catch` block run\n comments_template();\n } catch(CommentsTemplateException $e) {\n return $myEngine->render($e->template());\n } finally {\n remove_filter('comments_template', $filter, PHP_INT_MAX);\n }\n}\n</code></pre>\n\n<p>The <code>finally</code> block requires PHP 5.5+.</p>\n\n<p>Works the same way, and doesn't require an empty template.</p>\n"
},
{
"answer_id": 228273,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 2,
"selected": false,
"text": "<p>I have wrestled with this before and my solution was — it can knock itself out requiring file, as long as it doesn't <em>do</em> anything.</p>\n\n<p>Here is relevant code from my <a href=\"https://github.com/Rarst/meadow\" rel=\"nofollow\">Meadow templating project</a>:</p>\n\n<pre><code>public function comments_template( \\Twig_Environment $env, $context, $file = 'comments.twig', $separate_comments = false ) {\n\n try {\n $env->loadTemplate( $file );\n } catch ( \\Twig_Error_Loader $e ) {\n ob_start();\n comments_template( '/comments.php', $separate_comments );\n return ob_get_clean();\n }\n\n add_filter( 'comments_template', array( $this, 'return_blank_template' ) );\n comments_template( '/comments.php', $separate_comments );\n remove_filter( 'comments_template', array( $this, 'return_blank_template' ) );\n\n return twig_include( $env, $context, $file );\n}\n\npublic function return_blank_template() {\n\n return __DIR__ . '/blank.php';\n}\n</code></pre>\n\n<p>I let <code>comments_template()</code> go through the motions to set up globals and such, but feed it empty PHP file to <code>require</code> and move on to my actual Twig template for output.</p>\n\n<p>Note that this requires to be able to intercept initial <code>comments_template()</code> call, which I can do since my Twig template is calling intermediary abstraction rather than actual PHP function.</p>\n\n<p>While I still have to ship empty file for it, I do so in library and implementing theme doesn't have to care about it at all.</p>\n"
},
{
"answer_id": 228283,
"author": "kaiser",
"author_id": 385,
"author_profile": "https://wordpress.stackexchange.com/users/385",
"pm_score": 2,
"selected": false,
"text": "<h2>Solution: Use a temporary file – with a unique file name</h2>\n\n<p>After a lot of jumps and crawling into the dirtiest corners of PHP, I rephrased the question to just:</p>\n\n<blockquote>\n <p>How can one <em>trick</em> PHP into returning <code>TRUE</code> for <code>file_exists( $file )</code>?</p>\n</blockquote>\n\n<p>as the code in core just is</p>\n\n<pre><code>file_exists( apply_filters( 'comments_template', $template ) )\n</code></pre>\n\n<p>Then the question was solved quicker:</p>\n\n<pre><code>$template = tempnam( __DIR__, '' );\n</code></pre>\n\n<p>and that's it. Maybe it would be better to use <code>wp_upload_dir()</code> instead:</p>\n\n<pre><code>$uploads = wp_upload_dir();\n$template = tempname( $uploads['basedir'], '' );\n</code></pre>\n\n<p>Another option might be to use <a href=\"https://developer.wordpress.org/reference/functions/get_temp_dir/\" rel=\"nofollow\"><code>get_temp_dir()</code></a> which wraps <code>WP_TEMP_DIR</code>. Hint: It strangely falls back to <code>/tmp/</code> so files will <em>not</em> get preserved between reboots, which <code>/var/tmp/</code> would. One can do a simple string comparison at the end and check the return value and then fix this in case it's needed – which is not in this case:</p>\n\n<pre><code>$template = tempname( get_temp_dir(), '' )\n</code></pre>\n\n<p>Now to quickly test if there are errors thrown for a temporary file without contents:</p>\n\n<pre><code><?php\nerror_reporting( E_ALL );\n$template = tempnam( __DIR__, '' );\nvar_dump( $template );\nrequire $template;\n</code></pre>\n\n<p>And: <strong>No Errors</strong> → working.</p>\n\n<p><strong>EDIT:</strong> As <strong>@toscho</strong> pointed out in the comments, there's still a <strong>better</strong> way to do it:</p>\n\n<pre><code>$template = tempnam( trailingslashit( untrailingslashit( sys_get_temp_dir() ) ), 'comments.php' );\n</code></pre>\n\n<p>Note: According to <a href=\"http://php.net/manual/en/function.sys-get-temp-dir.php#80690\" rel=\"nofollow\">a users note on php.net docs</a>, the <code>sys_get_temp_dir()</code> behavior differs between systems. Therefore the result gets the trailing slash removed, then added again. As the core bug <a href=\"https://core.trac.wordpress.org/ticket/22267\" rel=\"nofollow\">#22267</a> is fixed, this should work on Win/ IIS servers now as well.</p>\n\n<p>Your refactored function (not tested):</p>\n\n<pre><code>function engineCommentsTemplate( $engine )\n{\n $template = null;\n\n $tmplGetter = function( $original ) use( &$template ) {\n $template = $original;\n return tempnam( \n trailingslashit( untrailingslashit( sys_get_temp_dir() ) ),\n 'comments.php'\n );\n };\n\n add_filter( 'comments_template', $tmplGetter, PHP_INT_MAX );\n\n comments_template();\n\n remove_filter( 'comments_template', $tmplGetter, PHP_INT_MAX );\n\n if ( is_file( $template ) && is_readable( $template ) ) {\n return $engine->render( $template );\n }\n\n return '';\n}\n</code></pre>\n\n<p>Bonus Nr.1: <code>tmpfile()</code> will return <code>NULL</code>. Yeah, really.</p>\n\n<p>Bonus Nr.2: <a href=\"http://www.php.net/manual/en/function.file-exists.php\" rel=\"nofollow\"><code>file_exists( __DIR__ )</code></a> will return <code>TRUE</code>. Yeah, really … in case you forgot.</p>\n\n<p><sup>^ This leads to an actual bug in WP core.</sup></p>\n\n<hr>\n\n<p>To help others going in explorer mode and finding those (badly to undocumented pieces), I will quickly sum up what I tried:</p>\n\n<h2>Attempt 1: Temporary file in memory</h2>\n\n<p>The first attempt I made was to create a stream to a temporary file, using <code>php://temp</code>. From the PHP docs:</p>\n\n<blockquote>\n <p>The only difference between the two is that <code>php://memory</code> will always store its data in memory, whereas <code>php://temp</code> will use a temporary file once the amount of data stored hits a predefined limit (the default is 2 MB). The location of this temporary file is determined in the same way as the <code>sys_get_temp_dir()</code> function.</p>\n</blockquote>\n\n<p>The code:</p>\n\n<pre><code>$handle = fopen( 'php://temp', 'r+' );\nfwrite( $handle, 'foo' );\nrewind( $handle );\nvar_dump( file_exist( stream_get_contents( $handle, 5 ) );\n</code></pre>\n\n<p>Finding: Nope, does not work.</p>\n\n<h2>Attempt 2: Use a temporary file</h2>\n\n<p>There's <code>tmpfile()</code>, so why not use that?!</p>\n\n<pre><code>var_dump( file_exists( tmpfile() ) );\n// boolean FALSE\n</code></pre>\n\n<p>Yeah, that much about this shortcut.</p>\n\n<h2>Attempt 3: Use a custom stream wrapper</h2>\n\n<p>Next I thought I could <a href=\"http://at2.php.net/manual/en/class.streamwrapper.php\" rel=\"nofollow\">build a custom stream wrapper</a> and <a href=\"http://php.net/manual/en/function.stream-wrapper-register.php\" rel=\"nofollow\">register it using <code>stream_wrapper_register()</code></a>. Then I could use a <em>virtual template</em> from that stream to trick core into believing that we have a file. Example code below (I already deleted the full class and history does not have enough steps…)</p>\n\n<pre><code>class TemplateStreamWrapper\n{\n public $context;\n\n public function stream_open( $path, $mode, $options, &$opened )\n {\n // return boolean\n }\n}\n\nstream_wrapper_register( 'vt://comments', 'TemplateStreamWrapper' );\n// … etc. …\n</code></pre>\n\n<p>Again, this returned <code>NULL</code> on <code>file_exists()</code>.</p>\n\n<hr>\n\n<p>Tested with PHP 5.6.20</p>\n"
},
{
"answer_id": 228391,
"author": "kaiser",
"author_id": 385,
"author_profile": "https://wordpress.stackexchange.com/users/385",
"pm_score": 2,
"selected": false,
"text": "<p>As <a href=\"https://wordpress.stackexchange.com/users/87576/alain-schlesser\">@AlainSchlesser</a> suggested to follow the route (and as non working things always bug me), I retried building a stream wrapper for virtual files. I could not solve it (read: reading the return values on the docs) on my own, but solved it with the help of <a href=\"https://stackoverflow.com/q/37553914/376483\">@HPierce on SO</a>.</p>\n\n<pre><code>class VirtualTemplateWrapper\n{\n public $context;\n\n public function stream_open( $path, $mode, $options, &$opened_path ) { return true; }\n\n public function stream_read( $count ) { return ''; }\n\n public function stream_eof() { return ''; }\n\n public function stream_stat() {\n # $user = posix_getpwuid( posix_geteuid() );\n $data = [\n 'dev' => 0,\n 'ino' => getmyinode(),\n 'mode' => 'r',\n 'nlink' => 0,\n 'uid' => getmyuid(),\n 'gid' => getmygid(),\n #'uid' => $user['uid'],\n #'gid' => $user['gid'],\n 'rdev' => 0,\n 'size' => 0,\n 'atime' => time(),\n 'mtime' => getlastmod(),\n 'ctime' => FALSE,\n 'blksize' => 0,\n 'blocks' => 0,\n ];\n return array_merge( array_values( $data ), $data );\n }\n\n public function url_stat( $path, $flags ) {\n return $this->stream_stat();\n }\n}\n</code></pre>\n\n<p>You just need to register the new class as new protocol:</p>\n\n<pre><code>add_action( 'template_redirect', function() {\n stream_wrapper_register( 'virtual', 'VirtualTemplateWrapper' );\n}, 0 );\n</code></pre>\n\n<p>This then allows to create a <em>virtual</em> (non existing) file:</p>\n\n<pre><code>$template = fopen( \"virtual://comments\", 'r+' );\n</code></pre>\n\n<p>Your function can then get refactored to:</p>\n\n<pre><code>function engineCommentsTemplate( $engine )\n{\n $replacement = null;\n $virtual = fopen( \"virtual://comments\", 'r+' );\n\n $tmplGetter = function( $original ) use( &$replacement, $virtual ) {\n $replacement = $original;\n return $virtual;\n };\n\n add_filter( 'comments_template', $tmplGetter, PHP_INT_MAX );\n\n comments_template();\n\n remove_filter( 'comments_template', $tmplGetter, PHP_INT_MAX );\n\n // As the PHP internals are quite unclear: Better safe then sorry\n unset( $virtual );\n\n if ( is_file( $replacement ) && is_readable( $replacement ) ) {\n return $engine->render( $replacement );\n }\n\n return '';\n}\n</code></pre>\n\n<p>as the <code>file_exists()</code> check in core returns <code>TRUE</code> and the <code>require $file</code> throws no error.</p>\n\n<p>I have to note that I am quite happy how this turned out as it might be really helpful with unit tests.</p>\n"
}
] |
2016/05/30
|
[
"https://wordpress.stackexchange.com/questions/228266",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35541/"
] |
I'm developing a WordPress theme using a template engine. I want my code to be as much compatible as possible with WP core functionality.
Some context first
------------------
My first problem was to find a way to *resolve* the template starting from a WP query. I solved that one using a library of mine, [Brain\Hierarchy](https://github.com/Brain-WP/Hierarchy).
Regarding `get_template_part()` and other functions that loads partials like `get_header()`, `get_footer()` and similar, it was pretty easy to write wrapper to template engine partial functionality.
The issue
---------
My problem is now how to load comments template.
WordPress function [`comments_template()`](https://developer.wordpress.org/reference/functions/comments_template/) is a ~200 lines function that does a lot of things, which I want to do as well for maximum core compatibility.
However, as soon as I call `comments_template()`, a file is `require`d, it is the first of:
* the file in the constant `COMMENTS_TEMPLATE`, if defined
* `comments.php` in theme folder, if found
* `/theme-compat/comments.php` in WP includes folder as last resort fallback
In short, there's no way to prevent the function to load a PHP file, which is not desirable for me, because I need to *render* my templates and not simply use `require`.
Current solution
----------------
At the moment, I'm shipping an empty `comments.php` file and I'm using [`'comments_template'`](https://developer.wordpress.org/reference/hooks/comments_template/) filter hook, to know which template WordPress wants to loads, and use feature from my template engine to load the template.
Something like this:
```
function engineCommentsTemplate($myEngine) {
$toLoad = null; // this will hold the template path
$tmplGetter = function($tmpl) use(&$toLoad) {
$toLoad = $tmpl;
return $tmpl;
};
// late priority to allow filters attached here to do their job
add_filter('comments_template', $tmplGetter, PHP_INT_MAX);
// this will load an empty comments.php file I ship in my theme
comments_template();
remove_filter('comments_template', $tmplGetter, PHP_INT_MAX);
if (is_file($toLoad) && is_readable($toLoad)) {
return $myEngine->render($toLoad);
}
return '';
}
```
The question
------------
This works, is core compatible, but... is there a way to make it work without having to ship an empty `comments.php`?
Because I don't like it.
|
Not sure the following solution is *better* than the solution in OP, let's just say is an alternative, probably more hackish, solution.
I think you can use a PHP exception to stop WordPress execution when `'comments_template'` filter is applied.
You can use a custom exception class as a DTO to *carry* the template.
This is a draft for the excepion:
```
class CommentsTemplateException extends \Exception {
protected $template;
public static function forTemplate($template) {
$instance = new static();
$instance->template = $template;
return $instance;
}
public function template() {
return $this->template;
}
}
```
With this exception class available, your function becomes:
```
function engineCommentsTemplate($myEngine) {
$filter = function($template) {
throw CommentsTemplateException::forTemplate($template);
};
try {
add_filter('comments_template', $filter, PHP_INT_MAX);
// this will throw the excption that makes `catch` block run
comments_template();
} catch(CommentsTemplateException $e) {
return $myEngine->render($e->template());
} finally {
remove_filter('comments_template', $filter, PHP_INT_MAX);
}
}
```
The `finally` block requires PHP 5.5+.
Works the same way, and doesn't require an empty template.
|
228,279 |
<p>Playing with WordPress customization I created a meta box with several others that report back details of the post. One meta box evaluates the featured image but I am having trouble figuring out how to fire the AJAX in the content of the meta box. At first I thought I would need to look into <code>admin-ajax.php</code> so I followed <a href="https://premium.wpmudev.org/blog/using-ajax-with-wordpress" rel="nofollow noreferrer">Using AJAX With PHP on Your WordPress Site Without a Plugin</a> but after looking into it I need to check if the post has a thumbnail loaded in the meta box content. I searched under the tag <a href="/questions/tagged/media" class="post-tag" title="show questions tagged 'media'" rel="tag">media</a> and tag <a href="/questions/tagged/javascript" class="post-tag" title="show questions tagged 'javascript'" rel="tag">javascript</a> and what I found was <a href="https://wordpress.stackexchange.com/questions/202988/trigger-js-when-featured-image-upload-window-is-opened-in-admin">Trigger JS when featured image upload window is opened in admin</a> which led me to search for <code>wp.media.featuredImage</code> but how can I build my function with AJAX to run when the featured image is loaded but if it isn't then do not.</p>
<p>I can get it to work by using:</p>
<pre><code>function foobar_metabox_callback( $post ) {
wp_nonce_field( basename( __FILE__ ), 'metabox_meta_nonce' );
$metabox_stored_meta = get_post_meta( $post->ID );
if ( has_post_thumbnail() ) { ?>
<p>
<!-- show results -->
</p>
<?php } else { ?>
<p>No Featured Image not loaded</p>
<?php
}
// test the meta content
$getPostCustom=get_post_custom();
var_dump($getPostCustom);
}
</code></pre>
<p>but that is only if I refresh after the featured image has been loaded to the post. How can I get the function <code>foobar_metabox_callback()</code> to run without refreshing using <code>admin-ajax.php</code> if possible?</p>
<p>Further reference:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/30085701/wordpress-wp-media-featured-image-id">Wordpress wp.media Featured Image ID</a></li>
<li><a href="https://stackoverflow.com/questions/30462407/how-to-detect-changes-in-wp-editor">How to detect changes in wp_editor?</a></li>
</ul>
|
[
{
"answer_id": 228384,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Very broad solution.</p>\n\n<p>There are two problems you are facing</p>\n\n<ol>\n<li><p>there are different HTML generated by the server based on if there is a featured image</p></li>\n<li><p>Meta box are just a UI artifact of post editing and are not easily manipulated via AJAX (even in AJAX it is easier to handle full objects rather then their individual properties, even if only for keeping everything in sync)</p></li>\n</ol>\n\n<p>The solution is by removing point 1 and keeping everything in the client. Add all the HTML as if there is a featured image, just hide it with <code>display:none</code> or similar.</p>\n\n<p>Now all you have to do is to monitor when a feature image is inserted, probably via DOM mutation event or whatever you can do with jQuery (there might even be an event raised by WP JS that associates the image). Once you detect that the image is there you can update whatever values you have in the metabox and remove the <code>display:none</code>.</p>\n\n<p>You are unlikely to get the same exact behavior as when the html is rendered with the featured image already there, depending on the complexity of what you do, but you should be able to get something that is good enough.</p>\n"
},
{
"answer_id": 228403,
"author": "Cai",
"author_id": 81652,
"author_profile": "https://wordpress.stackexchange.com/users/81652",
"pm_score": 2,
"selected": true,
"text": "<p>I couldn't find any WP specific event to hook in to. What you can do is set up an observer with a callback to respond to DOM changes using <code>MutationObserver</code> and check if the your featured image has been added in the callback.</p>\n\n<p>There's <a href=\"http://caniuse.com/#feat=mutationobserver\" rel=\"nofollow noreferrer\">no support</a> in IE < 11 though, which may be a deal breaker for you, or maybe not.</p>\n\n<p>I've done minimal testing on this, but it works for me:</p>\n\n<pre><code>MutationObserver = window.MutationObserver || window.WebKitMutationObserver;\n\nvar observer = new MutationObserver(function(mutations, observer) {\n\n // Fires every time a mutation occurs...\n\n // forEach all mutations\n mutations.forEach(function(mutation) {\n\n // Loop through added nodes\n for (var i = 0; i < mutation.addedNodes.length; ++i) {\n\n // any images added?\n if ( mutation.addedNodes[i].getElementsByTagName('img').length > 0) {\n alert('Featured Image Added');\n\n // Your featured image now exists\n console.log( $('#postimagediv img') );\n\n // Do some AJAX...\n }\n }\n });\n});\n\n// define what element should be observed (#postimagediv is the container for the featured image)\n// and what types of mutations trigger the callback\nvar $element = $('#postimagediv');\nvar config = { subtree: true, childList: true, characterData: true };\n\nobserver.observe( $element[0], config );\n</code></pre>\n\n<p>There's probably a better way to check for the featured image than just checking for an <code>img</code> element. You may want to have a var to keep track of the featured image so you can easily check for it being removed too (or just check <code>removedNodes</code> in the observer callback).</p>\n\n<p>This won't run on page load so you should check if a featured image exists there first.</p>\n\n<p>Further reading on the Mutation Observers:</p>\n\n<ul>\n<li><p><a href=\"https://www.w3.org/TR/dom/#mutation-observers\" rel=\"nofollow noreferrer\">https://www.w3.org/TR/dom/#mutation-observers</a></p></li>\n<li><p><a href=\"https://davidwalsh.name/mutationobserver-api\" rel=\"nofollow noreferrer\">https://davidwalsh.name/mutationobserver-api</a></p></li>\n<li><p><a href=\"http://ryanmorr.com/using-mutation-observers-to-watch-for-element-availability/\" rel=\"nofollow noreferrer\">http://ryanmorr.com/using-mutation-observers-to-watch-for-element-availability/</a></p></li>\n<li><p><a href=\"https://stackoverflow.com/a/11546242/1990216\">https://stackoverflow.com/a/11546242/1990216</a></p></li>\n</ul>\n"
}
] |
2016/05/30
|
[
"https://wordpress.stackexchange.com/questions/228279",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25271/"
] |
Playing with WordPress customization I created a meta box with several others that report back details of the post. One meta box evaluates the featured image but I am having trouble figuring out how to fire the AJAX in the content of the meta box. At first I thought I would need to look into `admin-ajax.php` so I followed [Using AJAX With PHP on Your WordPress Site Without a Plugin](https://premium.wpmudev.org/blog/using-ajax-with-wordpress) but after looking into it I need to check if the post has a thumbnail loaded in the meta box content. I searched under the tag [media](/questions/tagged/media "show questions tagged 'media'") and tag [javascript](/questions/tagged/javascript "show questions tagged 'javascript'") and what I found was [Trigger JS when featured image upload window is opened in admin](https://wordpress.stackexchange.com/questions/202988/trigger-js-when-featured-image-upload-window-is-opened-in-admin) which led me to search for `wp.media.featuredImage` but how can I build my function with AJAX to run when the featured image is loaded but if it isn't then do not.
I can get it to work by using:
```
function foobar_metabox_callback( $post ) {
wp_nonce_field( basename( __FILE__ ), 'metabox_meta_nonce' );
$metabox_stored_meta = get_post_meta( $post->ID );
if ( has_post_thumbnail() ) { ?>
<p>
<!-- show results -->
</p>
<?php } else { ?>
<p>No Featured Image not loaded</p>
<?php
}
// test the meta content
$getPostCustom=get_post_custom();
var_dump($getPostCustom);
}
```
but that is only if I refresh after the featured image has been loaded to the post. How can I get the function `foobar_metabox_callback()` to run without refreshing using `admin-ajax.php` if possible?
Further reference:
* [Wordpress wp.media Featured Image ID](https://stackoverflow.com/questions/30085701/wordpress-wp-media-featured-image-id)
* [How to detect changes in wp\_editor?](https://stackoverflow.com/questions/30462407/how-to-detect-changes-in-wp-editor)
|
I couldn't find any WP specific event to hook in to. What you can do is set up an observer with a callback to respond to DOM changes using `MutationObserver` and check if the your featured image has been added in the callback.
There's [no support](http://caniuse.com/#feat=mutationobserver) in IE < 11 though, which may be a deal breaker for you, or maybe not.
I've done minimal testing on this, but it works for me:
```
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
// Fires every time a mutation occurs...
// forEach all mutations
mutations.forEach(function(mutation) {
// Loop through added nodes
for (var i = 0; i < mutation.addedNodes.length; ++i) {
// any images added?
if ( mutation.addedNodes[i].getElementsByTagName('img').length > 0) {
alert('Featured Image Added');
// Your featured image now exists
console.log( $('#postimagediv img') );
// Do some AJAX...
}
}
});
});
// define what element should be observed (#postimagediv is the container for the featured image)
// and what types of mutations trigger the callback
var $element = $('#postimagediv');
var config = { subtree: true, childList: true, characterData: true };
observer.observe( $element[0], config );
```
There's probably a better way to check for the featured image than just checking for an `img` element. You may want to have a var to keep track of the featured image so you can easily check for it being removed too (or just check `removedNodes` in the observer callback).
This won't run on page load so you should check if a featured image exists there first.
Further reading on the Mutation Observers:
* <https://www.w3.org/TR/dom/#mutation-observers>
* <https://davidwalsh.name/mutationobserver-api>
* <http://ryanmorr.com/using-mutation-observers-to-watch-for-element-availability/>
* <https://stackoverflow.com/a/11546242/1990216>
|
228,284 |
<p>So...here is part of my code for a plugin. I'm a newb of sorts so be kind. I've read up on global variables but I can't seem to get it to work and I've read you shouldn't use them anyway. So what would be the best way to write the code below without having to re-declare the variables for each function? Here is the <a href="http://pastebin.com/8c5BAZPc" rel="nofollow">full code</a> if necessary.</p>
<pre><code>// Display the product badge on the shop page
add_action( 'woocommerce_after_shop_loop_item_title', 'wc_simple_product_badge_display_shop', 30 );
function wc_simple_product_badge_display_shop() {
$title = get_post_meta( get_the_ID(), '_wc_simple_product_badge_title', true ); // badge title
$class = get_post_meta( get_the_ID(), '_wc_simple_product_badge_class', true ); // badge class
$duration = get_post_meta( get_the_ID(), '_wc_simple_product_badge_duration', true ); // badge duration
$postdate = get_the_time( 'Y-m-d' ); // post date
$postdatestamp = strtotime( $postdate ); // post date in unix timestamp
$difference = round ((time() - $postdatestamp) / (24*60*60)); // difference in days between now and product's post date
if ( !empty( $title ) && empty( $duration ) || !empty( $title ) && $difference <= $duration ){ // Check to see if there is a title and the product is still within the duration timeframe if specified
$class = !empty( $class ) ? $class : '';
echo '<span class="wc_simple_product_badge ' . $class . '">' . $title . '</span>';
}
}
// Display the product badge on the single page
add_filter( 'woocommerce_single_product_image_html', 'wc_simple_product_badge_display_single' );
function wc_simple_product_badge_display_single( $img_html ) {
$title = get_post_meta( get_the_ID(), '_wc_simple_product_badge_title', true ); // badge title
$class = get_post_meta( get_the_ID(), '_wc_simple_product_badge_class', true ); // badge class
$duration = get_post_meta( get_the_ID(), '_wc_simple_product_badge_duration', true ); // badge duration
$single_opt = get_post_meta( get_the_ID(), '_wc_simple_product_badge_single_page_option', true ); // badge on single page
$postdate = get_the_time( 'Y-m-d' ); // post date
$postdatestamp = strtotime( $postdate ); // post date in unix timestamp
$difference = round ((time() - $postdatestamp) / (24*60*60)); // difference in days between now and product's post date
if ( !empty( $title ) && empty( $duration ) && $single_opt === 'yes' || !empty( $title ) && $difference <= $duration && $single_opt === 'yes' ){ // Check to see if there is a title and the product is still within the duration timeframe ()if specified) and the checkbox is checked to show on single page view
$class = !empty( $class ) ? $class : '';
echo '<span class="wc_simple_product_badge ' . $class . '">' . $title . '</span>';
return $img_html;
}
elseif ( $single_opt === 'no' ) { // Check to see if the checkbox is unchecked to show on single page view
return $img_html;
}
}
</code></pre>
|
[
{
"answer_id": 228384,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Very broad solution.</p>\n\n<p>There are two problems you are facing</p>\n\n<ol>\n<li><p>there are different HTML generated by the server based on if there is a featured image</p></li>\n<li><p>Meta box are just a UI artifact of post editing and are not easily manipulated via AJAX (even in AJAX it is easier to handle full objects rather then their individual properties, even if only for keeping everything in sync)</p></li>\n</ol>\n\n<p>The solution is by removing point 1 and keeping everything in the client. Add all the HTML as if there is a featured image, just hide it with <code>display:none</code> or similar.</p>\n\n<p>Now all you have to do is to monitor when a feature image is inserted, probably via DOM mutation event or whatever you can do with jQuery (there might even be an event raised by WP JS that associates the image). Once you detect that the image is there you can update whatever values you have in the metabox and remove the <code>display:none</code>.</p>\n\n<p>You are unlikely to get the same exact behavior as when the html is rendered with the featured image already there, depending on the complexity of what you do, but you should be able to get something that is good enough.</p>\n"
},
{
"answer_id": 228403,
"author": "Cai",
"author_id": 81652,
"author_profile": "https://wordpress.stackexchange.com/users/81652",
"pm_score": 2,
"selected": true,
"text": "<p>I couldn't find any WP specific event to hook in to. What you can do is set up an observer with a callback to respond to DOM changes using <code>MutationObserver</code> and check if the your featured image has been added in the callback.</p>\n\n<p>There's <a href=\"http://caniuse.com/#feat=mutationobserver\" rel=\"nofollow noreferrer\">no support</a> in IE < 11 though, which may be a deal breaker for you, or maybe not.</p>\n\n<p>I've done minimal testing on this, but it works for me:</p>\n\n<pre><code>MutationObserver = window.MutationObserver || window.WebKitMutationObserver;\n\nvar observer = new MutationObserver(function(mutations, observer) {\n\n // Fires every time a mutation occurs...\n\n // forEach all mutations\n mutations.forEach(function(mutation) {\n\n // Loop through added nodes\n for (var i = 0; i < mutation.addedNodes.length; ++i) {\n\n // any images added?\n if ( mutation.addedNodes[i].getElementsByTagName('img').length > 0) {\n alert('Featured Image Added');\n\n // Your featured image now exists\n console.log( $('#postimagediv img') );\n\n // Do some AJAX...\n }\n }\n });\n});\n\n// define what element should be observed (#postimagediv is the container for the featured image)\n// and what types of mutations trigger the callback\nvar $element = $('#postimagediv');\nvar config = { subtree: true, childList: true, characterData: true };\n\nobserver.observe( $element[0], config );\n</code></pre>\n\n<p>There's probably a better way to check for the featured image than just checking for an <code>img</code> element. You may want to have a var to keep track of the featured image so you can easily check for it being removed too (or just check <code>removedNodes</code> in the observer callback).</p>\n\n<p>This won't run on page load so you should check if a featured image exists there first.</p>\n\n<p>Further reading on the Mutation Observers:</p>\n\n<ul>\n<li><p><a href=\"https://www.w3.org/TR/dom/#mutation-observers\" rel=\"nofollow noreferrer\">https://www.w3.org/TR/dom/#mutation-observers</a></p></li>\n<li><p><a href=\"https://davidwalsh.name/mutationobserver-api\" rel=\"nofollow noreferrer\">https://davidwalsh.name/mutationobserver-api</a></p></li>\n<li><p><a href=\"http://ryanmorr.com/using-mutation-observers-to-watch-for-element-availability/\" rel=\"nofollow noreferrer\">http://ryanmorr.com/using-mutation-observers-to-watch-for-element-availability/</a></p></li>\n<li><p><a href=\"https://stackoverflow.com/a/11546242/1990216\">https://stackoverflow.com/a/11546242/1990216</a></p></li>\n</ul>\n"
}
] |
2016/05/30
|
[
"https://wordpress.stackexchange.com/questions/228284",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84806/"
] |
So...here is part of my code for a plugin. I'm a newb of sorts so be kind. I've read up on global variables but I can't seem to get it to work and I've read you shouldn't use them anyway. So what would be the best way to write the code below without having to re-declare the variables for each function? Here is the [full code](http://pastebin.com/8c5BAZPc) if necessary.
```
// Display the product badge on the shop page
add_action( 'woocommerce_after_shop_loop_item_title', 'wc_simple_product_badge_display_shop', 30 );
function wc_simple_product_badge_display_shop() {
$title = get_post_meta( get_the_ID(), '_wc_simple_product_badge_title', true ); // badge title
$class = get_post_meta( get_the_ID(), '_wc_simple_product_badge_class', true ); // badge class
$duration = get_post_meta( get_the_ID(), '_wc_simple_product_badge_duration', true ); // badge duration
$postdate = get_the_time( 'Y-m-d' ); // post date
$postdatestamp = strtotime( $postdate ); // post date in unix timestamp
$difference = round ((time() - $postdatestamp) / (24*60*60)); // difference in days between now and product's post date
if ( !empty( $title ) && empty( $duration ) || !empty( $title ) && $difference <= $duration ){ // Check to see if there is a title and the product is still within the duration timeframe if specified
$class = !empty( $class ) ? $class : '';
echo '<span class="wc_simple_product_badge ' . $class . '">' . $title . '</span>';
}
}
// Display the product badge on the single page
add_filter( 'woocommerce_single_product_image_html', 'wc_simple_product_badge_display_single' );
function wc_simple_product_badge_display_single( $img_html ) {
$title = get_post_meta( get_the_ID(), '_wc_simple_product_badge_title', true ); // badge title
$class = get_post_meta( get_the_ID(), '_wc_simple_product_badge_class', true ); // badge class
$duration = get_post_meta( get_the_ID(), '_wc_simple_product_badge_duration', true ); // badge duration
$single_opt = get_post_meta( get_the_ID(), '_wc_simple_product_badge_single_page_option', true ); // badge on single page
$postdate = get_the_time( 'Y-m-d' ); // post date
$postdatestamp = strtotime( $postdate ); // post date in unix timestamp
$difference = round ((time() - $postdatestamp) / (24*60*60)); // difference in days between now and product's post date
if ( !empty( $title ) && empty( $duration ) && $single_opt === 'yes' || !empty( $title ) && $difference <= $duration && $single_opt === 'yes' ){ // Check to see if there is a title and the product is still within the duration timeframe ()if specified) and the checkbox is checked to show on single page view
$class = !empty( $class ) ? $class : '';
echo '<span class="wc_simple_product_badge ' . $class . '">' . $title . '</span>';
return $img_html;
}
elseif ( $single_opt === 'no' ) { // Check to see if the checkbox is unchecked to show on single page view
return $img_html;
}
}
```
|
I couldn't find any WP specific event to hook in to. What you can do is set up an observer with a callback to respond to DOM changes using `MutationObserver` and check if the your featured image has been added in the callback.
There's [no support](http://caniuse.com/#feat=mutationobserver) in IE < 11 though, which may be a deal breaker for you, or maybe not.
I've done minimal testing on this, but it works for me:
```
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
// Fires every time a mutation occurs...
// forEach all mutations
mutations.forEach(function(mutation) {
// Loop through added nodes
for (var i = 0; i < mutation.addedNodes.length; ++i) {
// any images added?
if ( mutation.addedNodes[i].getElementsByTagName('img').length > 0) {
alert('Featured Image Added');
// Your featured image now exists
console.log( $('#postimagediv img') );
// Do some AJAX...
}
}
});
});
// define what element should be observed (#postimagediv is the container for the featured image)
// and what types of mutations trigger the callback
var $element = $('#postimagediv');
var config = { subtree: true, childList: true, characterData: true };
observer.observe( $element[0], config );
```
There's probably a better way to check for the featured image than just checking for an `img` element. You may want to have a var to keep track of the featured image so you can easily check for it being removed too (or just check `removedNodes` in the observer callback).
This won't run on page load so you should check if a featured image exists there first.
Further reading on the Mutation Observers:
* <https://www.w3.org/TR/dom/#mutation-observers>
* <https://davidwalsh.name/mutationobserver-api>
* <http://ryanmorr.com/using-mutation-observers-to-watch-for-element-availability/>
* <https://stackoverflow.com/a/11546242/1990216>
|
228,287 |
<p>I am working on a site for a client who has a theme built for them by a different developer. They have asked me to make some changes to the site, and I'd like to put all of my changes into a plugin as a courtesy to the original theme developer. So far this is simple with functions and CSS. Now I need to change a theme file. Essentially I'd like to replace one theme file with a different one that I've edited heavily. </p>
<p>In the theme, the file I'd like to replace is called with this:</p>
<pre><code>get_template_part( 'partials/post', 'sidebar' );
</code></pre>
<p>What I'd like to do is to somehow write a function in my plugin that catches the above statement and redirects that template request to a file that resides in my plugin directory. </p>
<p>I have absolutely no idea how to do this, and searching has so far turned up very little help. Is this possible?</p>
|
[
{
"answer_id": 228288,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 3,
"selected": true,
"text": "<p><strong>TL;DR:</strong> Use a <strong><a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow\">child theme</a></strong> instead :)</p>\n\n<hr>\n\n<p>If we dig into the <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow\">code for get_template_part()</a>, there's an action there - <code>get_template_part_{$slug}</code> - which we could hook into.</p>\n\n<p>Digging a bit further, get_template_part() calls <a href=\"https://developer.wordpress.org/reference/functions/locate_template/\" rel=\"nofollow\">locate_template()</a>, which calls <a href=\"https://developer.wordpress.org/reference/functions/load_template/\" rel=\"nofollow\">load_template()</a>. Unfortunately, there's nothing in either of these functions that seems to be pluggable, so we can't hook in and change anything (with the exception of being able to set variables through the call to extract() in load_template().... but we can't override the template file being called so it's not very useful anyway!)</p>\n\n<p>So, it looks like your only option to catch this is by running code on the <code>get_template_part_partials/post</code> action. The problem is, this won't allow you to filter the template called - it'll just allow you to run some code <em>when</em> the template is called. If all you want to do is add some output <em>above</em> the templated code then this will suit you perfectly, but I doubt that's all you want to do!</p>\n\n<p>The way around all this is to <strong>use a child theme</strong>.</p>\n\n<p>You said you wanted to put your code into a plugin in order to respect the original theme developer. Firstly, that respect is awesome - many developers wouldn't care less so I commend you for that!</p>\n\n<p>However, is a plugin the best choice? Plugins are generally used to add modular functionality to a site, not to change the look and feel of it. That's the domain of themes.</p>\n\n<p>You can in fact <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow\">create a child theme</a> which will let you modify the theme the site uses <em>without</em> making any changes to the parent theme. You should be able to apply all the changes you've already made here, plus you have the bonus that <em>get_template_part() will automatically use a file within your child theme if it exists</em>, before falling back to the parent theme.</p>\n"
},
{
"answer_id": 228325,
"author": "yousaf",
"author_id": 94778,
"author_profile": "https://wordpress.stackexchange.com/users/94778",
"pm_score": -1,
"selected": false,
"text": "<p>first of all you find directory of your partial-sidebar.php directory. when you find then Get_template_directory_uri(). then \"../ \" this means one folder back if your partial-sidebar.php is backed folder of plugin then use as \"../Get_template_directory_uri()/wp-content/\" as well as so on</p>\n"
}
] |
2016/05/31
|
[
"https://wordpress.stackexchange.com/questions/228287",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73822/"
] |
I am working on a site for a client who has a theme built for them by a different developer. They have asked me to make some changes to the site, and I'd like to put all of my changes into a plugin as a courtesy to the original theme developer. So far this is simple with functions and CSS. Now I need to change a theme file. Essentially I'd like to replace one theme file with a different one that I've edited heavily.
In the theme, the file I'd like to replace is called with this:
```
get_template_part( 'partials/post', 'sidebar' );
```
What I'd like to do is to somehow write a function in my plugin that catches the above statement and redirects that template request to a file that resides in my plugin directory.
I have absolutely no idea how to do this, and searching has so far turned up very little help. Is this possible?
|
**TL;DR:** Use a **[child theme](https://codex.wordpress.org/Child_Themes)** instead :)
---
If we dig into the [code for get\_template\_part()](https://developer.wordpress.org/reference/functions/get_template_part/), there's an action there - `get_template_part_{$slug}` - which we could hook into.
Digging a bit further, get\_template\_part() calls [locate\_template()](https://developer.wordpress.org/reference/functions/locate_template/), which calls [load\_template()](https://developer.wordpress.org/reference/functions/load_template/). Unfortunately, there's nothing in either of these functions that seems to be pluggable, so we can't hook in and change anything (with the exception of being able to set variables through the call to extract() in load\_template().... but we can't override the template file being called so it's not very useful anyway!)
So, it looks like your only option to catch this is by running code on the `get_template_part_partials/post` action. The problem is, this won't allow you to filter the template called - it'll just allow you to run some code *when* the template is called. If all you want to do is add some output *above* the templated code then this will suit you perfectly, but I doubt that's all you want to do!
The way around all this is to **use a child theme**.
You said you wanted to put your code into a plugin in order to respect the original theme developer. Firstly, that respect is awesome - many developers wouldn't care less so I commend you for that!
However, is a plugin the best choice? Plugins are generally used to add modular functionality to a site, not to change the look and feel of it. That's the domain of themes.
You can in fact [create a child theme](https://codex.wordpress.org/Child_Themes) which will let you modify the theme the site uses *without* making any changes to the parent theme. You should be able to apply all the changes you've already made here, plus you have the bonus that *get\_template\_part() will automatically use a file within your child theme if it exists*, before falling back to the parent theme.
|
228,300 |
<p>I am searching online and all I can see is how to <em>increase</em> file size for media upload, which I know how to do with <code>php.ini</code>, but what I need to do is limit the file size for media upload only.</p>
<p>The client and his associates have trouble with understanding: Please do not upload images that are bigger than 1MB because your site will load forever.</p>
<p>They keep uploading images that are over 8 MB in size, and the whole site takes over 30 sec to load. It's horrendous.</p>
<p>So I was thinking - if it's possible to limit the image upload to 1 MB or so without affecting the general <code>upload_max_filesize</code> which will influence the ability to upload themes and plugins (and I don't want that to happen).</p>
<p>Any idea if this can be done?</p>
|
[
{
"answer_id": 228306,
"author": "Capiedge",
"author_id": 39150,
"author_profile": "https://wordpress.stackexchange.com/users/39150",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, you can use the <code>wp_handle_upload_prefilter</code> that allows you to stop the uploading process if a specific condition is not accomplished.</p>\n\n<p>In your case, you could try this code snippet:</p>\n\n<pre><code>function limit_upload_size( $file ) {\n\n // Set the desired file size limit\n $file_size_limit = 1024; // 1MB in KB\n\n // exclude admins\n if ( ! current_user_can( 'manage_options' ) ) {\n\n $current_size = $file['size'];\n $current_size = $current_size / 1024; //get size in KB\n\n if ( $current_size > $file_size_limit ) {\n $file['error'] = sprintf( __( 'ERROR: File size limit is %d KB.' ), $file_size_limit );\n }\n\n }\n\n return $file;\n\n}\nadd_filter ( 'wp_handle_upload_prefilter', 'limit_upload_size', 10, 1 );\n</code></pre>\n\n<p>Hope it helps!</p>\n"
},
{
"answer_id": 228307,
"author": "Christine Cooper",
"author_id": 24875,
"author_profile": "https://wordpress.stackexchange.com/users/24875",
"pm_score": 2,
"selected": false,
"text": "<p>You can hook into <code>upload_size_limit</code> and set a maximum filesize:</p>\n\n<pre><code>// Change the upload size to 1MB\nadd_filter( 'upload_size_limit', 'wpse_228300_change_upload_size' ); \nfunction wpse_228300_change_upload_size()\n{\n return 1000 * 1024;\n}\n</code></pre>\n"
},
{
"answer_id": 228319,
"author": "yousaf",
"author_id": 94778,
"author_profile": "https://wordpress.stackexchange.com/users/94778",
"pm_score": -1,
"selected": false,
"text": "<p><strong>1: Theme Functions File</strong></p>\n\n<p>There are cases where we have seen that just by adding the following code in the theme function’s file, you can increase the upload size:</p>\n\n<pre><code>@ini_set( 'upload_max_size' , '64M' );\n@ini_set( 'post_max_size', '64M');\n@ini_set( 'max_execution_time', '300' );\n</code></pre>\n\n<p><strong>2. Create or Edit an existing PHP.INI file</strong></p>\n\n<p>In most cases if you are on a shared host, you will not see a php.ini file in your directory. If you do not see one, then create a file called php.ini and upload it in the root folder. In that file add the following code:</p>\n\n<pre><code>upload_max_filesize = 64M\npost_max_size = 64M\nmax_execution_time = 300\n</code></pre>\n\n<p><strong>3. htaccess Method</strong></p>\n\n<p>Some people have tried using the htaccess method where by modifying the <code>.htaccess</code> file in the root directory, you can increase the maximum upload size in WordPress. Open or create the <code>.htaccess</code> file in the root folder and add the following code:</p>\n\n<pre><code>php_value upload_max_filesize 64M\nphp_value post_max_size 64M\nphp_value max_execution_time 300\nphp_value max_input_time 300\n</code></pre>\n"
},
{
"answer_id": 307236,
"author": "Krystian Juraszek",
"author_id": 113214,
"author_profile": "https://wordpress.stackexchange.com/users/113214",
"pm_score": 1,
"selected": false,
"text": "<p>For me this is works great !</p>\n\n<pre><code> function my_max_image_size( $file ) {\n $size = $file['size'];\n $size = $size / 1024;\n $type = $file['type'];\n $is_image = strpos( $type, 'image' ) !== false;\n $limit = 750;\n $limit_output = '750kb';\n if ( $is_image && $size > $limit ) {\n $file['error'] = 'Image files must be smaller than ' . $limit_output;\n }\n return $file;\n}\nadd_filter( 'wp_handle_upload_prefilter', 'my_max_image_size' );\n</code></pre>\n"
}
] |
2016/05/31
|
[
"https://wordpress.stackexchange.com/questions/228300",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58895/"
] |
I am searching online and all I can see is how to *increase* file size for media upload, which I know how to do with `php.ini`, but what I need to do is limit the file size for media upload only.
The client and his associates have trouble with understanding: Please do not upload images that are bigger than 1MB because your site will load forever.
They keep uploading images that are over 8 MB in size, and the whole site takes over 30 sec to load. It's horrendous.
So I was thinking - if it's possible to limit the image upload to 1 MB or so without affecting the general `upload_max_filesize` which will influence the ability to upload themes and plugins (and I don't want that to happen).
Any idea if this can be done?
|
Yes, you can use the `wp_handle_upload_prefilter` that allows you to stop the uploading process if a specific condition is not accomplished.
In your case, you could try this code snippet:
```
function limit_upload_size( $file ) {
// Set the desired file size limit
$file_size_limit = 1024; // 1MB in KB
// exclude admins
if ( ! current_user_can( 'manage_options' ) ) {
$current_size = $file['size'];
$current_size = $current_size / 1024; //get size in KB
if ( $current_size > $file_size_limit ) {
$file['error'] = sprintf( __( 'ERROR: File size limit is %d KB.' ), $file_size_limit );
}
}
return $file;
}
add_filter ( 'wp_handle_upload_prefilter', 'limit_upload_size', 10, 1 );
```
Hope it helps!
|
228,301 |
<p>I am working on a plugin .I want to upload image from front end i.e by <code>input type="file"</code>.I did lot of google for it but could not upload image .Here is my code for uploading image</p>
<pre><code><form method="post" action="options.php">
<input type="file" name="my_image_upload" id="my_image_upload" multiple="false" />
<input type="hidden" name="post_id" id="post_id" value="55" />
<?php wp_nonce_field( 'my_image_upload', 'my_image_upload_nonce' ); ?>
<input id="submit_my_image_upload" name="submit_my_image_upload" type="submit" value="Upload" />
</form>
<?php
if (
isset( $_POST['my_image_upload_nonce'], $_POST['post_id'] )
&& wp_verify_nonce( $_POST['my_image_upload_nonce'], 'my_image_upload' )
&& current_user_can( 'edit_post', $_POST['post_id'] )
) {
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );
if ( is_wp_error( $attachment_id ) ) {
// There was an error uploading the image.
} else {
// The image was uploaded successfully!
}
} else {
// The security check failed, maybe show the user an error.
}
function wp_verify_nonce_X($nonce, $action = -1) {
return true;
$user = wp_get_current_user();
$uid = (int) $user->id;
$i = wp_nonce_tick();
if ( substr(wp_hash($i . $action . $uid, 'nonce'), -12, 10) == $nonce )
return 1;
if ( substr(wp_hash(($i - 1) . $action . $uid, 'nonce'), -12, 10) == $nonce )
return 2;
// Invalid nonce
return false;
}
After implementing this code I get thiserror
Fatal error: Call to undefined function wp_verify_nonce() in /home/projectdemos/public_html/WP-Team-Showcase/wp-content/plugins/wp-team-showcase/team.php on line 435
</code></pre>
<p>I google this error and run all possible solution found across it but could not solved it .
Tell me how to upload image and save it ,if there is any other solution beside my this code.</p>
|
[
{
"answer_id": 228330,
"author": "Jebble",
"author_id": 81939,
"author_profile": "https://wordpress.stackexchange.com/users/81939",
"pm_score": 0,
"selected": false,
"text": "<p>You call for a WordPress function before WordPress is fully loaded.\nA quick and dirty way to fix this is to add</p>\n\n<pre><code>require_once(ABSPATH .'wp-includes/pluggable.php');\n</code></pre>\n\n<p>at the top of your plugin file so it has the needed functions.</p>\n\n<p>A better and the correct way of solving this is to wait with your code until WordPress is done by using one of the available hooks</p>\n\n<pre><code>add_action( 'init', 'wpse_228301' );\n</code></pre>\n\n<p>or </p>\n\n<pre><code>add_action( 'wp_loaded', 'wpse_228301' );\n</code></pre>\n"
},
{
"answer_id": 228892,
"author": "raxa",
"author_id": 84928,
"author_profile": "https://wordpress.stackexchange.com/users/84928",
"pm_score": 3,
"selected": true,
"text": "<p>Now I have an answer for my own question.I solved this issue by using this code.I add this code just for sharing and helping other as it works for me.</p>\n\n<pre><code><input type=\"file\" name=\"my_file_upload\" id=\"my_file_upload_id\" class=\"bg_checkbox\" >\n\nfunction register_team_show_case_setting() {\n//register our settings\n register_setting('my_team_show_case_setting', 'my_file_upload');\n}\nadd_action('admin_init', 'register_team_show_case_setting');\n</code></pre>\n\n<p>Code to upload and save image:</p>\n\n<pre><code>require_once( ABSPATH . 'wp-admin/includes/image.php' );\nrequire_once( ABSPATH . 'wp-admin/includes/file.php' );\nrequire_once( ABSPATH . 'wp-admin/includes/media.php' );\n$attach_id = media_handle_upload('my_file_upload', $post_id);\nif (is_numeric($attach_id)) {\n update_option('option_image', $attach_id);\n update_post_meta($post_id, '_my_file_upload', $attach_id);\n}\n</code></pre>\n\n<p>Display image code</p>\n\n<pre><code>echo wp_get_attachment_url(get_option('option_image'));\n</code></pre>\n"
}
] |
2016/05/31
|
[
"https://wordpress.stackexchange.com/questions/228301",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84928/"
] |
I am working on a plugin .I want to upload image from front end i.e by `input type="file"`.I did lot of google for it but could not upload image .Here is my code for uploading image
```
<form method="post" action="options.php">
<input type="file" name="my_image_upload" id="my_image_upload" multiple="false" />
<input type="hidden" name="post_id" id="post_id" value="55" />
<?php wp_nonce_field( 'my_image_upload', 'my_image_upload_nonce' ); ?>
<input id="submit_my_image_upload" name="submit_my_image_upload" type="submit" value="Upload" />
</form>
<?php
if (
isset( $_POST['my_image_upload_nonce'], $_POST['post_id'] )
&& wp_verify_nonce( $_POST['my_image_upload_nonce'], 'my_image_upload' )
&& current_user_can( 'edit_post', $_POST['post_id'] )
) {
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );
if ( is_wp_error( $attachment_id ) ) {
// There was an error uploading the image.
} else {
// The image was uploaded successfully!
}
} else {
// The security check failed, maybe show the user an error.
}
function wp_verify_nonce_X($nonce, $action = -1) {
return true;
$user = wp_get_current_user();
$uid = (int) $user->id;
$i = wp_nonce_tick();
if ( substr(wp_hash($i . $action . $uid, 'nonce'), -12, 10) == $nonce )
return 1;
if ( substr(wp_hash(($i - 1) . $action . $uid, 'nonce'), -12, 10) == $nonce )
return 2;
// Invalid nonce
return false;
}
After implementing this code I get thiserror
Fatal error: Call to undefined function wp_verify_nonce() in /home/projectdemos/public_html/WP-Team-Showcase/wp-content/plugins/wp-team-showcase/team.php on line 435
```
I google this error and run all possible solution found across it but could not solved it .
Tell me how to upload image and save it ,if there is any other solution beside my this code.
|
Now I have an answer for my own question.I solved this issue by using this code.I add this code just for sharing and helping other as it works for me.
```
<input type="file" name="my_file_upload" id="my_file_upload_id" class="bg_checkbox" >
function register_team_show_case_setting() {
//register our settings
register_setting('my_team_show_case_setting', 'my_file_upload');
}
add_action('admin_init', 'register_team_show_case_setting');
```
Code to upload and save image:
```
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$attach_id = media_handle_upload('my_file_upload', $post_id);
if (is_numeric($attach_id)) {
update_option('option_image', $attach_id);
update_post_meta($post_id, '_my_file_upload', $attach_id);
}
```
Display image code
```
echo wp_get_attachment_url(get_option('option_image'));
```
|
228,322 |
<p>I am facing a problem to set default value for the checkbox field in WordPress.
I have a checkbox input field (metabox) in a custom post. I want the checkbox to be checked by default. and if user uncheck it then it should be saved and unchecked and remain unchecked when page is refreshed. My problem is that I can not set the default value for the checkbox. I have only two values to work with. Main problem arises, because the savemetadata function runs when I click 'add new' post, So, a default value gets saved in the database automatically without saving the new post. I have been trying for 3 days now. I have tried to save a default value 'yes' when user does not check the checkbox. </p>
<p>but in that case, when user does uncheck then still it become checked with the default value.
my current code snippet </p>
<pre><code>// for displaying metabox
function aps_add_meta_box() {
add_meta_box(
'aps_metabox',
__( 'Slider Settings & Shortcode Generator', APS_TEXTDOMAIN ),
'aps_metabox_cb', // callback
'apspostslider', // screen or posttype
'normal'
);}
add_action( 'add_meta_boxes', 'aps_add_meta_box' );
function aps_metabox_cb( $post ) {
wp_nonce_field( 'aps_meta_save', 'aps_meta_save_nounce' ); // nounce
$aps_display_post_title = get_post_meta( $post->ID, 'aps_display_post_title', true );
<input type="checkbox" name="aps_display_post_title" value="yes" <?php checked( $aps_display_post_title, 'yes'); />
}
</code></pre>
<p>The code for saving metabox data in the save fucntion:</p>
<pre><code>function aps_meta_save( $post_id ) {
// Perform checking for before saving
$is_autosave = wp_is_post_autosave($post_id);
$is_revision = wp_is_post_revision($post_id);
$is_valid_nonce = (isset($_POST['aps_meta_save_nounce']) && wp_verify_nonce( $_POST['aps_meta_save_nounce'], 'aps_meta_save' )? 'true': 'false');
if ( $is_autosave || $is_revision || !$is_valid_nonce ) return;
// Is the user allowed to edit the post or page?
if ( !current_user_can( 'edit_post', $post_id )) return;
$aps_display_post_title = (isset($_POST['aps_display_post_title']))? sanitize_text_field( $_POST["aps_display_post_title"] ): '' ;
update_post_meta($post_id, "aps_display_post_title", $aps_display_post_title);
}
// save only when aps post slider posttype is saved
add_action( 'save_post_apspostslider', 'aps_meta_save');
</code></pre>
<p>I have tried the following code while saving but in that case the checkbox is checked by default. but when I uncheck and save the post, then checkbox remained checked.</p>
<pre><code> $aps_display_post_title = (isset($_POST['aps_display_post_title']))? sanitize_text_field( $_POST["aps_display_post_title"] ): 'yes' ;
update_post_meta($post_id, "aps_display_post_title", $aps_display_post_title);
</code></pre>
<p><strong>UPDATE:</strong>
Now everything is working after changing the hook. the save_post hook runs when a post is newly created or updated. SO, the function to save the meta data would run when a post is created and thus a default value would be saved in the database. However, now after changing the hook to -"edit_post", now everything works. Thanks to the brother <a href="https://wordpress.stackexchange.com/users/76440/majick">majick</a> who helped me. All working code is given below: </p>
<pre><code>//Show meta box
function aps_add_meta_box() {
add_meta_box(
'aps_metabox',
__( 'Slider Settings & Shortcode Generator', APS_TEXTDOMAIN ),
'aps_metabox_cb',
'apspostslider',
'normal'
);
}
add_action( 'add_meta_boxes', 'aps_add_meta_box' );
/**
* Prints the box content.
*/
function aps_metabox_cb( $post ) {
// Add a nonce field so we can check for it later.
wp_nonce_field( 'aps_meta_save', 'aps_meta_save_nounce' );
$aps_display_post_title = get_post_meta( $post->ID, 'aps_display_post_title', true );
<input type="checkbox" name="aps_display_post_title" value="yes" <?php if ($aps_display_post_title != 'no') { echo 'checked'; }?>/>
}
// Save or Update metabox data
function aps_meta_save( $post_id, $post ) {
if ($post->post_type != 'apspostslider') {return;}
// Perform checking for before saving
$is_autosave = wp_is_post_autosave($post_id);
$is_revision = wp_is_post_revision($post_id);
$is_valid_nonce = (isset($_POST['aps_meta_save_nounce']) && wp_verify_nonce( $_POST['aps_meta_save_nounce'], 'aps_meta_save' )? 'true': 'false');
if ( $is_autosave || $is_revision || !$is_valid_nonce ) return;
// Is the user allowed to edit the post or page?
if ( !current_user_can( 'edit_post', $post_id )) return;
if ( (isset($_POST['aps_display_post_title']))
&& ($_POST['aps_display_post_title'] == 'yes') ) {
$aps_display_post_title = 'yes';
} else {$aps_display_post_title = 'no';}
update_post_meta($post_id, "aps_display_post_title", $aps_display_post_title);
add_action( 'edit_post', 'aps_meta_save', 10, 2);
</code></pre>
|
[
{
"answer_id": 228332,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 0,
"selected": false,
"text": "<p>Your code will make the value <code>yes</code> only when the user fills the form. You could check if the meta is not there then make it checked, or try this:</p>\n\n<pre><code>$aps_display_post_title = get_post_meta( $post->ID, 'aps_display_post_title', true );\n$aps_display_post_title = ! ( 'off' == (string) $aps_display_post_title );\n\n?>\n <input type=\"checkbox\" name=\"aps_display_post_title\" <?php checked( $aps_display_post_title ); ?> />\n<?php\n\n\n// updating the meta\n$aps_display_post_title = ! empty($_POST['aps_display_post_title'])? 'on' : 'off'; // call this only when the checkbox is in the screen\nupdate_post_meta( $post_id, \"aps_display_post_title\", $aps_display_post_title );\n</code></pre>\n\n<p>Guess it should be working. BUT don't call the updating script if the checkbox is not in the form in the screen, that will uncheck the boxes even if checked..</p>\n"
},
{
"answer_id": 228345,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 3,
"selected": true,
"text": "<p>I think the problem might could be the logic with using <code>checked</code>... </p>\n\n<pre><code> <input type=\"checkbox\" name=\"aps_display_post_title\" value=\"yes\" <?php if ($aps_display_post_title != 'no') {echo 'checked';} ?> />\n</code></pre>\n\n<p>...on the other hand then running <code>sanitize_text_field</code> on the checkbox value might also be causing the problem. </p>\n\n<p>Instead you might want to break the logic down differently so it is easier to understand, and use this with the code above which checked that the value is not <code>no</code> and so will default as checked:</p>\n\n<pre><code>if ( (isset($_POST['aps_display_post_title'])) \n && ($_POST['aps_display_post_title'] == 'yes') ) {\n $aps_display_post_title = 'yes';}\n} else {$aps_display_post_title = 'no';}\n\nupdate_post_meta($post_id, \"aps_display_post_title\", $aps_display_post_title);\n</code></pre>\n\n<p><strong>UPDATE</strong> </p>\n\n<p>To prevent the metasave function from firing on post creation, hook to <code>edit_post</code> instead of <code>save_post</code> (and do the post type check internally using the second argument passed which is <code>$post</code>)... </p>\n\n<pre><code>add_action( 'edit_post', 'aps_meta_save', 10, 2);\n\nfunction aps_meta_save($post_id, $post) {\n\n if ($post->post_type != 'apspostslider') {return;}\n\n ...\n</code></pre>\n"
}
] |
2016/05/31
|
[
"https://wordpress.stackexchange.com/questions/228322",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93685/"
] |
I am facing a problem to set default value for the checkbox field in WordPress.
I have a checkbox input field (metabox) in a custom post. I want the checkbox to be checked by default. and if user uncheck it then it should be saved and unchecked and remain unchecked when page is refreshed. My problem is that I can not set the default value for the checkbox. I have only two values to work with. Main problem arises, because the savemetadata function runs when I click 'add new' post, So, a default value gets saved in the database automatically without saving the new post. I have been trying for 3 days now. I have tried to save a default value 'yes' when user does not check the checkbox.
but in that case, when user does uncheck then still it become checked with the default value.
my current code snippet
```
// for displaying metabox
function aps_add_meta_box() {
add_meta_box(
'aps_metabox',
__( 'Slider Settings & Shortcode Generator', APS_TEXTDOMAIN ),
'aps_metabox_cb', // callback
'apspostslider', // screen or posttype
'normal'
);}
add_action( 'add_meta_boxes', 'aps_add_meta_box' );
function aps_metabox_cb( $post ) {
wp_nonce_field( 'aps_meta_save', 'aps_meta_save_nounce' ); // nounce
$aps_display_post_title = get_post_meta( $post->ID, 'aps_display_post_title', true );
<input type="checkbox" name="aps_display_post_title" value="yes" <?php checked( $aps_display_post_title, 'yes'); />
}
```
The code for saving metabox data in the save fucntion:
```
function aps_meta_save( $post_id ) {
// Perform checking for before saving
$is_autosave = wp_is_post_autosave($post_id);
$is_revision = wp_is_post_revision($post_id);
$is_valid_nonce = (isset($_POST['aps_meta_save_nounce']) && wp_verify_nonce( $_POST['aps_meta_save_nounce'], 'aps_meta_save' )? 'true': 'false');
if ( $is_autosave || $is_revision || !$is_valid_nonce ) return;
// Is the user allowed to edit the post or page?
if ( !current_user_can( 'edit_post', $post_id )) return;
$aps_display_post_title = (isset($_POST['aps_display_post_title']))? sanitize_text_field( $_POST["aps_display_post_title"] ): '' ;
update_post_meta($post_id, "aps_display_post_title", $aps_display_post_title);
}
// save only when aps post slider posttype is saved
add_action( 'save_post_apspostslider', 'aps_meta_save');
```
I have tried the following code while saving but in that case the checkbox is checked by default. but when I uncheck and save the post, then checkbox remained checked.
```
$aps_display_post_title = (isset($_POST['aps_display_post_title']))? sanitize_text_field( $_POST["aps_display_post_title"] ): 'yes' ;
update_post_meta($post_id, "aps_display_post_title", $aps_display_post_title);
```
**UPDATE:**
Now everything is working after changing the hook. the save\_post hook runs when a post is newly created or updated. SO, the function to save the meta data would run when a post is created and thus a default value would be saved in the database. However, now after changing the hook to -"edit\_post", now everything works. Thanks to the brother [majick](https://wordpress.stackexchange.com/users/76440/majick) who helped me. All working code is given below:
```
//Show meta box
function aps_add_meta_box() {
add_meta_box(
'aps_metabox',
__( 'Slider Settings & Shortcode Generator', APS_TEXTDOMAIN ),
'aps_metabox_cb',
'apspostslider',
'normal'
);
}
add_action( 'add_meta_boxes', 'aps_add_meta_box' );
/**
* Prints the box content.
*/
function aps_metabox_cb( $post ) {
// Add a nonce field so we can check for it later.
wp_nonce_field( 'aps_meta_save', 'aps_meta_save_nounce' );
$aps_display_post_title = get_post_meta( $post->ID, 'aps_display_post_title', true );
<input type="checkbox" name="aps_display_post_title" value="yes" <?php if ($aps_display_post_title != 'no') { echo 'checked'; }?>/>
}
// Save or Update metabox data
function aps_meta_save( $post_id, $post ) {
if ($post->post_type != 'apspostslider') {return;}
// Perform checking for before saving
$is_autosave = wp_is_post_autosave($post_id);
$is_revision = wp_is_post_revision($post_id);
$is_valid_nonce = (isset($_POST['aps_meta_save_nounce']) && wp_verify_nonce( $_POST['aps_meta_save_nounce'], 'aps_meta_save' )? 'true': 'false');
if ( $is_autosave || $is_revision || !$is_valid_nonce ) return;
// Is the user allowed to edit the post or page?
if ( !current_user_can( 'edit_post', $post_id )) return;
if ( (isset($_POST['aps_display_post_title']))
&& ($_POST['aps_display_post_title'] == 'yes') ) {
$aps_display_post_title = 'yes';
} else {$aps_display_post_title = 'no';}
update_post_meta($post_id, "aps_display_post_title", $aps_display_post_title);
add_action( 'edit_post', 'aps_meta_save', 10, 2);
```
|
I think the problem might could be the logic with using `checked`...
```
<input type="checkbox" name="aps_display_post_title" value="yes" <?php if ($aps_display_post_title != 'no') {echo 'checked';} ?> />
```
...on the other hand then running `sanitize_text_field` on the checkbox value might also be causing the problem.
Instead you might want to break the logic down differently so it is easier to understand, and use this with the code above which checked that the value is not `no` and so will default as checked:
```
if ( (isset($_POST['aps_display_post_title']))
&& ($_POST['aps_display_post_title'] == 'yes') ) {
$aps_display_post_title = 'yes';}
} else {$aps_display_post_title = 'no';}
update_post_meta($post_id, "aps_display_post_title", $aps_display_post_title);
```
**UPDATE**
To prevent the metasave function from firing on post creation, hook to `edit_post` instead of `save_post` (and do the post type check internally using the second argument passed which is `$post`)...
```
add_action( 'edit_post', 'aps_meta_save', 10, 2);
function aps_meta_save($post_id, $post) {
if ($post->post_type != 'apspostslider') {return;}
...
```
|
228,356 |
<p>I've seen there are several ways to display a user's last login date on the Users page without having to use a 3rd party plugin. Building on that, I'd really like to have the user's last login date column be sortable (hopefully orderby date). </p>
<p>I'm using the display user last login function via <a href="http://wpdailybits.com/blog/capture-user-last-login-time/705" rel="nofollow">wpdailybits</a>, but my additions to the code can't get the column to sort. </p>
<p>Suggestions? I know I'm missing something...</p>
<pre><code>//Capture User Last Login
add_action('wp_login','wpdb_capture_user_last_login', 10, 2);
function wpdb_capture_user_last_login($user_login, $user){
update_user_meta($user->ID, 'last_login', current_time('mysql'));
}
//Display Last Login Date in Admin
add_filter( 'manage_users_columns', 'wpdb_user_last_login_column');
function wpdb_user_last_login_column($columns){
$columns['lastlogin'] = __('Last Login', 'lastlogin');
return $columns;
}
add_action( 'manage_users_custom_column', 'wpdb_add_user_last_login_column', 10, 3);
function wpdb_add_user_last_login_column($value, $column_name, $user_id ) {
if ( 'lastlogin' != $column_name )
return $value;
return get_user_last_login($user_id,false);
}
function get_user_last_login($user_id,$echo = true){
$date_format = get_option('date_format') . ' ' . get_option('time_format');
$last_login = get_user_meta($user_id, 'last_login', true);
$login_time = 'Never logged in';
if(!empty($last_login)){
if(is_array($last_login)){
$login_time = mysql2date($date_format, array_pop($last_login), false);
}
else{
$login_time = mysql2date($date_format, $last_login, false);
}
}
if($echo){
echo $login_time;
}
else{
return $login_time;
}
}
//Sort the Columns
add_filter( 'manage_edit-users_sortable_columns', 'sortable_users_column' );
function sortable_users_column( $sortable_columns ) {
$sortable_columns[ 'last_login_column' ] = 'lastlogin';
}
</code></pre>
|
[
{
"answer_id": 228397,
"author": "brianjohnhanna",
"author_id": 65403,
"author_profile": "https://wordpress.stackexchange.com/users/65403",
"pm_score": 3,
"selected": true,
"text": "<p>I don't see anywhere in your code that the query is being modified. Just flagging a column to be sortable doesn't mean it knows how to sort the data - it will just add the little up/down arrow and make the column clickable but you have to intercept the query var accordingly and tell WP what to do. You'll want to hook into <code>pre_get_users</code> and modify the query accordingly. Since you're already storing the time using <code>current_time( 'mysql' )</code> then the default ordering should work as intended.</p>\n\n<p>This is untested but should work or at least get you started.</p>\n\n<pre><code>add_action( 'pre_get_users', 'wpse_filter_user_query' );\nfunction wpse_filter_user_query( $user_query ) {\n global $current_screen;\n\n if ( !is_admin() || 'users' != $current_screen->id ) \n return;\n\n if( 'lastlogin' == $user_query->get( 'orderby' ) ) \n {\n $user_query->set( 'orderby', 'meta_value' ); \n $user_query->set( 'meta_key', 'last_login' );\n } \n}\n</code></pre>\n"
},
{
"answer_id": 378084,
"author": "Viktor Borítás",
"author_id": 142701,
"author_profile": "https://wordpress.stackexchange.com/users/142701",
"pm_score": 0,
"selected": false,
"text": "<p>You can try to use <code>'manage_users_sortable_columns'</code> filter handle instead.</p>\n<pre><code>//Sort the Columns\n add_filter( 'manage_users_sortable_columns', 'sortable_users_column' );\n\n function sortable_users_column( $sortable_columns ) {\n $sortable_columns[ 'last_login_column' ] = 'lastlogin';\n }\n</code></pre>\n<p>That's the proper one for the users admin screen.</p>\n"
}
] |
2016/05/31
|
[
"https://wordpress.stackexchange.com/questions/228356",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54745/"
] |
I've seen there are several ways to display a user's last login date on the Users page without having to use a 3rd party plugin. Building on that, I'd really like to have the user's last login date column be sortable (hopefully orderby date).
I'm using the display user last login function via [wpdailybits](http://wpdailybits.com/blog/capture-user-last-login-time/705), but my additions to the code can't get the column to sort.
Suggestions? I know I'm missing something...
```
//Capture User Last Login
add_action('wp_login','wpdb_capture_user_last_login', 10, 2);
function wpdb_capture_user_last_login($user_login, $user){
update_user_meta($user->ID, 'last_login', current_time('mysql'));
}
//Display Last Login Date in Admin
add_filter( 'manage_users_columns', 'wpdb_user_last_login_column');
function wpdb_user_last_login_column($columns){
$columns['lastlogin'] = __('Last Login', 'lastlogin');
return $columns;
}
add_action( 'manage_users_custom_column', 'wpdb_add_user_last_login_column', 10, 3);
function wpdb_add_user_last_login_column($value, $column_name, $user_id ) {
if ( 'lastlogin' != $column_name )
return $value;
return get_user_last_login($user_id,false);
}
function get_user_last_login($user_id,$echo = true){
$date_format = get_option('date_format') . ' ' . get_option('time_format');
$last_login = get_user_meta($user_id, 'last_login', true);
$login_time = 'Never logged in';
if(!empty($last_login)){
if(is_array($last_login)){
$login_time = mysql2date($date_format, array_pop($last_login), false);
}
else{
$login_time = mysql2date($date_format, $last_login, false);
}
}
if($echo){
echo $login_time;
}
else{
return $login_time;
}
}
//Sort the Columns
add_filter( 'manage_edit-users_sortable_columns', 'sortable_users_column' );
function sortable_users_column( $sortable_columns ) {
$sortable_columns[ 'last_login_column' ] = 'lastlogin';
}
```
|
I don't see anywhere in your code that the query is being modified. Just flagging a column to be sortable doesn't mean it knows how to sort the data - it will just add the little up/down arrow and make the column clickable but you have to intercept the query var accordingly and tell WP what to do. You'll want to hook into `pre_get_users` and modify the query accordingly. Since you're already storing the time using `current_time( 'mysql' )` then the default ordering should work as intended.
This is untested but should work or at least get you started.
```
add_action( 'pre_get_users', 'wpse_filter_user_query' );
function wpse_filter_user_query( $user_query ) {
global $current_screen;
if ( !is_admin() || 'users' != $current_screen->id )
return;
if( 'lastlogin' == $user_query->get( 'orderby' ) )
{
$user_query->set( 'orderby', 'meta_value' );
$user_query->set( 'meta_key', 'last_login' );
}
}
```
|
228,358 |
<p>For version control purpose, our client has a WordPress app with directory structure like this:</p>
<pre><code>.
|_____app
| |_____themes
| |_____plugins
| |_____uploads
|_____index.php
|_____WordPress
|_____wp-config.php
</code></pre>
<p>In <code>wp-config.php</code>:</p>
<pre><code>define('WP_CONTENT_DIR', __DIR__ . '/app');
define('WP_CONTENT_URL', WP_HOME . '/app');
</code></pre>
<p>Now, she want to rename all default WordPress folders in app directory.</p>
<p>With <code>plugins</code> and <code>themes</code> we can do it easily by using <code>WP_PLUGIN_DIR</code> and <a href="https://developer.wordpress.org/reference/functions/register_theme_directory/">register_theme_directory()</a>. But, somehow, it's not easy to rename <code>uploads</code> folder.</p>
<p>I have tried many modifications with <code>UPLOADS</code> constant, but it can't help because custom uploads folder is always created inside <code>WordPress</code> directory.</p>
<p>Are there any ways to workaround this problem?</p>
|
[
{
"answer_id": 228368,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 2,
"selected": false,
"text": "<p>If you look at the source of <a href=\"https://developer.wordpress.org/reference/functions/_wp_upload_dir/\" rel=\"nofollow\"><code>_wp_upload_dir</code></a>, you'll see:</p>\n\n<pre><code>if (defined('UPLOADS') && ! (is_multisite() && get_site_option('ms_files_rewriting'))) {\n $dir = ABSPATH.UPLOADS;\n $url = trailingslashit($siteurl).UPLOADS;\n}\n</code></pre>\n\n<p>So <code>UPLOADS</code> can only be used to define a foder relative to <code>ABSPATH</code>, which I guess is <code>/WordPress</code> folder in your setup.</p>\n\n<p>In the same function, you can see that if <code>get_option('upload_path')</code> and <code>get_option('upload_url_path')</code> are empty, the path and the URL of uploads folder are set to, respectively, <code>WP_CONTENT_DIR.'/uploads'</code> and <code>WP_CONTENT_URL.'/uploads'</code> which should be perfectly fine for you, as long as you define <code>WP_CONTENT_DIR</code> and <code>WP_CONTENT_URL</code> like in OP.</p>\n\n<p>If you don't define <code>UPLOADS</code>at all and the uploads folder is still not resolved to <code>/app/uploads</code>, very likely your database contains <em>some</em> value for <code>'upload_path'</code> and <code>'upload_url_path'</code> options.</p>\n\n<p>You have 2 possibilities:</p>\n\n<ul>\n<li>delete those options</li>\n<li>use <a href=\"https://developer.wordpress.org/reference/hooks/pre_option_option/\" rel=\"nofollow\"><code>\"pre_option_{$option}\"</code></a> filters to force <code>get_option()</code> to return something empty for those options (but not <code>false</code> or the filters will be ignored). </li>\n</ul>\n\n<p>For the second possibility the code could be something like this:</p>\n\n<pre><code>add_filter('pre_option_upload_path', '__return_empty_string');\nadd_filter('pre_option_upload_url_path', '__return_empty_string');\n</code></pre>\n\n<p>With the above code in place, and without any <code>UPLOADS</code> constant defined, as long as you define <code>WP_CONTENT_DIR</code> and <code>WP_CONTENT_URL</code>, the uploads folder should be resolved correctly.</p>\n\n<p>If that not happen, there must be something that acts on <em>some</em> filter, for instance <a href=\"https://developer.wordpress.org/reference/hooks/upload_dir/\" rel=\"nofollow\"><code>upload_dir</code></a>.</p>\n"
},
{
"answer_id": 228470,
"author": "wpclevel",
"author_id": 92212,
"author_profile": "https://wordpress.stackexchange.com/users/92212",
"pm_score": 4,
"selected": true,
"text": "<p>After digging around, I ended up with using <a href=\"https://developer.wordpress.org/reference/hooks/upload_dir/\" rel=\"nofollow noreferrer\"><code>upload_dir</code></a> filter.</p>\n\n<p>Here is what I tried in <code>functions.php</code> to change <code>uploads</code> to <code>media</code>. Hope it can help someone too :)</p>\n\n<pre><code> add_filter('upload_dir', function($uploads)\n {\n $custom = [];\n\n foreach ($uploads as $key => $value) {\n if ( false !== strpos($value, '/app/uploads') ) {\n $custom[$key] = str_replace('/app/uploads', '/app/media', $value);\n } else {\n $custom[$key] = $value;\n }\n }\n\n return $custom;\n });\n</code></pre>\n\n<p>Many thanks to <a href=\"https://wordpress.stackexchange.com/users/35541/gmazzap\">@gmazzap</a> for the guidelines and the suggestion about <code>upload_dir</code> filter!</p>\n"
}
] |
2016/05/31
|
[
"https://wordpress.stackexchange.com/questions/228358",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92212/"
] |
For version control purpose, our client has a WordPress app with directory structure like this:
```
.
|_____app
| |_____themes
| |_____plugins
| |_____uploads
|_____index.php
|_____WordPress
|_____wp-config.php
```
In `wp-config.php`:
```
define('WP_CONTENT_DIR', __DIR__ . '/app');
define('WP_CONTENT_URL', WP_HOME . '/app');
```
Now, she want to rename all default WordPress folders in app directory.
With `plugins` and `themes` we can do it easily by using `WP_PLUGIN_DIR` and [register\_theme\_directory()](https://developer.wordpress.org/reference/functions/register_theme_directory/). But, somehow, it's not easy to rename `uploads` folder.
I have tried many modifications with `UPLOADS` constant, but it can't help because custom uploads folder is always created inside `WordPress` directory.
Are there any ways to workaround this problem?
|
After digging around, I ended up with using [`upload_dir`](https://developer.wordpress.org/reference/hooks/upload_dir/) filter.
Here is what I tried in `functions.php` to change `uploads` to `media`. Hope it can help someone too :)
```
add_filter('upload_dir', function($uploads)
{
$custom = [];
foreach ($uploads as $key => $value) {
if ( false !== strpos($value, '/app/uploads') ) {
$custom[$key] = str_replace('/app/uploads', '/app/media', $value);
} else {
$custom[$key] = $value;
}
}
return $custom;
});
```
Many thanks to [@gmazzap](https://wordpress.stackexchange.com/users/35541/gmazzap) for the guidelines and the suggestion about `upload_dir` filter!
|
228,390 |
<p>I have this shortcode to display a loop of user avatars with order by registration date.</p>
<pre><code>function Profiles() {
$args = array(
'orderby' => 'registered',
'order' => 'DESC',
'fields' => 'all_with_meta',
);
$user_query = new WP_User_Query( $args );
if ( ! empty( $user_query->results ) ) {
foreach ( $user_query->results as $user ) { ?>
<div class="user-item user-img-<?php echo $user->ID; ?>" rel="<?php echo $user->ID; ?>">
<a href="<?php echo $website; ?>" rel="<?php echo $user->ID; ?>" target="_blank"><?php echo get_avatar( $user->ID, 100 ); ?></a>
</div>
<?php }
} else {
echo 'No users found.';
}
}
add_shortcode('profiles', 'Profiles');
</code></pre>
<p>If any user role changes to <code>sticky</code> (a custom role) then that users move to top of the list. Default orderby should stay as registered for all other users in the loop. Once <code>sticky</code> user role is removed, it goes back to normal sorting.</p>
<p>I gave it quite a bit thought and maybe if i can combine two arguments in a single <code>Wp_User_Query</code> that might do the trick?</p>
<p>For example <code>$sticky_args</code> have <code>role__in => 'sticky'</code> and <code>$simple_args</code> have all others <code>roles => 'subscriber', 'customer', 'author'</code> OR <code>role__not_in => 'sticky'</code> argument. Then combining this <code>Wp_User_Query</code> in a way that <code>$user_query->results</code> shows <code>$sticky_args</code> users list first and then <code>$simple_args</code> user list after that in the loop. I tried several codes and trying to think if statements but nothing works so far. Google didn't help either. Would appreciate the help.</p>
|
[
{
"answer_id": 228385,
"author": "user9447",
"author_id": 25271,
"author_profile": "https://wordpress.stackexchange.com/users/25271",
"pm_score": 3,
"selected": true,
"text": "<p>Based on what you're asking and what I am understanding there is <a href=\"https://codex.wordpress.org/Function_Reference/the_modified_date\" rel=\"nofollow noreferrer\"><code>the_modified_date()</code></a> or if you just want the value <a href=\"https://codex.wordpress.org/Function_Reference/get_the_modified_date\" rel=\"nofollow noreferrer\"><code>get_the_modified_date()</code></a>.</p>\n\n<p>If you ever want the creation date you could use <code>post_date</code> and <code>post_date_gmt</code>. Several questions on this:</p>\n\n<ul>\n<li><a href=\"https://wordpress.stackexchange.com/questions/177065/how-to-get-post-creation-date\">How to get post creation date?</a></li>\n<li><a href=\"https://wordpress.stackexchange.com/questions/134512/what-is-considered-the-posts-creation-date-for-wp-insert-post\">What is considered the post's creation date for wp_insert_post?</a></li>\n</ul>\n\n<p>If you are asking for a complete solution I would encourage you to search under custom post type and <code>wp_query</code>. We have several questions that are on the topic. If can make an edit with code I do not mind trying to help you further.</p>\n"
},
{
"answer_id": 228393,
"author": "Steven",
"author_id": 13118,
"author_profile": "https://wordpress.stackexchange.com/users/13118",
"pm_score": 1,
"selected": false,
"text": "<p>You need a custom query for that. Basically, just a query that pulls 1 result from the posts table where the post type is your custom post type:</p>\n\n<pre><code>global $wpdb;\n\n// the name you gave to your custom post type\n$post_type = 'my_custom_post_type';\n\n// this is the query string that we'll use with the $wpdb class\n// selecting from the posts table where the post_type is your custom post type\n// ordered DESC and LIMITed to 1 to get on the most recent entry\n$query_str = \"SELECT * from \" . $wpdb -> prefix . \"posts WHERE post_type = %s ORDER BY post_date DESC LIMIT 1\";\n\n// it's good practice to $wpdb -> prepare queries to the database\n$results = $wpdb -> get_results( $wpdb -> prepare( $query_str, $post_type ) );\n</code></pre>\n\n<p>I've used <code>get_results</code> so you have your choice of which date (created or modified) you want to use</p>\n"
}
] |
2016/05/31
|
[
"https://wordpress.stackexchange.com/questions/228390",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94925/"
] |
I have this shortcode to display a loop of user avatars with order by registration date.
```
function Profiles() {
$args = array(
'orderby' => 'registered',
'order' => 'DESC',
'fields' => 'all_with_meta',
);
$user_query = new WP_User_Query( $args );
if ( ! empty( $user_query->results ) ) {
foreach ( $user_query->results as $user ) { ?>
<div class="user-item user-img-<?php echo $user->ID; ?>" rel="<?php echo $user->ID; ?>">
<a href="<?php echo $website; ?>" rel="<?php echo $user->ID; ?>" target="_blank"><?php echo get_avatar( $user->ID, 100 ); ?></a>
</div>
<?php }
} else {
echo 'No users found.';
}
}
add_shortcode('profiles', 'Profiles');
```
If any user role changes to `sticky` (a custom role) then that users move to top of the list. Default orderby should stay as registered for all other users in the loop. Once `sticky` user role is removed, it goes back to normal sorting.
I gave it quite a bit thought and maybe if i can combine two arguments in a single `Wp_User_Query` that might do the trick?
For example `$sticky_args` have `role__in => 'sticky'` and `$simple_args` have all others `roles => 'subscriber', 'customer', 'author'` OR `role__not_in => 'sticky'` argument. Then combining this `Wp_User_Query` in a way that `$user_query->results` shows `$sticky_args` users list first and then `$simple_args` user list after that in the loop. I tried several codes and trying to think if statements but nothing works so far. Google didn't help either. Would appreciate the help.
|
Based on what you're asking and what I am understanding there is [`the_modified_date()`](https://codex.wordpress.org/Function_Reference/the_modified_date) or if you just want the value [`get_the_modified_date()`](https://codex.wordpress.org/Function_Reference/get_the_modified_date).
If you ever want the creation date you could use `post_date` and `post_date_gmt`. Several questions on this:
* [How to get post creation date?](https://wordpress.stackexchange.com/questions/177065/how-to-get-post-creation-date)
* [What is considered the post's creation date for wp\_insert\_post?](https://wordpress.stackexchange.com/questions/134512/what-is-considered-the-posts-creation-date-for-wp-insert-post)
If you are asking for a complete solution I would encourage you to search under custom post type and `wp_query`. We have several questions that are on the topic. If can make an edit with code I do not mind trying to help you further.
|
228,395 |
<p>Oddly enough I can't seem to find anyone asking this question exactly in this fashion.</p>
<p>Is it at possible to make a page be a child of a CPT? In a repeatable fashion (see below for more info) n.b. I do not mean vice versa -- which is easy enough see: <a href="https://wordpress.stackexchange.com/questions/81711/can-a-custom-post-type-have-a-parent-page">Can a custom post type have a Parent Page?</a></p>
<p>Example:</p>
<ul>
<li>I have a CPT <code>author</code> with a permalink structure: <a href="http://example.com/authors/john-doe" rel="nofollow noreferrer">http://example.com/authors/john-doe</a> </li>
<li>I want a custom Thank You post type <code>page</code> to live at <a href="http://example.com/authors/john-doe/thank-you" rel="nofollow noreferrer">http://example.com/authors/john-doe/thank-you</a> </li>
</ul>
<p>Is that possible to achieve that permalink structure in a repeatable manner? That is I'd want to have multiple arbitrary children <code>page</code> post type posts underneath the arbitrary <code>author</code> post type posts?</p>
<p>N.b. not all author pages will need to have a /authors/author-name/thank-you some many need nothing at all, some may need a different slug e.g. /authors/jane-doe/happy-birthday-greeting</p>
|
[
{
"answer_id": 228396,
"author": "Jake Deichmann",
"author_id": 94445,
"author_profile": "https://wordpress.stackexchange.com/users/94445",
"pm_score": 1,
"selected": false,
"text": "<p>I can't really think of an easy and repeatable way to do this, but check out: <a href=\"https://wordpress.org/support/topic/create-static-subpage-for-a-custom-post-type\" rel=\"nofollow\">https://wordpress.org/support/topic/create-static-subpage-for-a-custom-post-type</a></p>\n\n<p>You can create a custom parameter at the end of your post type. Once you get this you can load a template and use that parameter to query the page's content.</p>\n"
},
{
"answer_id": 228398,
"author": "brianjohnhanna",
"author_id": 65403,
"author_profile": "https://wordpress.stackexchange.com/users/65403",
"pm_score": 2,
"selected": false,
"text": "<p>I can't really think of a way that you would have a post type of page and have it be \"repeatable.\" As Jake said, it's going to involve rewrite rules. I think the easiest way to do it would be to set up some templates for whatever these cases may be in your theme directory, and make use of query vars to populate them. So, for example:</p>\n\n<pre><code>function wpse_add_query_vars( $vars ){\n $vars[] = \"tmpl\";\n $vars[] = \"author_slug\";\n return $vars;\n}\nadd_filter( 'query_vars', 'wpse_add_query_vars' );\n\nfunction wpse_add_rewrite_rule() {\n add_rewrite_rule( '^authors/([^/]*)/([^/]*)', 'index.php?author_slug=$matches[1]&tmpl=$matches[2]', 'top' );\n}\nadd_action( 'init', 'wpse_add_rewrite_rule' );\n\nfunction wpse_template_include( $template ) {\n if ( get_query_var( 'tmpl' ) && get_query_var( 'author_slug' ) ) {\n if ( file_exists( get_template_directory() . '/' . get_query_var( 'tmpl' ) . '.php' ) ) {\n $template = get_template_directory() . '/' . get_query_var( 'tmpl' ) . '.php';\n }\n }\n return $template;\n}\nadd_filter( 'template_include', 'wpse_template_include' );\n</code></pre>\n\n<p>I tested this and it works, but it will probably need to be tweaked for your needs. Basically, here's what's happening:</p>\n\n<ol>\n<li>We register a <code>tmpl</code> query var so we can specify a template file slug as the name. We will have to create the templates we want in our theme folder.</li>\n<li>We'll add a rewrite rule so that if you hit <code>/authors/author-name/template-name</code> then we can load a template (if it exists). <em>Make sure to flush your permalinks in settings after adding or changing any rewrite rules!</em></li>\n<li>Now we hook into <code>template_include</code> to see if we have the <code>tmpl</code> var set, check if we have a template in our theme directory, and return that template if we have it. So, for example, we hit <code>/authors/author-name/thank-you</code>, we will look for a <code>thank-you.php</code> template file in the theme folder and load that instead of a default template. You would have access to the author slug in the template file by using <code>get_query_var()</code>.</li>\n</ol>\n\n<p>This is just an abstract example and will obviously need to be tweaked for your needs, but using this method you would be able to make as many of these pages as you need and maintain them right from the theme. I also didn't create an author CPT to fully test this so you may need to adjust the rewrite rule so it doesn't conflict with other things you are trying to do with the author CPT (in fact, you may not even need to use the author_slug query var as it's probably available already from WP).</p>\n\n<p>Here's some more resources:</p>\n\n<ol>\n<li><a href=\"http://code.tutsplus.com/articles/custom-page-template-page-based-on-url-rewrite--wp-30564\" rel=\"nofollow\">Custom Page Template Page Based on URL Rewrite</a></li>\n<li><a href=\"http://code.tutsplus.com/articles/the-rewrite-api-post-types-taxonomies--wp-25488\" rel=\"nofollow\">The Rewrite API: Post Types & Taxonomies</a></li>\n</ol>\n\n<p>Of course there's more than one way to skin a cat, but hope this helps point you in the right direction or at least gives you some ideas of what's possible.</p>\n"
}
] |
2016/05/31
|
[
"https://wordpress.stackexchange.com/questions/228395",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8756/"
] |
Oddly enough I can't seem to find anyone asking this question exactly in this fashion.
Is it at possible to make a page be a child of a CPT? In a repeatable fashion (see below for more info) n.b. I do not mean vice versa -- which is easy enough see: [Can a custom post type have a Parent Page?](https://wordpress.stackexchange.com/questions/81711/can-a-custom-post-type-have-a-parent-page)
Example:
* I have a CPT `author` with a permalink structure: <http://example.com/authors/john-doe>
* I want a custom Thank You post type `page` to live at <http://example.com/authors/john-doe/thank-you>
Is that possible to achieve that permalink structure in a repeatable manner? That is I'd want to have multiple arbitrary children `page` post type posts underneath the arbitrary `author` post type posts?
N.b. not all author pages will need to have a /authors/author-name/thank-you some many need nothing at all, some may need a different slug e.g. /authors/jane-doe/happy-birthday-greeting
|
I can't really think of a way that you would have a post type of page and have it be "repeatable." As Jake said, it's going to involve rewrite rules. I think the easiest way to do it would be to set up some templates for whatever these cases may be in your theme directory, and make use of query vars to populate them. So, for example:
```
function wpse_add_query_vars( $vars ){
$vars[] = "tmpl";
$vars[] = "author_slug";
return $vars;
}
add_filter( 'query_vars', 'wpse_add_query_vars' );
function wpse_add_rewrite_rule() {
add_rewrite_rule( '^authors/([^/]*)/([^/]*)', 'index.php?author_slug=$matches[1]&tmpl=$matches[2]', 'top' );
}
add_action( 'init', 'wpse_add_rewrite_rule' );
function wpse_template_include( $template ) {
if ( get_query_var( 'tmpl' ) && get_query_var( 'author_slug' ) ) {
if ( file_exists( get_template_directory() . '/' . get_query_var( 'tmpl' ) . '.php' ) ) {
$template = get_template_directory() . '/' . get_query_var( 'tmpl' ) . '.php';
}
}
return $template;
}
add_filter( 'template_include', 'wpse_template_include' );
```
I tested this and it works, but it will probably need to be tweaked for your needs. Basically, here's what's happening:
1. We register a `tmpl` query var so we can specify a template file slug as the name. We will have to create the templates we want in our theme folder.
2. We'll add a rewrite rule so that if you hit `/authors/author-name/template-name` then we can load a template (if it exists). *Make sure to flush your permalinks in settings after adding or changing any rewrite rules!*
3. Now we hook into `template_include` to see if we have the `tmpl` var set, check if we have a template in our theme directory, and return that template if we have it. So, for example, we hit `/authors/author-name/thank-you`, we will look for a `thank-you.php` template file in the theme folder and load that instead of a default template. You would have access to the author slug in the template file by using `get_query_var()`.
This is just an abstract example and will obviously need to be tweaked for your needs, but using this method you would be able to make as many of these pages as you need and maintain them right from the theme. I also didn't create an author CPT to fully test this so you may need to adjust the rewrite rule so it doesn't conflict with other things you are trying to do with the author CPT (in fact, you may not even need to use the author\_slug query var as it's probably available already from WP).
Here's some more resources:
1. [Custom Page Template Page Based on URL Rewrite](http://code.tutsplus.com/articles/custom-page-template-page-based-on-url-rewrite--wp-30564)
2. [The Rewrite API: Post Types & Taxonomies](http://code.tutsplus.com/articles/the-rewrite-api-post-types-taxonomies--wp-25488)
Of course there's more than one way to skin a cat, but hope this helps point you in the right direction or at least gives you some ideas of what's possible.
|
228,402 |
<p>In the plugin, The css file loads sitewide by default, I want to load it only on the Single post.</p>
<p>the conditional tags, i.e, is_single() isn’t working in plugins,</p>
<p>any idea how can we achieve that?</p>
|
[
{
"answer_id": 228410,
"author": "Steve Clason",
"author_id": 94857,
"author_profile": "https://wordpress.stackexchange.com/users/94857",
"pm_score": 0,
"selected": false,
"text": "<p>You need something like this in your functions.php file:</p>\n\n<pre><code>if( is_single()) {\n wp_enqueue_style( 'ahmedkaludi-style', get_stylesheet_uri() . '/css/plugin-styles.css' );\n}\n</code></pre>\n\n<p>Change '/css/plugin-styles.css' to the actual path of the plugin's stylesheet.</p>\n\n<p>If the plugin is written well, <code>wp_enqueue_style</code> will be wrapped in a function, like:</p>\n\n<pre><code>if ( ! function_exists( 'my_scripts' ) ) {\n function my_scripts() {\n wp_enqueue_style( 'ahmedkaludi-style', get_stylesheet_uri() . '/css/plugin-styles.css' );\n }\n add_action( 'wp_enqueue_scripts', 'steveclason_flat_scripts' );\n}\n</code></pre>\n\n<p>If that's how it's done in the plugin you can override it with a similar block of code in your theme's functions.php. We can't make very good recommendations without seeing how the plugin calls the stylesheet -- the block of code on your Pastebin does something else.</p>\n"
},
{
"answer_id": 228418,
"author": "bravokeyl",
"author_id": 43098,
"author_profile": "https://wordpress.stackexchange.com/users/43098",
"pm_score": 1,
"selected": false,
"text": "<p><strong>TL,DR;</strong></p>\n\n<p>You are hooking early.</p>\n\n<hr>\n\n<blockquote>\n <p>In the plugin, the css file loads site-wide by default, I want to load\n it only on the single post.</p>\n</blockquote>\n\n<p>It's a very good thought many developers don't take this into account while developing themes/plugins.</p>\n\n<blockquote>\n <p><strong><code>is_single()</code></strong> isn’t working in plugins</p>\n</blockquote>\n\n<p>Where are you using <strong><code>is_single</code></strong> template tag in <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow\">WP run cycle</a> ?</p>\n\n<h1>Assuming you are hooking to <strong><code>init</code></strong> or <strong><code>wp</code></strong></h1>\n\n<p>Template tags are not available yet until <strong><code>template_redirect</code></strong> action. So those tags don't work for <strong><code>init</code></strong> or <strong><code>wp</code></strong>.</p>\n\n<p>Best place to work with scripts or styles is on <strong><code>wp_enqueue_scripts</code></strong> which runs after <strong><code>template_redirect</code></strong> .</p>\n\n<blockquote>\n <p>Any idea how can we achieve that ?</p>\n</blockquote>\n\n<p>There are many ways to achieve depending on the plugin we are using. </p>\n\n<p>Coming to <strong>TablePress</strong> plugin.</p>\n\n<p><code>controllers/controller-frontend.php</code> is the place where plugin is en-queue-ing stylesheet.</p>\n\n<pre><code>if ( apply_filters( 'tablepress_use_default_css', true ) || TablePress::$model_options->get( 'use_custom_css' ) ) {\n add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_css' ) );\n}\n</code></pre>\n\n<p>You can completely turn off en-queuing the stylesheet using the <strong><code>tablepress_use_default_css</code></strong> and custom css option to false, and then load them wherever you need in your custom plugin/theme.</p>\n\n<p>If you dig through the file there are many conditional en-queuing is done for that plugin.</p>\n\n<p>You can also dequeue style first and then enqueue wherever needed.</p>\n\n<h1>Sample code</h1>\n\n<pre><code>add_action('wp_enqueue_scripts','wp_228402_load_styles_conditionally',11);\nfunction wp_228402_load_styles_conditionally() {\n if(is_single()){\n return; // return if not on the single post/page\n }\n wp_dequeue_style('tablepress-default'); \n}\n</code></pre>\n\n<p>Check the <strong>priority</strong> for the above that's the key it should be greater than default value <strong>10</strong>.</p>\n"
}
] |
2016/05/31
|
[
"https://wordpress.stackexchange.com/questions/228402",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/95019/"
] |
In the plugin, The css file loads sitewide by default, I want to load it only on the Single post.
the conditional tags, i.e, is\_single() isn’t working in plugins,
any idea how can we achieve that?
|
**TL,DR;**
You are hooking early.
---
>
> In the plugin, the css file loads site-wide by default, I want to load
> it only on the single post.
>
>
>
It's a very good thought many developers don't take this into account while developing themes/plugins.
>
> **`is_single()`** isn’t working in plugins
>
>
>
Where are you using **`is_single`** template tag in [WP run cycle](https://codex.wordpress.org/Plugin_API/Action_Reference) ?
Assuming you are hooking to **`init`** or **`wp`**
==================================================
Template tags are not available yet until **`template_redirect`** action. So those tags don't work for **`init`** or **`wp`**.
Best place to work with scripts or styles is on **`wp_enqueue_scripts`** which runs after **`template_redirect`** .
>
> Any idea how can we achieve that ?
>
>
>
There are many ways to achieve depending on the plugin we are using.
Coming to **TablePress** plugin.
`controllers/controller-frontend.php` is the place where plugin is en-queue-ing stylesheet.
```
if ( apply_filters( 'tablepress_use_default_css', true ) || TablePress::$model_options->get( 'use_custom_css' ) ) {
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_css' ) );
}
```
You can completely turn off en-queuing the stylesheet using the **`tablepress_use_default_css`** and custom css option to false, and then load them wherever you need in your custom plugin/theme.
If you dig through the file there are many conditional en-queuing is done for that plugin.
You can also dequeue style first and then enqueue wherever needed.
Sample code
===========
```
add_action('wp_enqueue_scripts','wp_228402_load_styles_conditionally',11);
function wp_228402_load_styles_conditionally() {
if(is_single()){
return; // return if not on the single post/page
}
wp_dequeue_style('tablepress-default');
}
```
Check the **priority** for the above that's the key it should be greater than default value **10**.
|
228,405 |
<p>I've built a function within a plugin. I'd like to call it with an jQuery ajax function.</p>
<p>The function is defined as follows:</p>
<pre><code>add_action( 'wp_ajax_my_test_ajax', 'my_test_ajax' );
add_action( 'wp_ajax_nopriv_my_test_ajax', 'my_test_ajax' );
function my_test_ajax() {
$resp = array('title' => 'here is the title', 'content' => ' here is the content') ;
wp_send_json($resp) ;
}
</code></pre>
<p>I then attempt to call the function with from javascript:</p>
<pre><code>var target = 'http://' + window.location.hostname + '/wp-admin/admin-ajax.php' ;
var data = {
action: ' my_test_ajax'
} ;
var req = jQuery.post( target , data, function(resp) {
console.log(resp.responseText);
}) ;
}
</code></pre>
<p>The site responds from admin-ajax.php. The response carries a '200 OK' header. The body of the response is '0'.</p>
<p>The codex tells me that I can expect this response if the value of 'action' in the post body doesn't match the name of a function hooked to the wordpress ajax hooks. But as far as I can tell, I'm good there.</p>
<p>I'm certain that the function is included in my plugin file.</p>
<p>What are the other barest essentials that I need to get this working?</p>
<p>(I don't want to worry about nonces or localizing js at this point. I just want to get a response from the function before I build up further)</p>
|
[
{
"answer_id": 228410,
"author": "Steve Clason",
"author_id": 94857,
"author_profile": "https://wordpress.stackexchange.com/users/94857",
"pm_score": 0,
"selected": false,
"text": "<p>You need something like this in your functions.php file:</p>\n\n<pre><code>if( is_single()) {\n wp_enqueue_style( 'ahmedkaludi-style', get_stylesheet_uri() . '/css/plugin-styles.css' );\n}\n</code></pre>\n\n<p>Change '/css/plugin-styles.css' to the actual path of the plugin's stylesheet.</p>\n\n<p>If the plugin is written well, <code>wp_enqueue_style</code> will be wrapped in a function, like:</p>\n\n<pre><code>if ( ! function_exists( 'my_scripts' ) ) {\n function my_scripts() {\n wp_enqueue_style( 'ahmedkaludi-style', get_stylesheet_uri() . '/css/plugin-styles.css' );\n }\n add_action( 'wp_enqueue_scripts', 'steveclason_flat_scripts' );\n}\n</code></pre>\n\n<p>If that's how it's done in the plugin you can override it with a similar block of code in your theme's functions.php. We can't make very good recommendations without seeing how the plugin calls the stylesheet -- the block of code on your Pastebin does something else.</p>\n"
},
{
"answer_id": 228418,
"author": "bravokeyl",
"author_id": 43098,
"author_profile": "https://wordpress.stackexchange.com/users/43098",
"pm_score": 1,
"selected": false,
"text": "<p><strong>TL,DR;</strong></p>\n\n<p>You are hooking early.</p>\n\n<hr>\n\n<blockquote>\n <p>In the plugin, the css file loads site-wide by default, I want to load\n it only on the single post.</p>\n</blockquote>\n\n<p>It's a very good thought many developers don't take this into account while developing themes/plugins.</p>\n\n<blockquote>\n <p><strong><code>is_single()</code></strong> isn’t working in plugins</p>\n</blockquote>\n\n<p>Where are you using <strong><code>is_single</code></strong> template tag in <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow\">WP run cycle</a> ?</p>\n\n<h1>Assuming you are hooking to <strong><code>init</code></strong> or <strong><code>wp</code></strong></h1>\n\n<p>Template tags are not available yet until <strong><code>template_redirect</code></strong> action. So those tags don't work for <strong><code>init</code></strong> or <strong><code>wp</code></strong>.</p>\n\n<p>Best place to work with scripts or styles is on <strong><code>wp_enqueue_scripts</code></strong> which runs after <strong><code>template_redirect</code></strong> .</p>\n\n<blockquote>\n <p>Any idea how can we achieve that ?</p>\n</blockquote>\n\n<p>There are many ways to achieve depending on the plugin we are using. </p>\n\n<p>Coming to <strong>TablePress</strong> plugin.</p>\n\n<p><code>controllers/controller-frontend.php</code> is the place where plugin is en-queue-ing stylesheet.</p>\n\n<pre><code>if ( apply_filters( 'tablepress_use_default_css', true ) || TablePress::$model_options->get( 'use_custom_css' ) ) {\n add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_css' ) );\n}\n</code></pre>\n\n<p>You can completely turn off en-queuing the stylesheet using the <strong><code>tablepress_use_default_css</code></strong> and custom css option to false, and then load them wherever you need in your custom plugin/theme.</p>\n\n<p>If you dig through the file there are many conditional en-queuing is done for that plugin.</p>\n\n<p>You can also dequeue style first and then enqueue wherever needed.</p>\n\n<h1>Sample code</h1>\n\n<pre><code>add_action('wp_enqueue_scripts','wp_228402_load_styles_conditionally',11);\nfunction wp_228402_load_styles_conditionally() {\n if(is_single()){\n return; // return if not on the single post/page\n }\n wp_dequeue_style('tablepress-default'); \n}\n</code></pre>\n\n<p>Check the <strong>priority</strong> for the above that's the key it should be greater than default value <strong>10</strong>.</p>\n"
}
] |
2016/06/01
|
[
"https://wordpress.stackexchange.com/questions/228405",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51378/"
] |
I've built a function within a plugin. I'd like to call it with an jQuery ajax function.
The function is defined as follows:
```
add_action( 'wp_ajax_my_test_ajax', 'my_test_ajax' );
add_action( 'wp_ajax_nopriv_my_test_ajax', 'my_test_ajax' );
function my_test_ajax() {
$resp = array('title' => 'here is the title', 'content' => ' here is the content') ;
wp_send_json($resp) ;
}
```
I then attempt to call the function with from javascript:
```
var target = 'http://' + window.location.hostname + '/wp-admin/admin-ajax.php' ;
var data = {
action: ' my_test_ajax'
} ;
var req = jQuery.post( target , data, function(resp) {
console.log(resp.responseText);
}) ;
}
```
The site responds from admin-ajax.php. The response carries a '200 OK' header. The body of the response is '0'.
The codex tells me that I can expect this response if the value of 'action' in the post body doesn't match the name of a function hooked to the wordpress ajax hooks. But as far as I can tell, I'm good there.
I'm certain that the function is included in my plugin file.
What are the other barest essentials that I need to get this working?
(I don't want to worry about nonces or localizing js at this point. I just want to get a response from the function before I build up further)
|
**TL,DR;**
You are hooking early.
---
>
> In the plugin, the css file loads site-wide by default, I want to load
> it only on the single post.
>
>
>
It's a very good thought many developers don't take this into account while developing themes/plugins.
>
> **`is_single()`** isn’t working in plugins
>
>
>
Where are you using **`is_single`** template tag in [WP run cycle](https://codex.wordpress.org/Plugin_API/Action_Reference) ?
Assuming you are hooking to **`init`** or **`wp`**
==================================================
Template tags are not available yet until **`template_redirect`** action. So those tags don't work for **`init`** or **`wp`**.
Best place to work with scripts or styles is on **`wp_enqueue_scripts`** which runs after **`template_redirect`** .
>
> Any idea how can we achieve that ?
>
>
>
There are many ways to achieve depending on the plugin we are using.
Coming to **TablePress** plugin.
`controllers/controller-frontend.php` is the place where plugin is en-queue-ing stylesheet.
```
if ( apply_filters( 'tablepress_use_default_css', true ) || TablePress::$model_options->get( 'use_custom_css' ) ) {
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_css' ) );
}
```
You can completely turn off en-queuing the stylesheet using the **`tablepress_use_default_css`** and custom css option to false, and then load them wherever you need in your custom plugin/theme.
If you dig through the file there are many conditional en-queuing is done for that plugin.
You can also dequeue style first and then enqueue wherever needed.
Sample code
===========
```
add_action('wp_enqueue_scripts','wp_228402_load_styles_conditionally',11);
function wp_228402_load_styles_conditionally() {
if(is_single()){
return; // return if not on the single post/page
}
wp_dequeue_style('tablepress-default');
}
```
Check the **priority** for the above that's the key it should be greater than default value **10**.
|
228,406 |
<p>For some reason WordPress is ignoring my thumbnail sizes and keeping thumbnails cropped proportionately instead of specific dimensions. Here is what I have in <code>functions.php</code>:</p>
<pre><code>add_image_size( 'main-thumbnail', 728, 410, true );
</code></pre>
<p>and in <code>content.php</code>:</p>
<pre><code><div class="thumbnail">
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail( 'main-thumbnail' ); ?>
</a>
</div>
</code></pre>
<p>I added these two things and regenerated my images with the <a href="https://wordpress.org/plugins/regenerate-thumbnails/" rel="nofollow noreferrer">Regenerate Thumbnails</a> plugin, but it doesn't seem to matter. The images don't change.</p>
<p>For some reason WordPress isn't recognizing the hard crop and is keeping the images proportional, so some of my images are way taller than 410 pixels. Why is this?</p>
|
[
{
"answer_id": 228410,
"author": "Steve Clason",
"author_id": 94857,
"author_profile": "https://wordpress.stackexchange.com/users/94857",
"pm_score": 0,
"selected": false,
"text": "<p>You need something like this in your functions.php file:</p>\n\n<pre><code>if( is_single()) {\n wp_enqueue_style( 'ahmedkaludi-style', get_stylesheet_uri() . '/css/plugin-styles.css' );\n}\n</code></pre>\n\n<p>Change '/css/plugin-styles.css' to the actual path of the plugin's stylesheet.</p>\n\n<p>If the plugin is written well, <code>wp_enqueue_style</code> will be wrapped in a function, like:</p>\n\n<pre><code>if ( ! function_exists( 'my_scripts' ) ) {\n function my_scripts() {\n wp_enqueue_style( 'ahmedkaludi-style', get_stylesheet_uri() . '/css/plugin-styles.css' );\n }\n add_action( 'wp_enqueue_scripts', 'steveclason_flat_scripts' );\n}\n</code></pre>\n\n<p>If that's how it's done in the plugin you can override it with a similar block of code in your theme's functions.php. We can't make very good recommendations without seeing how the plugin calls the stylesheet -- the block of code on your Pastebin does something else.</p>\n"
},
{
"answer_id": 228418,
"author": "bravokeyl",
"author_id": 43098,
"author_profile": "https://wordpress.stackexchange.com/users/43098",
"pm_score": 1,
"selected": false,
"text": "<p><strong>TL,DR;</strong></p>\n\n<p>You are hooking early.</p>\n\n<hr>\n\n<blockquote>\n <p>In the plugin, the css file loads site-wide by default, I want to load\n it only on the single post.</p>\n</blockquote>\n\n<p>It's a very good thought many developers don't take this into account while developing themes/plugins.</p>\n\n<blockquote>\n <p><strong><code>is_single()</code></strong> isn’t working in plugins</p>\n</blockquote>\n\n<p>Where are you using <strong><code>is_single</code></strong> template tag in <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow\">WP run cycle</a> ?</p>\n\n<h1>Assuming you are hooking to <strong><code>init</code></strong> or <strong><code>wp</code></strong></h1>\n\n<p>Template tags are not available yet until <strong><code>template_redirect</code></strong> action. So those tags don't work for <strong><code>init</code></strong> or <strong><code>wp</code></strong>.</p>\n\n<p>Best place to work with scripts or styles is on <strong><code>wp_enqueue_scripts</code></strong> which runs after <strong><code>template_redirect</code></strong> .</p>\n\n<blockquote>\n <p>Any idea how can we achieve that ?</p>\n</blockquote>\n\n<p>There are many ways to achieve depending on the plugin we are using. </p>\n\n<p>Coming to <strong>TablePress</strong> plugin.</p>\n\n<p><code>controllers/controller-frontend.php</code> is the place where plugin is en-queue-ing stylesheet.</p>\n\n<pre><code>if ( apply_filters( 'tablepress_use_default_css', true ) || TablePress::$model_options->get( 'use_custom_css' ) ) {\n add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_css' ) );\n}\n</code></pre>\n\n<p>You can completely turn off en-queuing the stylesheet using the <strong><code>tablepress_use_default_css</code></strong> and custom css option to false, and then load them wherever you need in your custom plugin/theme.</p>\n\n<p>If you dig through the file there are many conditional en-queuing is done for that plugin.</p>\n\n<p>You can also dequeue style first and then enqueue wherever needed.</p>\n\n<h1>Sample code</h1>\n\n<pre><code>add_action('wp_enqueue_scripts','wp_228402_load_styles_conditionally',11);\nfunction wp_228402_load_styles_conditionally() {\n if(is_single()){\n return; // return if not on the single post/page\n }\n wp_dequeue_style('tablepress-default'); \n}\n</code></pre>\n\n<p>Check the <strong>priority</strong> for the above that's the key it should be greater than default value <strong>10</strong>.</p>\n"
}
] |
2016/06/01
|
[
"https://wordpress.stackexchange.com/questions/228406",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73086/"
] |
For some reason WordPress is ignoring my thumbnail sizes and keeping thumbnails cropped proportionately instead of specific dimensions. Here is what I have in `functions.php`:
```
add_image_size( 'main-thumbnail', 728, 410, true );
```
and in `content.php`:
```
<div class="thumbnail">
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail( 'main-thumbnail' ); ?>
</a>
</div>
```
I added these two things and regenerated my images with the [Regenerate Thumbnails](https://wordpress.org/plugins/regenerate-thumbnails/) plugin, but it doesn't seem to matter. The images don't change.
For some reason WordPress isn't recognizing the hard crop and is keeping the images proportional, so some of my images are way taller than 410 pixels. Why is this?
|
**TL,DR;**
You are hooking early.
---
>
> In the plugin, the css file loads site-wide by default, I want to load
> it only on the single post.
>
>
>
It's a very good thought many developers don't take this into account while developing themes/plugins.
>
> **`is_single()`** isn’t working in plugins
>
>
>
Where are you using **`is_single`** template tag in [WP run cycle](https://codex.wordpress.org/Plugin_API/Action_Reference) ?
Assuming you are hooking to **`init`** or **`wp`**
==================================================
Template tags are not available yet until **`template_redirect`** action. So those tags don't work for **`init`** or **`wp`**.
Best place to work with scripts or styles is on **`wp_enqueue_scripts`** which runs after **`template_redirect`** .
>
> Any idea how can we achieve that ?
>
>
>
There are many ways to achieve depending on the plugin we are using.
Coming to **TablePress** plugin.
`controllers/controller-frontend.php` is the place where plugin is en-queue-ing stylesheet.
```
if ( apply_filters( 'tablepress_use_default_css', true ) || TablePress::$model_options->get( 'use_custom_css' ) ) {
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_css' ) );
}
```
You can completely turn off en-queuing the stylesheet using the **`tablepress_use_default_css`** and custom css option to false, and then load them wherever you need in your custom plugin/theme.
If you dig through the file there are many conditional en-queuing is done for that plugin.
You can also dequeue style first and then enqueue wherever needed.
Sample code
===========
```
add_action('wp_enqueue_scripts','wp_228402_load_styles_conditionally',11);
function wp_228402_load_styles_conditionally() {
if(is_single()){
return; // return if not on the single post/page
}
wp_dequeue_style('tablepress-default');
}
```
Check the **priority** for the above that's the key it should be greater than default value **10**.
|
228,426 |
<p><strong>Happy day scenario</strong>: I implement WP REST API that sends JSONs to a JavaScript client, which parses it and displays the data to the user. All is fine.</p>
<p><strong>What actually happens, inevitably</strong>: some WordPress code or plugin generates a PHP notice or warning, and the server is configured so that this garbage finds its way to the JSON response. (WP REST API <a href="https://core.trac.wordpress.org/ticket/34915" rel="nofollow">tries to avoid that</a> but for example if <code>ini_set()</code> is disallowed by server configuration, it can still happen.)</p>
<p>One way to approach is to simply blame it on the users – if their servers are configured so that they send PHP notices and warnings in production it's certainly bad. However, even the core REST infrastructure tries to support users who have badly configured servers and it's my goal as well in this case.</p>
<p>Is there a technique established for dealing with this? I can see two ways:</p>
<ol>
<li>Detect in JavaScript that the response is malformed, show some error and refuse to work.</li>
<li>Modify the actual JSON by adding some unique key to it on the server and let the JavaScript client work with that. For example, instead of the plain value <code>123</code>, it would be wrapped into an object like <code>{ "__VALID__": true, "data": 123 }</code> and the JS code would use <code>response.body.data</code> instead of <code>response.body</code>.</li>
</ol>
<p>Or is there some other approach?</p>
|
[
{
"answer_id": 228429,
"author": "AntonChanning",
"author_id": 5077,
"author_profile": "https://wordpress.stackexchange.com/users/5077",
"pm_score": -1,
"selected": false,
"text": "<p>You need to use a combination of <a href=\"https://stackoverflow.com/a/5373824/641534\">exception catching and a custom error handler</a>.</p>\n\n<p>If you use this to suppress errors to the end user, you might want to add in some method that flags the error to the administrator/developer/yourself, so you are at least aware of the issue.</p>\n\n<p>Alternatively, instead of suppressing the errors, you could return an object with both the return value, and an array of any errors, to the client. It would then be up to the client whether it did anything with that information. Whether you want to do this depends on who the clients are, and what sensitive information might be exposed by these errors. Of course you have complete control over what gets output, you don't need to just output the notices word for word. </p>\n"
},
{
"answer_id": 284120,
"author": "Ernest",
"author_id": 130383,
"author_profile": "https://wordpress.stackexchange.com/users/130383",
"pm_score": 1,
"selected": false,
"text": "<p>If you are creating classes, the first thing in the construct would be this. Or you can drop it in with an action as early as possible. Maybe plugins_loaded.</p>\n\n<pre><code>/*\n * If WP DEBUG is not on do NOT return any php warning, notices, and/or fatal errors.\n * Well If it is a fatal error then this return is FUBAR anyway...\n * We do this because some badly configured servers will return notices and warnings switch get prepended or appended to the rest response.\n */\n if( defined('WP_DEBUG') ){\n if( false === WP_DEBUG ){\n error_reporting(0);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 284126,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>You can not fix in your own plugin general problems caused by other parts of the software as there are just too many possibilities. It is the site owner's responsibility to run a clean operation if he expects to be able to use additional plugin/themes.</p>\n\n<p>The only reasonable approach that you may have is to log this kind of responses in the browser console so it will be easier for you to track down why things are not working when a plugin user complains. </p>\n"
}
] |
2016/06/01
|
[
"https://wordpress.stackexchange.com/questions/228426",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12248/"
] |
**Happy day scenario**: I implement WP REST API that sends JSONs to a JavaScript client, which parses it and displays the data to the user. All is fine.
**What actually happens, inevitably**: some WordPress code or plugin generates a PHP notice or warning, and the server is configured so that this garbage finds its way to the JSON response. (WP REST API [tries to avoid that](https://core.trac.wordpress.org/ticket/34915) but for example if `ini_set()` is disallowed by server configuration, it can still happen.)
One way to approach is to simply blame it on the users – if their servers are configured so that they send PHP notices and warnings in production it's certainly bad. However, even the core REST infrastructure tries to support users who have badly configured servers and it's my goal as well in this case.
Is there a technique established for dealing with this? I can see two ways:
1. Detect in JavaScript that the response is malformed, show some error and refuse to work.
2. Modify the actual JSON by adding some unique key to it on the server and let the JavaScript client work with that. For example, instead of the plain value `123`, it would be wrapped into an object like `{ "__VALID__": true, "data": 123 }` and the JS code would use `response.body.data` instead of `response.body`.
Or is there some other approach?
|
If you are creating classes, the first thing in the construct would be this. Or you can drop it in with an action as early as possible. Maybe plugins\_loaded.
```
/*
* If WP DEBUG is not on do NOT return any php warning, notices, and/or fatal errors.
* Well If it is a fatal error then this return is FUBAR anyway...
* We do this because some badly configured servers will return notices and warnings switch get prepended or appended to the rest response.
*/
if( defined('WP_DEBUG') ){
if( false === WP_DEBUG ){
error_reporting(0);
}
}
```
|
228,466 |
<p>I created a plugin that sets up a custom route and then loads a template file for that url. Everything works fine, except that WordPress seems to think it's a 404 even though it's correctly rendering my template.</p>
<p>For instance it says 404 in the document title and an <code>error404</code> class is added to <code><body></code></p>
<p>The custom url is domain.com/path/:id where <code>:id</code> is a dynamic value corresponding to a post id, so the URL could be domain.com/path/275. In the example below <code>some_id</code> is used as the post id variable.</p>
<p>Here's a reduced version of my plugin:</p>
<pre><code><?php
class MyPlugin {
public function __construct() {
add_action( 'init', array($this, 'add_response_endpoint') );
add_filter( 'template_include', array($this, 'add_response_template') );
}
public function add_response_endpoint() {
add_rewrite_rule(
'^path/([0-9]+)/?',
'index.php?pagename=my_custom_url&some_id=$matches[1]',
'top'
);
add_rewrite_tag('%some_id%', '([^&]+)');
}
public function add_response_template($template) {
if ( get_query_var( 'pagename' ) === 'my_custom_url' ) {
$template = trailingslashit( dirname( __FILE__ ) ) . 'templates/custom-page-template.php';
}
return $template;
}
}
new MyPlugin();
</code></pre>
<p>Am I missing something here? Or should I start looking for this bug elsewhere?</p>
|
[
{
"answer_id": 258466,
"author": "Ahrengot",
"author_id": 23829,
"author_profile": "https://wordpress.stackexchange.com/users/23829",
"pm_score": 3,
"selected": true,
"text": "<p>Manually setting <code>is_404 = false;</code> fixed my issue. However I'm not sure this is the best way to do it. I tried using the <code>pre_get_posts</code> filter instead without any luck.</p>\n\n<p>Anyway, for anyone else in the same boat, you can do this to get rid of the 404 state:</p>\n\n<pre><code>public function add_response_template($template) {\n global $wp_query;\n if ( 'my_custom_url' === get_query_var( 'pagename' ) ) {\n $wp_query->is_404 = false;\n $template = trailingslashit( dirname( __FILE__ ) ) . 'templates/custom-page-template.php';\n }\n\n return $template;\n}\n</code></pre>\n\n<p>And to update the document title (The stuff inside <code><title></code> in the <code><head></code> section) here's a snippet for making that work nicely too.</p>\n\n<pre><code>add_filter( 'document_title_parts', function($title_arr) {\n if ( 'my_custom_url' === get_query_var('pagename') ) {\n $title_arr['title'] = \"Document title for my custom route\";\n }\n\n return $title_arr;\n}, 10, 1 );\n</code></pre>\n\n<p>If anyone knows of a better way please let me know.</p>\n"
},
{
"answer_id": 380857,
"author": "2046",
"author_id": 92718,
"author_profile": "https://wordpress.stackexchange.com/users/92718",
"pm_score": 0,
"selected": false,
"text": "<p>I have not found custom routes in WP mature enough.\nI suggest you use any of the 3 routes solutions mentioned in Timber docs.\n<a href=\"https://timber.github.io/docs/v2/guides/routing/\" rel=\"nofollow noreferrer\">https://timber.github.io/docs/v2/guides/routing/</a></p>\n<p>if you use Upstatement library (<a href=\"https://github.com/Upstatement/routes\" rel=\"nofollow noreferrer\">https://github.com/Upstatement/routes</a>) you would do:</p>\n<pre><code>Routes::map('info/:name/page/:pg', function($params){\n //make a custom query based on incoming path and run it...\n $query = 'posts_per_page=3&post_type='.$params['name'].'&paged='.intval($params['pg']);\n\n //load up a template which will use that query\n Routes::load('archive.php', null, $query, 200);\n});\n</code></pre>\n<p>See the 200 in Routes::load, that sends the proper header.</p>\n<p>If you need something more versatile use Rareloop router <a href=\"https://github.com/Rareloop/router\" rel=\"nofollow noreferrer\">https://github.com/Rareloop/router</a></p>\n"
}
] |
2016/06/01
|
[
"https://wordpress.stackexchange.com/questions/228466",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23829/"
] |
I created a plugin that sets up a custom route and then loads a template file for that url. Everything works fine, except that WordPress seems to think it's a 404 even though it's correctly rendering my template.
For instance it says 404 in the document title and an `error404` class is added to `<body>`
The custom url is domain.com/path/:id where `:id` is a dynamic value corresponding to a post id, so the URL could be domain.com/path/275. In the example below `some_id` is used as the post id variable.
Here's a reduced version of my plugin:
```
<?php
class MyPlugin {
public function __construct() {
add_action( 'init', array($this, 'add_response_endpoint') );
add_filter( 'template_include', array($this, 'add_response_template') );
}
public function add_response_endpoint() {
add_rewrite_rule(
'^path/([0-9]+)/?',
'index.php?pagename=my_custom_url&some_id=$matches[1]',
'top'
);
add_rewrite_tag('%some_id%', '([^&]+)');
}
public function add_response_template($template) {
if ( get_query_var( 'pagename' ) === 'my_custom_url' ) {
$template = trailingslashit( dirname( __FILE__ ) ) . 'templates/custom-page-template.php';
}
return $template;
}
}
new MyPlugin();
```
Am I missing something here? Or should I start looking for this bug elsewhere?
|
Manually setting `is_404 = false;` fixed my issue. However I'm not sure this is the best way to do it. I tried using the `pre_get_posts` filter instead without any luck.
Anyway, for anyone else in the same boat, you can do this to get rid of the 404 state:
```
public function add_response_template($template) {
global $wp_query;
if ( 'my_custom_url' === get_query_var( 'pagename' ) ) {
$wp_query->is_404 = false;
$template = trailingslashit( dirname( __FILE__ ) ) . 'templates/custom-page-template.php';
}
return $template;
}
```
And to update the document title (The stuff inside `<title>` in the `<head>` section) here's a snippet for making that work nicely too.
```
add_filter( 'document_title_parts', function($title_arr) {
if ( 'my_custom_url' === get_query_var('pagename') ) {
$title_arr['title'] = "Document title for my custom route";
}
return $title_arr;
}, 10, 1 );
```
If anyone knows of a better way please let me know.
|
228,476 |
<p>I read a lot about the <code>require_once</code> in stackoverflow.</p>
<p>But no anwser solved my problem.</p>
<p>I've a plugin with two files.</p>
<pre><code>dmd_main.php //main file
dmd_second.php //some WP functions
</code></pre>
<p>In my main file I've included this line:</p>
<pre><code>require_once (plugin_dir_path(__FILE__) . 'includes/dmd_second.php');
</code></pre>
<p>But on my second file I still got the errormessage:</p>
<blockquote>
<p>Call to undefined function get_option()</p>
</blockquote>
<p>I read that this is the right way to work with the wordpress functions or not?</p>
<p>I've tried a lot and this code will work if I include it in my second file:</p>
<pre><code>include_once($_SERVER['DOCUMENT_ROOT'].'wp-config.php' );
</code></pre>
<p>But this solution is realy bad.</p>
<p>Can somebody explain me how I can solve this problem?</p>
<p>EDIT:</p>
<p>Code from the main file:</p>
<pre><code><?php
/**
* Plugin Name: dmd Pages
*
* @package dmd_Pages
*
* @wordpress-plugin
* Plugin URI: https://dimadirekt.de/
* Author: digitalmarketingditrekt gmbh
* Author URI: https://dimadirekt.de/
* Description: This plugin loads a list of all published pages into a menu in the adminbar. You can edit pages faster and don't need to search in the dashboard=>pages.
* Version: 1.
**/
class dmd_pages{
public function __construct(){
require_once (plugin_dir_path(__FILE__) . 'includes/saveData.php');
$this->set_actions();
}
public function set_actions(){
add_action( 'admin_enqueue_scripts', array($this, 'dmd_custom_style_load'), 99 );
add_action( 'wp_enqueue_scripts', array($this, 'dmd_enqueue_child_theme_styles'), 99);
add_action( 'admin_menu', array($this, 'dmd_register_adminmenu'));
add_action( 'wp_before_admin_bar_render', array($this, 'dmdPages'));
}
/*
* Load style for the adminbar menu
*/
public function dmd_custom_style_load() {
wp_register_style( 'dmd-pages-css-admin', plugins_url('./css/style.css', __FILE__));
wp_enqueue_style( 'dmd-pages-css-admin' );
wp_enqueue_script( 'searchbox', plugins_url('./js/jquery.hideseek.min.js', __FILE__), true);
wp_enqueue_script( 'liveAjax', plugins_url('./js/liveAjax.js', __FILE__), true);
}
public function dmd_enqueue_child_theme_styles() {
wp_register_style( 'dmd-pages-css-fe', plugins_url( './css/style.css', __FILE__ ) );
wp_enqueue_style( 'dmd-pages-css-fe' );
wp_enqueue_script( 'searchbox', plugins_url('./js/jquery.hideseek.min.js', __FILE__), true);
wp_enqueue_script( 'liveAjax', plugins_url('./js/liveAjax.js', __FILE__), true);
}
/*
* Neues Menü anlegen
*/
public function dmd_register_adminmenu() {
add_menu_page( 'DMD Pages', 'DMD Pages', 'manage_options', '/dmd-pages/admin-tpl.php', '');
}
public function dmd_get_status_option(){
$status = explode(",", get_option('dmd-pages-settings'));
return $status;
}
public function dmdPages() {
if ( !is_super_admin() || !is_admin_bar_showing() )
return;
global $wpdb;
global $wp_admin_bar;
/*
* get all posts
*/
$option = $this->dmd_get_status_option();
$querystring = 'SELECT ID, post_title, post_type FROM '.$wpdb->prefix.'posts WHERE 1=1 AND 1=2 ';
if($option[0] == 1){
$querystring .= 'UNION SELECT ID, post_title, post_type FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND post_type="post"';
}
if($option[1] == 1){
$querystring .= 'UNION SELECT ID, post_title, post_type FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND post_type="page"';
}
if($option[3] == 1){
$querystring .= 'UNION SELECT id, name as post_title, default_template as post_type FROM '.$wpdb->prefix.'frm_forms WHERE status = "published" ORDER BY post_title ASC';
}
$results = $wpdb->get_results($querystring);
/*
* Create new menu in adminbar
*/
$wp_admin_bar->add_node(array(
'id' => 'FastMenu',
'title' => 'FastMenu'
));
if($option[2] == 1){
$wp_admin_bar->add_node( array(
'id' => 'live-search',
'title' => 'live search',
'parent'=>'FastMenu',
'meta'=> array( 'html' => '<input type="text" name="search" class="search tt-query" data-list=".searchclass">','target' => '_blank', 'class' => 'dmd_livesearch' )
));
}
/*
* Create submenu in the adminbar
*/
if(isset($results))
{
foreach ($results as $post){
$site = admin_url();
$url = $site.'post.php?post='.$post->ID.'&action=edit';
switch($post->post_type){
case 'post':
$this->dmd_create_submenu($post_title = $post->post_title, $post_type = $post->post_type, $url);
break;
case 'page':
$this->dmd_create_submenu($post_title = $post->post_title, $post_type = $post->post_type, $url);
break;
}
if($post->post_type != 'page' && $post->post_type != 'post'){
$url = $site.'admin.php?page=formidable&frm_action=edit&id='.$post->ID;
$this->dmd_create_submenu($post_title = $post->post_title, $post_type = 'formidable', $url);
}
}
}
}
/*
* Funktion zum Erstellen des Submenüs
*/
public function dmd_create_submenu($post_title, $post_type, $url){
global $wp_admin_bar;
$post_type = 'dmd_'.$post_type.' searchclass';
$wp_admin_bar->add_menu( array(
'id' => $post_title,
'title' => $post_title,
'href' => $url,
'parent'=>'FastMenu',
'meta'=> array('target' => '_blank', 'class' => $post_type)
)
);
}
}
$a = new dmd_pages();
</code></pre>
<p>Code from the second file:</p>
<pre><code><?php
/*
* Include wp-config um WP Funktionen verwenden zu können
*/
//include_once($_SERVER['DOCUMENT_ROOT'].'wp-config.php' );
/*
* POSTS in Variablen abspeichern.
* Es werden die Checkboxen übergeben mittels 1 oder 0.
*/
$dmd_posts = $_POST['post'];
$dmd_pages = $_POST['page'];
$dmd_searchbox = $_POST['searchbox'];
$dmd_formidable = $_POST['formidable'];
$dmd_setting_values = $dmd_posts.','.$dmd_pages.','.$dmd_searchbox.','.$dmd_formidable;
/*
* Prüfen ob der Key vorhanden ist mittels cURL.
* Die Keydaten liegen auf einem separaten Server.
*/
function dmd_check_key($arg){
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://xxx.de/dmd-pages-pro/dmd_key_generator.php?key='.$arg.'&website='.$_SERVER['HTTP_HOST'],
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_VERBOSE => 1,
CURLOPT_SSL_VERIFYPEER => false
));
curl_setopt($curl, CURLOPT_STDERR, fopen("curl_debug.txt", "w+"));
$resp = curl_exec($curl);
curl_close($curl);
return $resp;
}
if(isset($_POST['key'])){
$x = dmd_check_key($_POST['key']);
if($x == true){
if(!get_option('dmd-pages-key-status')){add_option('dmd-pages-key-status', 'true');}else{update_option('dmd-pages-key-status', 'true');}
if(!get_option('dmd-pages-key')){add_option('dmd-pages-key', $_POST['key']);}else{update_option('dmd-pages-key', $_POST['key']);}
}
}
/*
* Die Einstellungen im WP DMD Pages Admincenter werden abgespeichert
*/
function saveMethod($dmd_setting_values){
if(!get_option('dmd-pages-settings')){
add_option('dmd-pages-settings', $dmd_setting_values);
}else{
update_option('dmd-pages-settings', $dmd_setting_values);
}
}
saveMethod($dmd_setting_values);
</code></pre>
|
[
{
"answer_id": 228496,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 0,
"selected": false,
"text": "<p>You can access the full list of available plugin updates with <a href=\"https://developer.wordpress.org/reference/functions/get_plugin_updates/\" rel=\"nofollow\"><code>get_plugin_updates()</code></a> function.</p>\n\n<p>You just need to verify if your plugin is there, then check with the versions, and the best way to output a warning in the admin endpoint is with <code>admin_notices</code> hook</p>\n\n<p>Specify your plugin name in the <code>$requested_name</code> variable (line:4)</p>\n\n<pre><code>add_action('admin_init', function() { \n\n // Specify here the plugin name\n $requested_name = 'AJAX File Upload';\n\n function se_plugin_has_update( $name ) {\n\n if ( ! function_exists( 'get_plugin_updates' ) ) {\n require_once ABSPATH . 'wp-admin/includes/update.php';\n require_once ABSPATH . 'wp-admin/includes/plugin.php';\n }\n\n $list = get_plugin_updates();\n $data = array();\n\n foreach( $list as $i => $item ) { \n if( strtolower( $name ) == strtolower( $item->Name ) ) {\n $data = $list[$i];\n }\n }\n\n if( ! empty( $data ) ) {\n\n $data = array(\n 'name' => $data->Name,\n 'version' => $data->Version,\n 'new_version' => $data->update->new_version,\n 'url' => $data->update->url,\n 'package' => $data->update->package\n );\n\n } else {\n $data = array();\n }\n\n return $data;\n\n }\n\n $update_data = se_plugin_has_update( $requested_name );\n\n // var_dump( $update_data ) or print_r( $update_data ) for debugging\n\n if( ! empty( $update_data ) ) { // has update avail\n\n // You can avoid for specific versions (current: $update_data['version'] and latest: $update_data['new_version'])\n\n $GLOBALS['se_plugin_has_update_data'] = $update_data;\n\n add_action( 'admin_notices', function() {\n\n global $se_plugin_has_update_data;\n $update_data = $se_plugin_has_update_data;\n\n ?>\n\n <div id=\"updated\" class=\"error notice is-dismissible\">\n <p><?php echo sprintf(\n \"\\\"%s\\\" plugin has updates available. You are running v. %s while the latest version is %s\",\n $update_data['name'],\n $update_data['version'],\n $update_data['new_version']\n ); ?></p>\n </div>\n\n <?php\n });\n\n }\n\n});\n</code></pre>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 228547,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": true,
"text": "<p>Not possible unless you plan in advance in your plugin for such a possibility. And even if it was somehow possible you are still not likely to have any user read the message and actually understand it.</p>\n\n<p>A more realistic approach is to do a two steps upgrade, in the first vesion of your plugin to maintain appropriate backward compatibility and only later you remove it from your code, giving both you the option to give proper notification, and the user time to adjust whatever he needs.</p>\n"
},
{
"answer_id": 325487,
"author": "KFish",
"author_id": 158938,
"author_profile": "https://wordpress.stackexchange.com/users/158938",
"pm_score": 1,
"selected": false,
"text": "<p>Being that this is over 2 years old and all, I imagine, at least I would hope, that by now the updates have rolled out and were either handled without issues or caused a bunch of breakages that then had to be fixed. For anyone reading this, I think it does a perfect job at pointing out what Mark Kaplun eluded to in the comments of the accepted answer. There are an absurd number of plugins out there for WordPress, and it is actually very common even in very popular plugins, for a developer or whole development team to just go about doing something in so much the wrong way. This is why updates so often break sites. If you're listening, please stop it, LOL.</p>\n\n<p>In this case, as revealed in the comments, the developer has a plugin that takes direct function calls from the theme, presumably not a unique theme that he has any control over and can push updates to, hence the predicament. There is a very obvious and simple solution to the problem that would have solved it cleanly, and avoided any breakages for all future versions regardless of whether or not the functions in the theme were ever updated. Not to mention, it's also very bad practice to tell your users that they have to go through ever piece of their code in their theme where they called your function and change it now, because you couldn't be bothered to handle the function update correctly. Issuing a notice to warn users about this \"required\" change to all function calls, is the completely wrong approach to solving this problem, however the developer couldn't see that. He only knew how he wanted to try to solve it, and so he asked only the question that mattered to him, and it was also the wrong question.</p>\n\n<p>Assuming the code goes something like this:</p>\n\n<pre><code>// Plugin functions\n...\n// version 0.3\npublic function get_module($id, $name){\n // code that only handles $id and $name parameters\n}\n\n// version 0.4\npublic function get_module($module){\n // code that only handles $module as an object\n}\n\n// Theme code\n$modulator = new Plugin_Class();\n$module = $modulator->get_module(21, 'My Module');\n</code></pre>\n\n<p>The real problem has nothing to do with notices or warnings to display to the user. As soon as version 0.4 pushes out, presumably everyone who's ever used this plugin will see there site break on a totally avoidable fatal error because the plugin code is now expecting an object and they are passing it an id and a name, potentially in a lot of places throughout their code, that they now have to track down and deal with because the developer didn't bother handling it correctly. The real solution should look like this:</p>\n\n<pre><code>// Plugin functions\n...\n// version 0.4\npublic function get_module_by_id($id){\n //code to retrieve and return the module object by its ID\n return $module\n}\npublic function get_module($module){\n if(!is_object($module)){\n $module = $this->get_module_by_id($module);\n }\n // now you have your module object that you need, the rest of the code should be exactly as it would have for version 0.4\n}\n\n// Theme code\n$modulator = new Plugin_Class();\n$module = $modulator->get_module(21, 'My Module');\n// Still works in every future version of the plugin, until you decide to break it another way with an update of course.\n</code></pre>\n\n<p>As I said before, there's a time and place for notices/warnings to the user, but this isn't one of them. Think before you code, your users will appreciate it even if they don't know that they do. ;-)</p>\n"
}
] |
2016/06/01
|
[
"https://wordpress.stackexchange.com/questions/228476",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78481/"
] |
I read a lot about the `require_once` in stackoverflow.
But no anwser solved my problem.
I've a plugin with two files.
```
dmd_main.php //main file
dmd_second.php //some WP functions
```
In my main file I've included this line:
```
require_once (plugin_dir_path(__FILE__) . 'includes/dmd_second.php');
```
But on my second file I still got the errormessage:
>
> Call to undefined function get\_option()
>
>
>
I read that this is the right way to work with the wordpress functions or not?
I've tried a lot and this code will work if I include it in my second file:
```
include_once($_SERVER['DOCUMENT_ROOT'].'wp-config.php' );
```
But this solution is realy bad.
Can somebody explain me how I can solve this problem?
EDIT:
Code from the main file:
```
<?php
/**
* Plugin Name: dmd Pages
*
* @package dmd_Pages
*
* @wordpress-plugin
* Plugin URI: https://dimadirekt.de/
* Author: digitalmarketingditrekt gmbh
* Author URI: https://dimadirekt.de/
* Description: This plugin loads a list of all published pages into a menu in the adminbar. You can edit pages faster and don't need to search in the dashboard=>pages.
* Version: 1.
**/
class dmd_pages{
public function __construct(){
require_once (plugin_dir_path(__FILE__) . 'includes/saveData.php');
$this->set_actions();
}
public function set_actions(){
add_action( 'admin_enqueue_scripts', array($this, 'dmd_custom_style_load'), 99 );
add_action( 'wp_enqueue_scripts', array($this, 'dmd_enqueue_child_theme_styles'), 99);
add_action( 'admin_menu', array($this, 'dmd_register_adminmenu'));
add_action( 'wp_before_admin_bar_render', array($this, 'dmdPages'));
}
/*
* Load style for the adminbar menu
*/
public function dmd_custom_style_load() {
wp_register_style( 'dmd-pages-css-admin', plugins_url('./css/style.css', __FILE__));
wp_enqueue_style( 'dmd-pages-css-admin' );
wp_enqueue_script( 'searchbox', plugins_url('./js/jquery.hideseek.min.js', __FILE__), true);
wp_enqueue_script( 'liveAjax', plugins_url('./js/liveAjax.js', __FILE__), true);
}
public function dmd_enqueue_child_theme_styles() {
wp_register_style( 'dmd-pages-css-fe', plugins_url( './css/style.css', __FILE__ ) );
wp_enqueue_style( 'dmd-pages-css-fe' );
wp_enqueue_script( 'searchbox', plugins_url('./js/jquery.hideseek.min.js', __FILE__), true);
wp_enqueue_script( 'liveAjax', plugins_url('./js/liveAjax.js', __FILE__), true);
}
/*
* Neues Menü anlegen
*/
public function dmd_register_adminmenu() {
add_menu_page( 'DMD Pages', 'DMD Pages', 'manage_options', '/dmd-pages/admin-tpl.php', '');
}
public function dmd_get_status_option(){
$status = explode(",", get_option('dmd-pages-settings'));
return $status;
}
public function dmdPages() {
if ( !is_super_admin() || !is_admin_bar_showing() )
return;
global $wpdb;
global $wp_admin_bar;
/*
* get all posts
*/
$option = $this->dmd_get_status_option();
$querystring = 'SELECT ID, post_title, post_type FROM '.$wpdb->prefix.'posts WHERE 1=1 AND 1=2 ';
if($option[0] == 1){
$querystring .= 'UNION SELECT ID, post_title, post_type FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND post_type="post"';
}
if($option[1] == 1){
$querystring .= 'UNION SELECT ID, post_title, post_type FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND post_type="page"';
}
if($option[3] == 1){
$querystring .= 'UNION SELECT id, name as post_title, default_template as post_type FROM '.$wpdb->prefix.'frm_forms WHERE status = "published" ORDER BY post_title ASC';
}
$results = $wpdb->get_results($querystring);
/*
* Create new menu in adminbar
*/
$wp_admin_bar->add_node(array(
'id' => 'FastMenu',
'title' => 'FastMenu'
));
if($option[2] == 1){
$wp_admin_bar->add_node( array(
'id' => 'live-search',
'title' => 'live search',
'parent'=>'FastMenu',
'meta'=> array( 'html' => '<input type="text" name="search" class="search tt-query" data-list=".searchclass">','target' => '_blank', 'class' => 'dmd_livesearch' )
));
}
/*
* Create submenu in the adminbar
*/
if(isset($results))
{
foreach ($results as $post){
$site = admin_url();
$url = $site.'post.php?post='.$post->ID.'&action=edit';
switch($post->post_type){
case 'post':
$this->dmd_create_submenu($post_title = $post->post_title, $post_type = $post->post_type, $url);
break;
case 'page':
$this->dmd_create_submenu($post_title = $post->post_title, $post_type = $post->post_type, $url);
break;
}
if($post->post_type != 'page' && $post->post_type != 'post'){
$url = $site.'admin.php?page=formidable&frm_action=edit&id='.$post->ID;
$this->dmd_create_submenu($post_title = $post->post_title, $post_type = 'formidable', $url);
}
}
}
}
/*
* Funktion zum Erstellen des Submenüs
*/
public function dmd_create_submenu($post_title, $post_type, $url){
global $wp_admin_bar;
$post_type = 'dmd_'.$post_type.' searchclass';
$wp_admin_bar->add_menu( array(
'id' => $post_title,
'title' => $post_title,
'href' => $url,
'parent'=>'FastMenu',
'meta'=> array('target' => '_blank', 'class' => $post_type)
)
);
}
}
$a = new dmd_pages();
```
Code from the second file:
```
<?php
/*
* Include wp-config um WP Funktionen verwenden zu können
*/
//include_once($_SERVER['DOCUMENT_ROOT'].'wp-config.php' );
/*
* POSTS in Variablen abspeichern.
* Es werden die Checkboxen übergeben mittels 1 oder 0.
*/
$dmd_posts = $_POST['post'];
$dmd_pages = $_POST['page'];
$dmd_searchbox = $_POST['searchbox'];
$dmd_formidable = $_POST['formidable'];
$dmd_setting_values = $dmd_posts.','.$dmd_pages.','.$dmd_searchbox.','.$dmd_formidable;
/*
* Prüfen ob der Key vorhanden ist mittels cURL.
* Die Keydaten liegen auf einem separaten Server.
*/
function dmd_check_key($arg){
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://xxx.de/dmd-pages-pro/dmd_key_generator.php?key='.$arg.'&website='.$_SERVER['HTTP_HOST'],
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_VERBOSE => 1,
CURLOPT_SSL_VERIFYPEER => false
));
curl_setopt($curl, CURLOPT_STDERR, fopen("curl_debug.txt", "w+"));
$resp = curl_exec($curl);
curl_close($curl);
return $resp;
}
if(isset($_POST['key'])){
$x = dmd_check_key($_POST['key']);
if($x == true){
if(!get_option('dmd-pages-key-status')){add_option('dmd-pages-key-status', 'true');}else{update_option('dmd-pages-key-status', 'true');}
if(!get_option('dmd-pages-key')){add_option('dmd-pages-key', $_POST['key']);}else{update_option('dmd-pages-key', $_POST['key']);}
}
}
/*
* Die Einstellungen im WP DMD Pages Admincenter werden abgespeichert
*/
function saveMethod($dmd_setting_values){
if(!get_option('dmd-pages-settings')){
add_option('dmd-pages-settings', $dmd_setting_values);
}else{
update_option('dmd-pages-settings', $dmd_setting_values);
}
}
saveMethod($dmd_setting_values);
```
|
Not possible unless you plan in advance in your plugin for such a possibility. And even if it was somehow possible you are still not likely to have any user read the message and actually understand it.
A more realistic approach is to do a two steps upgrade, in the first vesion of your plugin to maintain appropriate backward compatibility and only later you remove it from your code, giving both you the option to give proper notification, and the user time to adjust whatever he needs.
|
228,525 |
<p>In Visual Studio, you can easily debug your application by running Debug mode and setting breakpoints in your application.</p>
<p>In Wordpress, how would you achieve same thing?</p>
<p>I have an issue in my website and there are no error or warnings thrown. I have spent enough time tweaking settings to figure this out without luck. The only solution I've found is to set breakpoints and debug the application like in .NET.</p>
<p>I know that if you enable Debug mode in Wordpress, it prints out a gigantic debug output on top of the site - this is fine, but I just cannot debug efficiently with that.</p>
<p>Please let me know if there is any better approach for debugging WP sites in Visual Studio.</p>
|
[
{
"answer_id": 228528,
"author": "Nebri",
"author_id": 94607,
"author_profile": "https://wordpress.stackexchange.com/users/94607",
"pm_score": 4,
"selected": true,
"text": "<p>Debugging in wordpress can be a bit difficult when your first starting out, while I don't use breakpoints such as what Visual Studio offers, I can offer advice on how to debug php in general, as well as turning on the debugging output from wordpress.</p>\n\n<p>First start by opening up your wp-config.php and finding the following line. </p>\n\n<pre><code>define('WP_DEBUG', false);\n</code></pre>\n\n<p>By default this is set to false, switch out the second parameter to true. This will enable the php notices, warning, and errors messages to be displayed in your browser.</p>\n\n<p>A quick view of the <a href=\"https://codex.wordpress.org/Class_Reference/wpdb#Show_and_Hide_SQL_Errors\">Wordpress Codex</a> shows you can enable database related error messaging with a quick:</p>\n\n<pre><code><?php $wpdb->show_errors(); ?> \n<?php $wpdb->print_error(); ?> \n</code></pre>\n\n<p>Doing this will allow you to view the last sql query sent out, and any error it may have encounted back from MySql.</p>\n\n<p>Then in general when trying to figure out what's wonky about variables or data structures I find this is always helpful:</p>\n\n<pre><code><pre>\n <?php print_r($arrayOrObject);\n</pre>\n</code></pre>\n\n<p>Using the pre tags will spit out raw output without any html preformatting coming in, scrunching your view of associative arrays and objects. var_dump() functions are also useful in this way.</p>\n\n<p>When trying to debug something like a postback, ajax request and you want to get into the middle of it simply echo out the variables you are trying to debug and immediately issue a die() command, ex:</p>\n\n<pre><code>echo '<pre>';\necho var_dump($arrayOrObject);\necho '</pre>';\ndie();\n</code></pre>\n\n<p>For development enviorments I prefer using something along the lines of a WAMP stack (MAMP for mac osx off the top of my head.)</p>\n\n<p>It's definitely useful to run a local copy of your wordpress instance on your own machine, allowing you to experiment with the above techniques as required. The above mentioned troubleshooting tips have gotten me through the last 5 years of php programming and wordpress programming. Hope you find this useful!</p>\n"
},
{
"answer_id": 228563,
"author": "Boris Kuzmanov",
"author_id": 68965,
"author_profile": "https://wordpress.stackexchange.com/users/68965",
"pm_score": 3,
"selected": false,
"text": "<p>WordPress comes with it's own debugging system that is using constants, making it easy to turn on/off when you are switching environments. All constants are defined in the <code>wp-config.php</code> file.</p>\n\n<p><code>define( 'WP_DEBUG', true )</code></p>\n\n<p>Setting <strong>WP_DEBUG</strong> to true will cause all PHP errors, warnings and notices to be displayed on the screen. Also, it will throw notices about deprecated functions and arguments.</p>\n\n<p><code>define( 'WP_DEBUG_LOG', true )</code></p>\n\n<p>Enabling <strong>WP_DEBUG_LOG</strong> will save all errors in a file( <code>debug.log</code> located in /wp-content/). It is useful when debugging AJAX events.</p>\n\n<p><code>define( 'WP_DEBUG_DISPLAY', true )</code></p>\n\n<p>As an addition to the previous two constants, <strong>WP_DEBUG_DISPLAY</strong> can be used to control whether or not we want to print the errors on the page. </p>\n\n<p><code>define( 'SAVEQUERIES', true )</code></p>\n\n<p>When <strong>SAVEQUERIES</strong> is defined as true, every query that is executed will be saved. Also there are information about how long a query took to execute and what function called it. All information is stored in <code>$wpdb->queries</code>.</p>\n\n<p>Also there is a <strong>SCRIPT_DEBUG</strong> constant <code>define( 'SCRIPT_DEBUG', true)</code> which forces the WordPress to use the development versions of the core CSS and JS files, instead of the minified versions.</p>\n\n<hr>\n\n<p>Using Visual Studio (you will need PHP Tools)/PHPStorm/Eclipse, you can do debugging with Xdebug. If you are using XAMPP/MAMP, it already has Xdebug installed, so you will just need to configure it.</p>\n\n<p>Locate <code>php.ini</code> and add these two lines:</p>\n\n<pre><code>zend_extension=\"/absolute/path/to/xdebug.so\"\nxdebug.remote_enable = 1\n</code></pre>\n\n<p>There are other options that can be configured abd you can read about them in the <a href=\"https://xdebug.org/docs/all_settings\">xdebug documentation</a>. Once you finish with editing the <code>php.ini</code> file, restart your Apache server.</p>\n\n<p>The next step is to set the PHP Debugger settings in your editor. Navigate to the Settings/Preferences dialog and locate the PHP Settings.\nOnce you are done with that, you can start setting breakpoints.</p>\n"
},
{
"answer_id": 410225,
"author": "Maxwell Cheng",
"author_id": 225813,
"author_profile": "https://wordpress.stackexchange.com/users/225813",
"pm_score": 0,
"selected": false,
"text": "<p>I just succeed step debugging wordpress using <code>Eclipse IDE for PHP Developers</code>,\n<br> and <code>WAMP server</code> for running wordpress locally.<br>\nI mainly follow below guide:\n<a href=\"https://brainyloop.com/debugging-wordpress-with-eclipse-php-development-toolkit/\" rel=\"nofollow noreferrer\">https://brainyloop.com/debugging-wordpress-with-eclipse-php-development-toolkit/</a>\n<br>the tricky part is that I have to enable the step Debugger following <a href=\"https://xdebug.org/docs/remote\" rel=\"nofollow noreferrer\">https://xdebug.org/docs/remote</a>\n<br> Hope this help.</p>\n"
}
] |
2016/06/01
|
[
"https://wordpress.stackexchange.com/questions/228525",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91516/"
] |
In Visual Studio, you can easily debug your application by running Debug mode and setting breakpoints in your application.
In Wordpress, how would you achieve same thing?
I have an issue in my website and there are no error or warnings thrown. I have spent enough time tweaking settings to figure this out without luck. The only solution I've found is to set breakpoints and debug the application like in .NET.
I know that if you enable Debug mode in Wordpress, it prints out a gigantic debug output on top of the site - this is fine, but I just cannot debug efficiently with that.
Please let me know if there is any better approach for debugging WP sites in Visual Studio.
|
Debugging in wordpress can be a bit difficult when your first starting out, while I don't use breakpoints such as what Visual Studio offers, I can offer advice on how to debug php in general, as well as turning on the debugging output from wordpress.
First start by opening up your wp-config.php and finding the following line.
```
define('WP_DEBUG', false);
```
By default this is set to false, switch out the second parameter to true. This will enable the php notices, warning, and errors messages to be displayed in your browser.
A quick view of the [Wordpress Codex](https://codex.wordpress.org/Class_Reference/wpdb#Show_and_Hide_SQL_Errors) shows you can enable database related error messaging with a quick:
```
<?php $wpdb->show_errors(); ?>
<?php $wpdb->print_error(); ?>
```
Doing this will allow you to view the last sql query sent out, and any error it may have encounted back from MySql.
Then in general when trying to figure out what's wonky about variables or data structures I find this is always helpful:
```
<pre>
<?php print_r($arrayOrObject);
</pre>
```
Using the pre tags will spit out raw output without any html preformatting coming in, scrunching your view of associative arrays and objects. var\_dump() functions are also useful in this way.
When trying to debug something like a postback, ajax request and you want to get into the middle of it simply echo out the variables you are trying to debug and immediately issue a die() command, ex:
```
echo '<pre>';
echo var_dump($arrayOrObject);
echo '</pre>';
die();
```
For development enviorments I prefer using something along the lines of a WAMP stack (MAMP for mac osx off the top of my head.)
It's definitely useful to run a local copy of your wordpress instance on your own machine, allowing you to experiment with the above techniques as required. The above mentioned troubleshooting tips have gotten me through the last 5 years of php programming and wordpress programming. Hope you find this useful!
|
228,553 |
<p>I managed to add a custom option-select for images with </p>
<pre><code>function attachment_field_credit( $form_fields, $post ) {
$field_value = get_post_meta( $post->ID, 'first_image', true );
$isSelected1 = $field_value == '1' ? 'selected ' : '';
$isSelected2 = $field_value != '1' ? 'selected ' : '';
$form_fields['first_image'] = array(
'label' => __( 'Use as first image' ),
'input' => 'html',
'html' => "<select name='attachments[{$post->ID}][first_image]' id='attachments[{$post->ID}][first_image]'>
<option ".$isSelected1." value='1'>Yes</option>
<option ".$isSelected2." value='2'>No</option>
</select>"
);
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'attachment_field_credit', 10, 2 );
</code></pre>
<p>Now I need to do almost the same for links. So if I click on <code>Pages -> Add New -> Insert / Edit Link</code> I get this:</p>
<p><a href="https://i.stack.imgur.com/PtiGa.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PtiGa.png" alt="enter image description here"></a></p>
<p>Can I add another option-select field for those links? How to do that?</p>
|
[
{
"answer_id": 228559,
"author": "Capiedge",
"author_id": 39150,
"author_profile": "https://wordpress.stackexchange.com/users/39150",
"pm_score": 2,
"selected": false,
"text": "<p>Looking at the core, there's no trace of any filter or action in the <code>wp_link_dialog</code> function, which would have made your life easier...</p>\n\n<p>Investigating how others has solved this problem, there's <a href=\"https://wordpress.org/plugins/rel-nofollow-checkbox/\" rel=\"nofollow\">a plugin</a> that does more or less the same as you want. Basically it deregisters the wplink.js, <code>wp_deregister_script('wplink');</code> and registers again a modified version of the file, this time including the desired extra field.</p>\n\n<p>Although I don't think this is the best method (taking into account possible subsequent conflicts while updating WordPress), I think that it is the easiest wat to get it.</p>\n\n<p>Hope it helps!</p>\n"
},
{
"answer_id": 228564,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": true,
"text": "<p>The dialog HTML comes from <code>WP_Editors::wp_link_dialog()</code> but no hooks in there.</p>\n\n<p>We could instead use jQuery to append the custom HTML to the link dialog and try to override e.g. the <code>wpLink.getAttrs()</code>, because it's very short ;-) </p>\n\n<p>Demo example:</p>\n\n<pre><code>jQuery( document ).ready( function( $ ) {\n $('#link-options').append( \n '<div> \n <label><span>Link Class</span>\n <select name=\"wpse-link-class\" id=\"wpse_link_class\">\n <option value=\"normal\">normal</option>\n <option value=\"lightbox\">lightbox</option>\n </select>\n </label>\n </div>' );\n\n wpLink.getAttrs = function() {\n wpLink.correctURL(); \n return {\n class: $( '#wpse_link_class' ).val(),\n href: $.trim( $( '#wp-link-url' ).val() ),\n target: $( '#wp-link-target' ).prop( 'checked' ) ? '_blank' : ''\n };\n }\n});\n</code></pre>\n\n<p>I just did a quick test and it seems to work but needs further testing and adjustments when updating links. <a href=\"https://wordpress.stackexchange.com/questions/170753/modify-links-when-inserted-by-wysiwyg-editor\">Here's an old hack</a> that I did that might need a refresh.</p>\n\n<h2>Update</h2>\n\n<p>It looks like you want to add the <code>rel=\"nofollow\"</code> option to the link dialog, so let's update the above approach for that case:</p>\n\n<p>We add the <code>rel</code> link attribute with:</p>\n\n<pre><code>/**\n * Modify link attributes\n */\nwpLink.getAttrs = function() {\n wpLink.correctURL(); \n return {\n rel: $( '#wpse-rel-no-follow' ).prop( 'checked' ) ? 'nofollow' : '',\n href: $.trim( $( '#wp-link-url' ).val() ),\n target: $( '#wp-link-target' ).prop( 'checked' ) ? '_blank' : ''\n };\n}\n</code></pre>\n\n<p>If the <code>rel</code> attribute is empty, then it will be automatically removed from the link in the editor.</p>\n\n<p>Then we can hook into the <code>wplink-open</code> event that fires when the link dialog is opened. Here we can inject our custom HTML and update it according to the current link selection:</p>\n\n<pre><code>$(document).on( 'wplink-open', function( wrap ) {\n\n // Custom HTML added to the link dialog\n if( $('#wpse-rel-no-follow').length < 1 )\n $('#link-options').append( '<div> <label><span></span> <input type=\"checkbox\" id=\"wpse-rel-no-follow\"/> No Follow Link</label></div>');\n\n // Get the current link selection:\n var _node = wpse_getLink();\n\n if( _node ) {\n // Fetch the rel attribute\n var _rel = $( _node ).attr( 'rel' );\n\n // Update the checkbox\n $('#wpse-rel-no-follow').prop( 'checked', 'nofollow' === _rel );\n }\n\n});\n</code></pre>\n\n<p>where we use the following helper function, based on the <code>getLink()</code> core function, to get the HTML of the selected link:</p>\n\n<pre><code>function wpse_getLink() {\n var _ed = window.tinymce.get( window.wpActiveEditor );\n if ( _ed && ! _ed.isHidden() ) {\n return _ed.dom.getParent( _ed.selection.getNode(), 'a[href]' );\n } \n return null;\n}\n</code></pre>\n\n<p>Here's the output:</p>\n\n<p><a href=\"https://i.stack.imgur.com/LGQBo.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/LGQBo.jpg\" alt=\"no follow option\"></a></p>\n\n<p>with the following HTML:</p>\n\n<p><a href=\"https://i.stack.imgur.com/arpDO.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/arpDO.jpg\" alt=\"html\"></a></p>\n\n<p>ps: This could be tested further and might also be extended to support translations</p>\n"
},
{
"answer_id": 358201,
"author": "Roman Stone",
"author_id": 182414,
"author_profile": "https://wordpress.stackexchange.com/users/182414",
"pm_score": 2,
"selected": false,
"text": "<p>This is my simple solution, it will add an checkbox without overriding 'wplink.js'</p>\n\n<pre><code>add_action('admin_print_footer_scripts', function() {\n ?>\n <script type=\"text/javascript\">\n /* <![CDATA[ */\n (function($) {\n $(function() {\n $(document).on(\"wplink-open\", function(inputs_wrap) {\n $(\"#link-options\").append(\n $(\"<div></div>\").addClass(\"link-nofollow\").html(\n $(\"<label></label>\").html([\n $(\"<span></span>\"),\n $(\"<input></input>\").attr({\"type\": \"checkbox\", \"id\": \"wp-link-nofollow\"}),\n \"rel=\\\"nofollow\\\"\"\n ])\n )\n );\n if (wpLink && typeof(wpLink.getAttrs) == \"function\") {\n wpLink.getAttrs = function() {\n wpLink.correctURL();\n <?php /* [attention] Do not use inputs.url.val() or any input.* */ ?>\n return {\n href: $.trim( $(\"#wp-link-url\").val() ),\n target: $(\"#wp-link-target\").prop(\"checked\") ? \"_blank\" : null,\n rel: $(\"#wp-link-nofollow\").prop(\"checked\") ? \"nofollow\" : null\n };\n };\n }\n });\n });\n })(jQuery);\n /* ]]> */\n </script>\n <?php\n}, 45);\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/7qCcI.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7qCcI.jpg\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 366463,
"author": "Bhautik Nada",
"author_id": 187947,
"author_profile": "https://wordpress.stackexchange.com/users/187947",
"pm_score": 2,
"selected": false,
"text": "<p>In my case, I was looking to add the checkbox to <strong>enable 'rel=sponsored'</strong> as Google has recommended that sponsored posts be marked Sponsored now instead of No Follow from 2020.</p>\n\n<pre><code>/**\n * Custom scripts for Admin\n */\n\njQuery( document ).ready( function() {\n // Adding custom checkbox to enable sponsored link\n jQuery( '#link-options' ).append( '<div><label><span></span> <input type=\"checkbox\" id=\"wpse-rel-sponsored\"/> Sponsored Link</label></div>');\n\n // Override buildHtml function from wplink.js\n wpLink.buildHtml = function(attrs) {\n var sponsored = jQuery( '#wpse-rel-sponsored' ).prop( 'checked' ) ? true : false;\n var html = '<a href=\"' + attrs.href + '\"';\n\n if ( sponsored && attrs.target ) {\n html += ' rel=\"sponsored\" target=\"' + attrs.target + '\"'; // 'Sponsored' and 'New tab' selected\n } else if ( sponsored ) {\n html += ' rel=\"sponsored\" '; // Only 'Sponsored' selected\n } else if ( attrs.target ) {\n html += ' rel=\"noopener\" target=\"' + attrs.target + '\"'; // Only 'new tab' selected\n }\n return html + '>';\n }\n} );\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/uQT90.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uQT90.png\" alt=\"enter image description here\"></a></p>\n"
}
] |
2016/06/02
|
[
"https://wordpress.stackexchange.com/questions/228553",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57245/"
] |
I managed to add a custom option-select for images with
```
function attachment_field_credit( $form_fields, $post ) {
$field_value = get_post_meta( $post->ID, 'first_image', true );
$isSelected1 = $field_value == '1' ? 'selected ' : '';
$isSelected2 = $field_value != '1' ? 'selected ' : '';
$form_fields['first_image'] = array(
'label' => __( 'Use as first image' ),
'input' => 'html',
'html' => "<select name='attachments[{$post->ID}][first_image]' id='attachments[{$post->ID}][first_image]'>
<option ".$isSelected1." value='1'>Yes</option>
<option ".$isSelected2." value='2'>No</option>
</select>"
);
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'attachment_field_credit', 10, 2 );
```
Now I need to do almost the same for links. So if I click on `Pages -> Add New -> Insert / Edit Link` I get this:
[](https://i.stack.imgur.com/PtiGa.png)
Can I add another option-select field for those links? How to do that?
|
The dialog HTML comes from `WP_Editors::wp_link_dialog()` but no hooks in there.
We could instead use jQuery to append the custom HTML to the link dialog and try to override e.g. the `wpLink.getAttrs()`, because it's very short ;-)
Demo example:
```
jQuery( document ).ready( function( $ ) {
$('#link-options').append(
'<div>
<label><span>Link Class</span>
<select name="wpse-link-class" id="wpse_link_class">
<option value="normal">normal</option>
<option value="lightbox">lightbox</option>
</select>
</label>
</div>' );
wpLink.getAttrs = function() {
wpLink.correctURL();
return {
class: $( '#wpse_link_class' ).val(),
href: $.trim( $( '#wp-link-url' ).val() ),
target: $( '#wp-link-target' ).prop( 'checked' ) ? '_blank' : ''
};
}
});
```
I just did a quick test and it seems to work but needs further testing and adjustments when updating links. [Here's an old hack](https://wordpress.stackexchange.com/questions/170753/modify-links-when-inserted-by-wysiwyg-editor) that I did that might need a refresh.
Update
------
It looks like you want to add the `rel="nofollow"` option to the link dialog, so let's update the above approach for that case:
We add the `rel` link attribute with:
```
/**
* Modify link attributes
*/
wpLink.getAttrs = function() {
wpLink.correctURL();
return {
rel: $( '#wpse-rel-no-follow' ).prop( 'checked' ) ? 'nofollow' : '',
href: $.trim( $( '#wp-link-url' ).val() ),
target: $( '#wp-link-target' ).prop( 'checked' ) ? '_blank' : ''
};
}
```
If the `rel` attribute is empty, then it will be automatically removed from the link in the editor.
Then we can hook into the `wplink-open` event that fires when the link dialog is opened. Here we can inject our custom HTML and update it according to the current link selection:
```
$(document).on( 'wplink-open', function( wrap ) {
// Custom HTML added to the link dialog
if( $('#wpse-rel-no-follow').length < 1 )
$('#link-options').append( '<div> <label><span></span> <input type="checkbox" id="wpse-rel-no-follow"/> No Follow Link</label></div>');
// Get the current link selection:
var _node = wpse_getLink();
if( _node ) {
// Fetch the rel attribute
var _rel = $( _node ).attr( 'rel' );
// Update the checkbox
$('#wpse-rel-no-follow').prop( 'checked', 'nofollow' === _rel );
}
});
```
where we use the following helper function, based on the `getLink()` core function, to get the HTML of the selected link:
```
function wpse_getLink() {
var _ed = window.tinymce.get( window.wpActiveEditor );
if ( _ed && ! _ed.isHidden() ) {
return _ed.dom.getParent( _ed.selection.getNode(), 'a[href]' );
}
return null;
}
```
Here's the output:
[](https://i.stack.imgur.com/LGQBo.jpg)
with the following HTML:
[](https://i.stack.imgur.com/arpDO.jpg)
ps: This could be tested further and might also be extended to support translations
|
228,571 |
<p>I made a simple loop to display product base from category and brand (custom taxonomy.)</p>
<p>Here piece of my loop:</p>
<pre><code><?php
$args = array(
'post_type' => 'product',
'posts_per_page' => 4,
'orderby' => 'DESC',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'brands',
'field' => 'id',
'terms' => array($category)
),
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => array($category)
)
),
);
$wp_query = null;
$wp_query = new WP_Query( $args );?>
</code></pre>
<p>But nothing to display.
When I change </p>
<pre><code> 'relation' => 'AND', to 'relation' => 'OR',
</code></pre>
<p>The products displayed but only by brand.</p>
<p><strong>Practice with the following Nitin Singh Chouhan'S code and Champeau's suggestion, but still failed</strong></p>
<pre><code> <?php
$args = array(
'post_type' => array('post','product'),
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'terms' => array($category),
'field' => 'id'
),
array(
'taxonomy' => 'brands',
'terms' => array($categories_brands),
'field' => 'id'
),
)
);
);
$wp_query = null;
$wp_query = new WP_Query( $args );?>
<?php if ( $wp_query -> have_posts()) : ?>
<?php while ( $wp_query -> have_posts()) : $wp_query -> the_post(); ?>
<?php the_title(); ?>
<?php
endwhile;
wp_reset_query();
endif;
?>
</code></pre>
<p>Can anyone help me?</p>
<p>Thank for any kind of helps.</p>
|
[
{
"answer_id": 228578,
"author": "Champeau",
"author_id": 94714,
"author_profile": "https://wordpress.stackexchange.com/users/94714",
"pm_score": 1,
"selected": false,
"text": "<p>If I were you I would print_r($category) and make sure it is giving you ID's and not slugs. Also, you are submitting $category to both product_cat and brands.</p>\n\n<p>If your field type were slug instead of id, and terms were exactly the same in both product_cat and brands then this would work... though it doesn't make sense in the grand scheme of things.</p>\n\n<p>Your ID's are going to be unique from each taxonomy so passing $category to both taxonomies will not work.</p>\n\n<p>I hope this helped.</p>\n"
},
{
"answer_id": 231509,
"author": "Nitin Singh Chouhan",
"author_id": 97861,
"author_profile": "https://wordpress.stackexchange.com/users/97861",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to get product filter by category and brand (both) so you can add following code..</p>\n\n<pre><code>$args = array(\n 'post_type' => array('post','product'),\n 'tax_query' => array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'product_cat',\n 'terms' => 82,\n 'field' => 'id'\n ),\n array(\n 'taxonomy' => 'brand',\n 'terms' => 81,\n 'field' => 'id'\n ),\n )\n);\nquery_posts($args);\n\n if ( have_posts() ) {\n while ( have_posts() ) {\n the_post(); \n the_title(); \n } \n} \n</code></pre>\n\n<p>I hope this will be helpful for you</p>\n"
}
] |
2016/06/02
|
[
"https://wordpress.stackexchange.com/questions/228571",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89109/"
] |
I made a simple loop to display product base from category and brand (custom taxonomy.)
Here piece of my loop:
```
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => 4,
'orderby' => 'DESC',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'brands',
'field' => 'id',
'terms' => array($category)
),
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => array($category)
)
),
);
$wp_query = null;
$wp_query = new WP_Query( $args );?>
```
But nothing to display.
When I change
```
'relation' => 'AND', to 'relation' => 'OR',
```
The products displayed but only by brand.
**Practice with the following Nitin Singh Chouhan'S code and Champeau's suggestion, but still failed**
```
<?php
$args = array(
'post_type' => array('post','product'),
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'terms' => array($category),
'field' => 'id'
),
array(
'taxonomy' => 'brands',
'terms' => array($categories_brands),
'field' => 'id'
),
)
);
);
$wp_query = null;
$wp_query = new WP_Query( $args );?>
<?php if ( $wp_query -> have_posts()) : ?>
<?php while ( $wp_query -> have_posts()) : $wp_query -> the_post(); ?>
<?php the_title(); ?>
<?php
endwhile;
wp_reset_query();
endif;
?>
```
Can anyone help me?
Thank for any kind of helps.
|
If I were you I would print\_r($category) and make sure it is giving you ID's and not slugs. Also, you are submitting $category to both product\_cat and brands.
If your field type were slug instead of id, and terms were exactly the same in both product\_cat and brands then this would work... though it doesn't make sense in the grand scheme of things.
Your ID's are going to be unique from each taxonomy so passing $category to both taxonomies will not work.
I hope this helped.
|
228,579 |
<p>I have an SQL query here:</p>
<pre><code>$data_listg = $wpdb->get_results( "SELECT ID FROM " . $wpdb->prefix . "posts where post_type='post' and SUBSTR(" . $wpdb->prefix . "posts.post_title, 1, 1) LIKE '%$data' and post_status='publish' LIMIT 2" );
</code></pre>
<p>The query shows posts by first word. For example:</p>
<p>If titles start with "A" or "B" then show that post first. </p>
<ul>
<li>American hair style</li>
<li>A new Audi</li>
<li>Amazing cars</li>
<li>Alphabet </li>
</ul>
<p>or "B"</p>
<ul>
<li>B</li>
</ul>
<p>The problem is when to change:</p>
<pre><code>$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
'paged' => $paged,
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 2
);
</code></pre>
<p>How do I add that into my WP_Query <code>$args</code>?</p>
|
[
{
"answer_id": 228578,
"author": "Champeau",
"author_id": 94714,
"author_profile": "https://wordpress.stackexchange.com/users/94714",
"pm_score": 1,
"selected": false,
"text": "<p>If I were you I would print_r($category) and make sure it is giving you ID's and not slugs. Also, you are submitting $category to both product_cat and brands.</p>\n\n<p>If your field type were slug instead of id, and terms were exactly the same in both product_cat and brands then this would work... though it doesn't make sense in the grand scheme of things.</p>\n\n<p>Your ID's are going to be unique from each taxonomy so passing $category to both taxonomies will not work.</p>\n\n<p>I hope this helped.</p>\n"
},
{
"answer_id": 231509,
"author": "Nitin Singh Chouhan",
"author_id": 97861,
"author_profile": "https://wordpress.stackexchange.com/users/97861",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to get product filter by category and brand (both) so you can add following code..</p>\n\n<pre><code>$args = array(\n 'post_type' => array('post','product'),\n 'tax_query' => array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'product_cat',\n 'terms' => 82,\n 'field' => 'id'\n ),\n array(\n 'taxonomy' => 'brand',\n 'terms' => 81,\n 'field' => 'id'\n ),\n )\n);\nquery_posts($args);\n\n if ( have_posts() ) {\n while ( have_posts() ) {\n the_post(); \n the_title(); \n } \n} \n</code></pre>\n\n<p>I hope this will be helpful for you</p>\n"
}
] |
2016/06/02
|
[
"https://wordpress.stackexchange.com/questions/228579",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85340/"
] |
I have an SQL query here:
```
$data_listg = $wpdb->get_results( "SELECT ID FROM " . $wpdb->prefix . "posts where post_type='post' and SUBSTR(" . $wpdb->prefix . "posts.post_title, 1, 1) LIKE '%$data' and post_status='publish' LIMIT 2" );
```
The query shows posts by first word. For example:
If titles start with "A" or "B" then show that post first.
* American hair style
* A new Audi
* Amazing cars
* Alphabet
or "B"
* B
The problem is when to change:
```
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
'paged' => $paged,
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 2
);
```
How do I add that into my WP\_Query `$args`?
|
If I were you I would print\_r($category) and make sure it is giving you ID's and not slugs. Also, you are submitting $category to both product\_cat and brands.
If your field type were slug instead of id, and terms were exactly the same in both product\_cat and brands then this would work... though it doesn't make sense in the grand scheme of things.
Your ID's are going to be unique from each taxonomy so passing $category to both taxonomies will not work.
I hope this helped.
|
228,585 |
<p>I would like to start using the <a href="http://v2.wp-api.org/" rel="noreferrer">WordPress REST API v2</a> to query information from my site. I've noticed that when I visit an endpoint URL directly, I can see all of the data publicly. I've also seen that a lot of tutorials mention the use of test or local servers rather than live sites.</p>
<p>My questions are:</p>
<ul>
<li>Is this meant to be used on sites in production?</li>
<li>Is there a security
risk to allowing endpoints to be viewed by anyone, such as
<code>/wp-json/wp/v2/users/</code> which shows all users registered to the site?</li>
<li>Is it possible to allow only authorized users to access an endpoint?</li>
</ul>
<p>I want to make sure that I am following best practices regarding security, so any tips would be helpful. The <a href="http://v2.wp-api.org/guide/authentication/" rel="noreferrer">api docs</a> mention authentication, but I'm not sure how to prevent the URL from being accessed directly. How do others usually set up this data to be accessed by external applications without exposing too much information?</p>
|
[
{
"answer_id": 228648,
"author": "wpclevel",
"author_id": 92212,
"author_profile": "https://wordpress.stackexchange.com/users/92212",
"pm_score": 6,
"selected": true,
"text": "<blockquote>\n<p>Is this meant to be used on sites in production?</p>\n</blockquote>\n<p>Yes. <a href=\"https://make.wordpress.org/core/2015/07/23/rest-api-whos-using-this-thing/\" rel=\"nofollow noreferrer\">Many sites have been already using it</a>.</p>\n<blockquote>\n<p>Is there a security risk to allowing endpoints to be viewed by anyone, such as /wp-json/wp/v2/users/ which shows all users registered to the site?</p>\n</blockquote>\n<p>No. Server responses have nothing to do with security, nothing you can do against a blank screen or read only response.</p>\n<p>However, If your sites allow weak passwords, there're <a href=\"https://codex.wordpress.org/Brute_Force_Attacks\" rel=\"nofollow noreferrer\">some problems</a>. But it's your site's policy, REST API knows nothing about that.</p>\n<blockquote>\n<p>Is it possible to allow only authorized users to access an endpoint?</p>\n</blockquote>\n<p>Yes. You can do it by using <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#permissions-callback\" rel=\"nofollow noreferrer\">permission callback</a>.</p>\n<p>For example:</p>\n<pre><code>if ( 'edit' === $request['context'] && ! current_user_can( 'list_users' ) ) {\n return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you cannot view this resource with edit context.' ), array( 'status' => rest_authorization_required_code() ) );\n}\n</code></pre>\n<blockquote>\n<p>How do others usually set up this data to be accessed by external applications without exposing too much information?</p>\n</blockquote>\n<p>This question is hard to answer because we don't know what/when is <em>too much information</em>. But we can strictly follow <a href=\"http://v2.wp-api.org\" rel=\"nofollow noreferrer\">API references</a> and <a href=\"https://www.owasp.org/index.php/REST_Security_Cheat_Sheet\" rel=\"nofollow noreferrer\">security cheatsheets</a> to avoid unwanted situation.</p>\n"
},
{
"answer_id": 232654,
"author": "Dalton Rooney",
"author_id": 799,
"author_profile": "https://wordpress.stackexchange.com/users/799",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Is it possible to allow only authorized users to access an endpoint?</p>\n</blockquote>\n\n<p>It is possible to add a custom permission callback to your API endpoint which requires authentication to view the content. Unauthorized users will receive an error response <code>\"code\": \"rest_forbidden\"</code></p>\n\n<p>The simplest way to do this is to extend the WP_REST_Posts_Controller. Here's a very simple example of that: </p>\n\n<pre><code>class My_Private_Posts_Controller extends WP_REST_Posts_Controller {\n\n /**\n * The namespace.\n *\n * @var string\n */\n protected $namespace;\n\n /**\n * The post type for the current object.\n *\n * @var string\n */\n protected $post_type;\n\n /**\n * Rest base for the current object.\n *\n * @var string\n */\n protected $rest_base;\n\n /**\n * Register the routes for the objects of the controller.\n * Nearly the same as WP_REST_Posts_Controller::register_routes(), but with a \n * custom permission callback.\n */\n public function register_routes() {\n register_rest_route( $this->namespace, '/' . $this->rest_base, array(\n array(\n 'methods' => WP_REST_Server::READABLE,\n 'callback' => array( $this, 'get_items' ),\n 'permission_callback' => array( $this, 'get_items_permissions_check' ),\n 'args' => $this->get_collection_params(),\n 'show_in_index' => true,\n ),\n array(\n 'methods' => WP_REST_Server::CREATABLE,\n 'callback' => array( $this, 'create_item' ),\n 'permission_callback' => array( $this, 'create_item_permissions_check' ),\n 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),\n 'show_in_index' => true,\n ),\n 'schema' => array( $this, 'get_public_item_schema' ),\n ) );\n\n register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\\d]+)', array(\n array(\n 'methods' => WP_REST_Server::READABLE,\n 'callback' => array( $this, 'get_item' ),\n 'permission_callback' => array( $this, 'get_item_permissions_check' ),\n 'args' => array(\n 'context' => $this->get_context_param( array( 'default' => 'view' ) ),\n ),\n 'show_in_index' => true,\n ),\n array(\n 'methods' => WP_REST_Server::EDITABLE,\n 'callback' => array( $this, 'update_item' ),\n 'permission_callback' => array( $this, 'update_item_permissions_check' ),\n 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),\n 'show_in_index' => true,\n ),\n array(\n 'methods' => WP_REST_Server::DELETABLE,\n 'callback' => array( $this, 'delete_item' ),\n 'permission_callback' => array( $this, 'delete_item_permissions_check' ),\n 'args' => array(\n 'force' => array(\n 'default' => true,\n 'description' => __( 'Whether to bypass trash and force deletion.' ),\n ),\n ),\n 'show_in_index' => false,\n ),\n 'schema' => array( $this, 'get_public_item_schema' ),\n ) ); \n }\n\n /**\n * Check if a given request has access to get items\n *\n * @param WP_REST_Request $request Full data about the request.\n * @return WP_Error|bool\n */\n public function get_items_permissions_check( $request ) {\n return current_user_can( 'edit_posts' );\n }\n\n}\n</code></pre>\n\n<p>You'll notice that the permissions callback <code>function get_items_permissions_check</code> uses <code>current_user_can</code> to determine whether to allow access. Depending on how you're using the API, you may need to learn more about client authentication. </p>\n\n<p>You can then register your custom post type with REST API support by adding the following arguments in <code>register_post_type</code></p>\n\n<pre><code> /**\n * Register a book post type, with REST API support\n *\n * Based on example at: http://codex.wordpress.org/Function_Reference/register_post_type\n */\n add_action( 'init', 'my_book_cpt' );\n function my_book_cpt() {\n $labels = array(\n 'name' => _x( 'Books', 'post type general name', 'your-plugin-textdomain' ),\n 'singular_name' => _x( 'Book', 'post type singular name', 'your-plugin-textdomain' ),\n 'menu_name' => _x( 'Books', 'admin menu', 'your-plugin-textdomain' ),\n 'name_admin_bar' => _x( 'Book', 'add new on admin bar', 'your-plugin-textdomain' ),\n 'add_new' => _x( 'Add New', 'book', 'your-plugin-textdomain' ),\n 'add_new_item' => __( 'Add New Book', 'your-plugin-textdomain' ),\n 'new_item' => __( 'New Book', 'your-plugin-textdomain' ),\n 'edit_item' => __( 'Edit Book', 'your-plugin-textdomain' ),\n 'view_item' => __( 'View Book', 'your-plugin-textdomain' ),\n 'all_items' => __( 'All Books', 'your-plugin-textdomain' ),\n 'search_items' => __( 'Search Books', 'your-plugin-textdomain' ),\n 'parent_item_colon' => __( 'Parent Books:', 'your-plugin-textdomain' ),\n 'not_found' => __( 'No books found.', 'your-plugin-textdomain' ),\n 'not_found_in_trash' => __( 'No books found in Trash.', 'your-plugin-textdomain' )\n );\n\n $args = array(\n 'labels' => $labels,\n 'description' => __( 'Description.', 'your-plugin-textdomain' ),\n 'public' => true,\n 'publicly_queryable' => true,\n 'show_ui' => true,\n 'show_in_menu' => true,\n 'query_var' => true,\n 'rewrite' => array( 'slug' => 'book' ),\n 'capability_type' => 'post',\n 'has_archive' => true,\n 'hierarchical' => false,\n 'menu_position' => null,\n 'show_in_rest' => true,\n 'rest_base' => 'books-api',\n 'rest_controller_class' => 'My_Private_Posts_Controller',\n 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )\n );\n\n register_post_type( 'book', $args );\n}\n</code></pre>\n\n<p>You'll see <code>rest_controller_class</code> uses <code>My_Private_Posts_Controller</code> instead of the default controller.</p>\n\n<p>I've been finding it difficult to find good examples and explanations for using the REST API outside the <a href=\"http://v2.wp-api.org\" rel=\"noreferrer\">documentation</a>. I did find this great <a href=\"https://webdevstudios.com/2016/05/24/wp-api-adding-custom-endpoints/\" rel=\"noreferrer\">explanation of extending the default controller</a>, and here's a <a href=\"https://wordpress.com/read/feeds/51116770/posts/1092123881\" rel=\"noreferrer\">very thorough guide to adding endpoints</a>.</p>\n"
},
{
"answer_id": 287474,
"author": "squarecandy",
"author_id": 41488,
"author_profile": "https://wordpress.stackexchange.com/users/41488",
"pm_score": 2,
"selected": false,
"text": "<p>Here is what I have used to block all non-logged in users from using the REST API at all:</p>\n\n<pre><code>add_filter( 'rest_api_init', 'rest_only_for_authorized_users', 99 );\nfunction rest_only_for_authorized_users($wp_rest_server){\n if ( !is_user_logged_in() ) {\n wp_die('sorry you are not allowed to access this data','cheatin eh?',403);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 290452,
"author": "dipen patel",
"author_id": 116371,
"author_profile": "https://wordpress.stackexchange.com/users/116371",
"pm_score": 0,
"selected": false,
"text": "<pre><code>add_filter( 'rest_api_init', 'rest_only_for_authorized_users', 99 );\nfunction rest_only_for_authorized_users($wp_rest_server)\n{\nif( !is_user_logged_in() ) \n\n wp_die('sorry you are not allowed to access this data','Require Authentication',403);\n} } \nfunction json_authenticate_handler( $user ) {\n\nglobal $wp_json_basic_auth_error;\n\n$wp_json_basic_auth_error = null;\n\n// Don't authenticate twice\nif ( ! empty( $user ) ) {\n return $user;\n}\n\nif ( !isset( $_SERVER['PHP_AUTH_USER'] ) ) {\n return $user;\n}\n\n$username = $_SERVER['PHP_AUTH_USER'];\n$password = $_SERVER['PHP_AUTH_PW'];\n\n\nremove_filter( 'determine_current_user', 'json_authenticate_handler', 20 );\n\n$user = wp_authenticate( $username, $password );\n\nadd_filter( 'determine_current_user', 'json_authenticate_handler', 20 );\n\nif ( is_wp_error( $user ) ) {\n $wp_json_basic_auth_error = $user;\n return null;\n}\n\n$wp_json_basic_auth_error = true;\n\nreturn $user->ID;}add_filter( 'determine_current_user', 'json_authenticate_handler', 20 );\n</code></pre>\n"
},
{
"answer_id": 366240,
"author": "Josep Marxuach",
"author_id": 187760,
"author_profile": "https://wordpress.stackexchange.com/users/187760",
"pm_score": 1,
"selected": false,
"text": "<p>Best option is to disable V5 new editor and then disable API json, as explains here.</p>\n\n<p><a href=\"https://codber.com/2020/05/01/how-to-disable-wordpress-rest-api-to-not-logged-in-user-without-a-plugin/\" rel=\"nofollow noreferrer\">https://codber.com/2020/05/01/how-to-disable-wordpress-rest-api-to-not-logged-in-user-without-a-plugin/</a></p>\n"
}
] |
2016/06/02
|
[
"https://wordpress.stackexchange.com/questions/228585",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88515/"
] |
I would like to start using the [WordPress REST API v2](http://v2.wp-api.org/) to query information from my site. I've noticed that when I visit an endpoint URL directly, I can see all of the data publicly. I've also seen that a lot of tutorials mention the use of test or local servers rather than live sites.
My questions are:
* Is this meant to be used on sites in production?
* Is there a security
risk to allowing endpoints to be viewed by anyone, such as
`/wp-json/wp/v2/users/` which shows all users registered to the site?
* Is it possible to allow only authorized users to access an endpoint?
I want to make sure that I am following best practices regarding security, so any tips would be helpful. The [api docs](http://v2.wp-api.org/guide/authentication/) mention authentication, but I'm not sure how to prevent the URL from being accessed directly. How do others usually set up this data to be accessed by external applications without exposing too much information?
|
>
> Is this meant to be used on sites in production?
>
>
>
Yes. [Many sites have been already using it](https://make.wordpress.org/core/2015/07/23/rest-api-whos-using-this-thing/).
>
> Is there a security risk to allowing endpoints to be viewed by anyone, such as /wp-json/wp/v2/users/ which shows all users registered to the site?
>
>
>
No. Server responses have nothing to do with security, nothing you can do against a blank screen or read only response.
However, If your sites allow weak passwords, there're [some problems](https://codex.wordpress.org/Brute_Force_Attacks). But it's your site's policy, REST API knows nothing about that.
>
> Is it possible to allow only authorized users to access an endpoint?
>
>
>
Yes. You can do it by using [permission callback](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#permissions-callback).
For example:
```
if ( 'edit' === $request['context'] && ! current_user_can( 'list_users' ) ) {
return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you cannot view this resource with edit context.' ), array( 'status' => rest_authorization_required_code() ) );
}
```
>
> How do others usually set up this data to be accessed by external applications without exposing too much information?
>
>
>
This question is hard to answer because we don't know what/when is *too much information*. But we can strictly follow [API references](http://v2.wp-api.org) and [security cheatsheets](https://www.owasp.org/index.php/REST_Security_Cheat_Sheet) to avoid unwanted situation.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.